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
// Set Upgrade Base Price /
function setUpgradeBasePrice(uint256 price) external onlyRole(MANAGER_ROLE)
function setUpgradeBasePrice(uint256 price) external onlyRole(MANAGER_ROLE)
8,882
125
// function to set tokens for the sale/self Stored Crowdsale from crowdsale contract/ return true if tokens set successfully
function setTokens(CrowdsaleStorage storage self) public returns (bool) { require(msg.sender == self.owner); require(!self.tokensSet); require(now < self.endTime); uint256 _tokenBalance; _tokenBalance = self.token.balanceOf(this); self.withdrawTokensMap[msg.sender] = _tokenBalance; self.startingTokenBalance = _tokenBalance; self.tokensSet = true; return true; }
function setTokens(CrowdsaleStorage storage self) public returns (bool) { require(msg.sender == self.owner); require(!self.tokensSet); require(now < self.endTime); uint256 _tokenBalance; _tokenBalance = self.token.balanceOf(this); self.withdrawTokensMap[msg.sender] = _tokenBalance; self.startingTokenBalance = _tokenBalance; self.tokensSet = true; return true; }
13,397
18
// ------------------------------------------------------------------------ Get the token balance for account tokenOwner ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; }
function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; }
6,890
11
// but there is no harm if they do, then just allow them towithdraw so long as debt< 0
require(IERC20(_debtToken).transferFrom(msg.sender, address(this), amount)); vaults[msg.sender].debtAmount -= amount; _debtReserveBalance += amount; uint256 periodsElapsed = (block.timestamp / _period) - (vaults[msg.sender].createdAt / _period); vaults[msg.sender].createdAt += periodsElapsed * _period; emit VaultRepay(msg.sender, amount);
require(IERC20(_debtToken).transferFrom(msg.sender, address(this), amount)); vaults[msg.sender].debtAmount -= amount; _debtReserveBalance += amount; uint256 periodsElapsed = (block.timestamp / _period) - (vaults[msg.sender].createdAt / _period); vaults[msg.sender].createdAt += periodsElapsed * _period; emit VaultRepay(msg.sender, amount);
43,668
13
// Emitted when settling a trader's funding payment/trader The address of trader/baseToken The address of virtual base token(ETH, BTC, etc...)/fundingPayment The fundingPayment of trader on baseToken market, > 0: payment, < 0 : receipt
event FundingPaymentSettled(address indexed trader, address indexed baseToken, int256 fundingPayment);
event FundingPaymentSettled(address indexed trader, address indexed baseToken, int256 fundingPayment);
8,417
52
// remove from play and put up for sale, delete entries during _open
entryOwners[entries[i]] = address(this);
entryOwners[entries[i]] = address(this);
7,094
49
// Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses. /
function activateSafeMode() external onlySigner { safeMode = true; emit SafeModeActivated(msg.sender); }
function activateSafeMode() external onlySigner { safeMode = true; emit SafeModeActivated(msg.sender); }
48,414
60
// sending Eth to Treasury
if (ethForTreasury > 0) { payable(treasury).transfer(ethForTreasury); }
if (ethForTreasury > 0) { payable(treasury).transfer(ethForTreasury); }
20,162
138
// the fuse comptroller
Unitroller public immutable comptroller;
Unitroller public immutable comptroller;
44,373
12
// check imbalance
int totalImbalance; int blockImbalance; (totalImbalance, blockImbalance) = getImbalance(token, updateRateBlock, currentBlockNumber);
int totalImbalance; int blockImbalance; (totalImbalance, blockImbalance) = getImbalance(token, updateRateBlock, currentBlockNumber);
34,275
23
// This strut is just to avoid "stak too deep" error
struct payInput
struct payInput
910
125
// Updates current amount of stake to apply compounding interest/This applies all of your earned interest to future payout calculations/a_nStakeIndex index of stake to compound interest for
function CompoundInterest( uint256 a_nStakeIndex ) external
function CompoundInterest( uint256 a_nStakeIndex ) external
31,197
353
// Get reward addresses extraRewardCount Extra reward countreturn Reward addresses /
function _getRewardAddresses(uint256 extraRewardCount) private view returns(address[] memory) { address[] memory rewardAddresses = new address[](extraRewardCount + BASE_REWARDS_COUNT); rewardAddresses[0] = address(rewardToken); rewardAddresses[1] = address(cvxToken); for (uint256 i = 0; i < extraRewardCount; i++) { rewardAddresses[i + BASE_REWARDS_COUNT] = address(crvRewards.extraReward(i)); } return rewardAddresses; }
function _getRewardAddresses(uint256 extraRewardCount) private view returns(address[] memory) { address[] memory rewardAddresses = new address[](extraRewardCount + BASE_REWARDS_COUNT); rewardAddresses[0] = address(rewardToken); rewardAddresses[1] = address(cvxToken); for (uint256 i = 0; i < extraRewardCount; i++) { rewardAddresses[i + BASE_REWARDS_COUNT] = address(crvRewards.extraReward(i)); } return rewardAddresses; }
65,270
401
// bidCount: currectBidCount.add(1),
bidder: msg.sender, price: _priceInWei, expiresAt: _expiresAt
bidder: msg.sender, price: _priceInWei, expiresAt: _expiresAt
45,463
181
// ========== MUTATIVE FUNCTIONS ========== / totalIssuedSynths checks synths for staleness check det rate is not stale
function flagAccountForLiquidation(address account) external rateNotInvalid("DET")
function flagAccountForLiquidation(address account) external rateNotInvalid("DET")
13,796
593
// Updates the active vault.// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts/ is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized.//_adapter the adapter for the new active vault.
function _updateActiveVault(IVaultAdapterV2 _adapter) internal { require(_adapter != IVaultAdapterV2(ZERO_ADDRESS), "YumIdleVault: active vault address cannot be 0x0."); require(_adapter.token() == token, "YumIdleVault: token mismatch."); _vaults.push(VaultV2.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); }
function _updateActiveVault(IVaultAdapterV2 _adapter) internal { require(_adapter != IVaultAdapterV2(ZERO_ADDRESS), "YumIdleVault: active vault address cannot be 0x0."); require(_adapter.token() == token, "YumIdleVault: token mismatch."); _vaults.push(VaultV2.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); }
21,019
31
// Returns the cached LendingPoolAddressesProvider connected to this contract /
function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; }
function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; }
15,929
11
// allow another account/contract to spend some coins on your behalf also, to minimize the risk of the approve/transferFrom attack vector, approve has to be called twice in 2 separate transactions -once to change the allowance to 0 and secondly to change it to the new allowance value
function approve(address _spender, uint256 _value) validAddress(_spender) returns (bool success) { // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
function approve(address _spender, uint256 _value) validAddress(_spender) returns (bool success) { // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
10,537
173
// 不包含FToken的流动性/
{ IFToken fToken = IFToken(getFTokeAddress(token)); (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( account, fToken, fToken.balanceOf(account), //用户的fToken数量 0 ); // These are safe, as the underflow condition is checked first if (sumCollaterals > sumBorrows) { return (sumCollaterals - sumBorrows, 0); } else { return (0, sumBorrows - sumCollaterals); } }
{ IFToken fToken = IFToken(getFTokeAddress(token)); (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( account, fToken, fToken.balanceOf(account), //用户的fToken数量 0 ); // These are safe, as the underflow condition is checked first if (sumCollaterals > sumBorrows) { return (sumCollaterals - sumBorrows, 0); } else { return (0, sumBorrows - sumCollaterals); } }
14,633
397
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
15,881
212
// Approve transfer of all available tokens _token token address /
function approveAll(address _token) public { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); require(cToken != address(0x0), "cToken address is zero"); IERC20(_token).safeApprove(cToken, 0); IERC20(_token).safeApprove(cToken, uint256(-1)); }
function approveAll(address _token) public { address cToken = globalConfig.tokenInfoRegistry().getCToken(_token); require(cToken != address(0x0), "cToken address is zero"); IERC20(_token).safeApprove(cToken, 0); IERC20(_token).safeApprove(cToken, uint256(-1)); }
15,072
7
// check erc20 balance and allowance
require(taleToken.balanceOf(staker) >= amount, "TaleStaking: Insufficient tokens"); require(taleToken.allowance(staker, address(this)) >= amount, "TaleStaking: Not enough tokens allowed"); uint stakingId = stakers[staker].stakingNumber; stakers[staker].stakingNumber = stakingId + 1; stakers[staker].stakings[stakingId] = Staking(block.timestamp, amount, 0, targetLevel, StakingLevel.SIMPLE, false, true); stakers[staker].activeStakings[stakingId] = true; totalStaked += amount; taleToken.safeTransferFrom(staker, address(this), amount);
require(taleToken.balanceOf(staker) >= amount, "TaleStaking: Insufficient tokens"); require(taleToken.allowance(staker, address(this)) >= amount, "TaleStaking: Not enough tokens allowed"); uint stakingId = stakers[staker].stakingNumber; stakers[staker].stakingNumber = stakingId + 1; stakers[staker].stakings[stakingId] = Staking(block.timestamp, amount, 0, targetLevel, StakingLevel.SIMPLE, false, true); stakers[staker].activeStakings[stakingId] = true; totalStaked += amount; taleToken.safeTransferFrom(staker, address(this), amount);
35,852
4
// CONSTANTS // STORAGE /
struct Token { address owner; uint256 price; }
struct Token { address owner; uint256 price; }
32,975
8
// INTERNAL //At this moment staking is only possible from a certain address (usually a smart contract). This is because in almost all cases you want another contract to perform custom logic on lock and unlock operations,without allowing users to directly unlock their tokens and sell them, for example. /
function _lock(uint256 tokenId) internal virtual { require(!lockedTokens.get(tokenId), "ERC721/ALREADY_LOCKED"); lockedTokens.set(tokenId); }
function _lock(uint256 tokenId) internal virtual { require(!lockedTokens.get(tokenId), "ERC721/ALREADY_LOCKED"); lockedTokens.set(tokenId); }
2,085
8
// total amount in subscription
uint256 amount;
uint256 amount;
45,156
5
// Maximum cap per purchaser on public sale ~ $20,000 in GDPR
uint256 public constant PURCHASER_MAX_TOKEN_CAP = 100000 * MIN_TOKEN_UNIT;
uint256 public constant PURCHASER_MAX_TOKEN_CAP = 100000 * MIN_TOKEN_UNIT;
11,528
42
// transfer to reserve owner failed
ErrorReport( tx.origin, 0x860000001, uint(token) ); return false;
ErrorReport( tx.origin, 0x860000001, uint(token) ); return false;
27,045
4
// Map from an account and uid for a claim condition, to the last timestampat which the account claimed tokens under that claim condition. /
mapping(bytes32 => mapping(address => uint256)) private lastClaimTimestamp;
mapping(bytes32 => mapping(address => uint256)) private lastClaimTimestamp;
10,037
137
// Withdraws the beneficiary's funds. /
function beneficiaryWithdraw() public { require(_state == State.Closed, "RefundEscrow: beneficiary can only withdraw while closed"); _beneficiary.transfer(address(this).balance); }
function beneficiaryWithdraw() public { require(_state == State.Closed, "RefundEscrow: beneficiary can only withdraw while closed"); _beneficiary.transfer(address(this).balance); }
35,425
4
// done so that if any one tries to dump eth into this contract, we can just forward it to corp bank.
currentCorpBank_.deposit.value(address(this).balance)(address(currentCorpBank_));
currentCorpBank_.deposit.value(address(this).balance)(address(currentCorpBank_));
40,725
27
// An event that's emitted when a new burn is accepted
event BurnAccepted(uint256 indexed amount, address indexed source, uint256 oldSupply, uint256 newSupply);
event BurnAccepted(uint256 indexed amount, address indexed source, uint256 oldSupply, uint256 newSupply);
9,078
3
// Destroy tokens Remove `_value` tokens from the system irreversibly_value the amount of money to burn/
// function burn(uint256 _value) public returns (bool) { // burnFrom(msg.sender, _value); // }
// function burn(uint256 _value) public returns (bool) { // burnFrom(msg.sender, _value); // }
53,204
1
// networks
uint constant NETWORK_TESTNET = 1; uint constant NETWORK_MAINNET = 2;
uint constant NETWORK_TESTNET = 1; uint constant NETWORK_MAINNET = 2;
26,306
77
// mapping of user address to history of Stake objects every user action creates a new object in the history
mapping(address => Stake[]) userStakeHistory;
mapping(address => Stake[]) userStakeHistory;
31,454
4
// Sets contract operations on/off When operational mode is disabled, all write transactions except for this one will fail /
function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; }
function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; }
36,464
2
// assert(b > 0);Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == bc + a % b);There is no case in which this doesn't hold
return a / b;
return a / b;
7,819
185
// Return EpochManager interfacereturn Epoch manager contract registered with Controller /
function epochManager() internal view returns (IEpochManager) { return IEpochManager(controller.getContractProxy(keccak256("EpochManager"))); }
function epochManager() internal view returns (IEpochManager) { return IEpochManager(controller.getContractProxy(keccak256("EpochManager"))); }
84,296
5
// Oracle, jobId, and fee for getting bytes32
address public oracleBytes32 = 0x56dd6586DB0D08c6Ce7B2f2805af28616E082455; bytes32 public jobIdBytes32 = "c128fbb0175442c8ba828040fdd1a25e"; uint256 public feeBytes32 = 0.1 * 10 ** 18;
address public oracleBytes32 = 0x56dd6586DB0D08c6Ce7B2f2805af28616E082455; bytes32 public jobIdBytes32 = "c128fbb0175442c8ba828040fdd1a25e"; uint256 public feeBytes32 = 0.1 * 10 ** 18;
30,683
324
// Add liquidity to the pool
(uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity,
(uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity,
21,645
102
// check output via tokenA -> weth -> tokenB
if ((_from != wethTokenAddress) && _to != wethTokenAddress) { address[] memory pathB = new address[](3); pathB[0] = _from; pathB[1] = wethTokenAddress; pathB[2] = _to; amtB = uniswapRouter.getAmountsOut(_amt, pathB)[2]; }
if ((_from != wethTokenAddress) && _to != wethTokenAddress) { address[] memory pathB = new address[](3); pathB[0] = _from; pathB[1] = wethTokenAddress; pathB[2] = _to; amtB = uniswapRouter.getAmountsOut(_amt, pathB)[2]; }
65,442
275
// Combines logic of requestPrice and proposePrice while taking advantage of gas savings from not having tooverwrite Request params that a normal requestPrice() => proposePrice() flow would entail. Note: The proposerwill receive any rewards that come from this proposal. However, any bonds are pulled from the caller. The caller is the requester, but the proposer can be customized. identifier price identifier to identify the existing request. timestamp timestamp to identify the existing request. ancillaryData ancillary data of the price being requested. currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. reward reward
function requestAndProposePriceFor(
function requestAndProposePriceFor(
12,885
27
// Gold = BTC
uint8 public decimals = 9;
uint8 public decimals = 9;
25,711
102
// account for deposit
uint value = treasury.valueOf( token, amount ); accountingFor( token, amount, value, true ); IERC20(token).approve(address(curve3Pool), amount); // approve curve pool to spend tokens uint curveAmount = curve3Pool.add_liquidity(curveToken, amounts, minAmount); // deposit into curve IERC20( curveToken ).approve( address(booster), curveAmount ); // approve to deposit to convex booster.deposit( pidForReserve[ token ], curveAmount, true ); // deposit into convex
uint value = treasury.valueOf( token, amount ); accountingFor( token, amount, value, true ); IERC20(token).approve(address(curve3Pool), amount); // approve curve pool to spend tokens uint curveAmount = curve3Pool.add_liquidity(curveToken, amounts, minAmount); // deposit into curve IERC20( curveToken ).approve( address(booster), curveAmount ); // approve to deposit to convex booster.deposit( pidForReserve[ token ], curveAmount, true ); // deposit into convex
23,776
3
// pass the name of NFTs token and its symbol.
constructor() ERC721 ("USurfNFT", "SURF") { console.log("This is my NFT contract. Woah!"); }
constructor() ERC721 ("USurfNFT", "SURF") { console.log("This is my NFT contract. Woah!"); }
8,882
197
// require that there are cats left to be rescued
require(remainingCats > 0, "no cats left");
require(remainingCats > 0, "no cats left");
10,985
3
// ballot settings
uint16 constant IS_BINDING = 8192; // 2^13 uint16 constant IS_OFFICIAL = 16384; // 2^14 uint16 constant USE_TESTING = 32768; // 2^15
uint16 constant IS_BINDING = 8192; // 2^13 uint16 constant IS_OFFICIAL = 16384; // 2^14 uint16 constant USE_TESTING = 32768; // 2^15
37,362
0
// maybe DEPOSIT and MAP_TOKEN can be reduced to bytes4
bytes32 public constant DEPOSIT = keccak256("DEPOSIT"); bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN"); event TokenMappedERC721(address indexed rootToken, address indexed childToken); event FxWithdrawERC721(address indexed rootToken, address indexed childToken, address indexed userAddress, uint256 id); event FxDepositERC721(address indexed rootToken, address indexed depositor, address indexed userAddress, uint256 id); mapping(address => address) public rootToChildTokens; bytes32 public childTokenTemplateCodeHash;
bytes32 public constant DEPOSIT = keccak256("DEPOSIT"); bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN"); event TokenMappedERC721(address indexed rootToken, address indexed childToken); event FxWithdrawERC721(address indexed rootToken, address indexed childToken, address indexed userAddress, uint256 id); event FxDepositERC721(address indexed rootToken, address indexed depositor, address indexed userAddress, uint256 id); mapping(address => address) public rootToChildTokens; bytes32 public childTokenTemplateCodeHash;
66,476
81
// Decreases the allowance granted by the sender to `spender` by `value`. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Reverts if `spender` is the zero address. Reverts if `spender` has an allowance with the message caller for less than `value`. Emits an {IERC20-Approval} event with an updated allowance for `spender`. spender The account whose allowance is being decreased by the message caller. value The allowance amount decrease.return True if the allowance decrease succeeds, false otherwise. /
function decreaseAllowance(address spender, uint256 value) external returns (bool);
function decreaseAllowance(address spender, uint256 value) external returns (bool);
39,004
3
// See {IEIP2981RoyaltyOverride-setDefaultRoyalty}. /
function setDefaultRoyalty(TokenRoyalty calldata royalty) external override onlyOwner { _setDefaultRoyalty(royalty); }
function setDefaultRoyalty(TokenRoyalty calldata royalty) external override onlyOwner { _setDefaultRoyalty(royalty); }
12,477
82
// Used to add new symbol to the bytes array
function _addHorse(bytes32 newHorse) internal { all_horses.push(newHorse); }
function _addHorse(bytes32 newHorse) internal { all_horses.push(newHorse); }
27,368
1
// sets the owner to sender
constructor(address _owner) { owner = _owner; }
constructor(address _owner) { owner = _owner; }
45,051
110
// Call account `target`, supplying value `amount` and data `data`.Only the owner may call this function. target address The account to call. amount uint256 The amount of ether to include as an endowment. data bytes The data to include along with the call.return A boolean to indicate if the call was successful, as well as thereturned data or revert reason. /
function callAny( address payable target, uint256 amount, bytes calldata data
function callAny( address payable target, uint256 amount, bytes calldata data
43,151
21
// Swap tokenOut tokenIn on separate DEX
uint256[] memory amountsTokenOut = _router.swapExactTokensForTokens(tokenAmountOut, amountIn, path, address(this), deadline);
uint256[] memory amountsTokenOut = _router.swapExactTokensForTokens(tokenAmountOut, amountIn, path, address(this), deadline);
32,658
26
// converts the data data: data int value in array inBits: inBits outBits: outBits /
function convert( uint256[] memory data, uint256 inBits, uint256 outBits
function convert( uint256[] memory data, uint256 inBits, uint256 outBits
15,372
233
// Safe tap transfer function, just in case if rounding error causes pool to not have enough TAPs.
function safeTapTransfer(address _to, uint256 _amount) internal { uint256 tapBal = tap.balanceOf(address(this)); if (_amount > tapBal) { tap.transfer(_to, tapBal); } else { tap.transfer(_to, _amount); } }
function safeTapTransfer(address _to, uint256 _amount) internal { uint256 tapBal = tap.balanceOf(address(this)); if (_amount > tapBal) { tap.transfer(_to, tapBal); } else { tap.transfer(_to, _amount); } }
15,517
124
// VSCToken is a VOWToken with:- a linked parent Vow token- tier 1 burn (with owner aproved exceptions)- tier 2 delegated lifting (only by owner approved contracts) /
contract VSCToken is VOWToken { using SafeMath for uint256; address public immutable vowContract; mapping(address => bool) public canLift; mapping(address => bool) public skipTier1Burn; uint256[2] public tier1BurnVSC; event LogTier1BurnVSCUpdated(uint256[2] ratio); event LogLiftPermissionSet(address indexed liftingAddress, bool canLift); event LogSkipTier1BurnSet(address indexed skipTier1BurnAddress, bool skipTier1Burn); constructor(string memory _name, string memory _symbol, uint256[2] memory _initialVSCUSD, address _vowContract) VOWToken(_name, _symbol, 0, _initialVSCUSD) public { vowContract = _vowContract; ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC777_TOKENS_RECIPIENT_HASH, address(this)); tier1BurnVSC = [0, 1]; // Default to no burn: ie burn 0 VSC for every 1 VSC sent on tier 1 setSkipTier1Burn(address(this), true); } modifier onlyLifter() { require(canLift[msg.sender], "onlyLifter"); _; } function setLiftPermission(address _liftingAddress, bool _canLift) external onlyOwner addressNotNull(_liftingAddress) { canLift[_liftingAddress] = _canLift; emit LogLiftPermissionSet(_liftingAddress, _canLift); } function setTier1BurnVSC(uint256 _numVSCBurned, uint256 _numVSCSent) external onlyOwner { require(_numVSCSent != 0, "Invalid burn ratio: div by zero"); require(_numVSCSent >= _numVSCBurned, "Invalid burn ratio: above 100%"); tier1BurnVSC = [_numVSCBurned, _numVSCSent]; emit LogTier1BurnVSCUpdated(tier1BurnVSC); } function lift(address _liftAccount, uint256 _amount, bytes calldata _data) external onlyLifter { address tier2ScalingManager = partnerContracts[keccak256(abi.encodePacked("FTScalingManager"))]; this.operatorSend(_liftAccount, tier2ScalingManager, _amount , _data, ""); } function setSkipTier1Burn(address _skipTier1BurnAddress, bool _skipTier1Burn) public onlyOwner addressNotNull(_skipTier1BurnAddress) { skipTier1Burn[_skipTier1BurnAddress] = _skipTier1Burn; emit LogSkipTier1BurnSet(_skipTier1BurnAddress, _skipTier1Burn); } function doSend(address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _enforceERC777) internal virtual override { uint256 actualSendAmount = _amount; if (!skipTier1Burn[_from] && !skipTier1Burn[_to]) { uint256 burnAmount = _amount.mul(tier1BurnVSC[0]).div(tier1BurnVSC[1]); doBurn(_operator, _from, burnAmount, _data, _operatorData); actualSendAmount = actualSendAmount.sub(burnAmount); } super.doSend(_operator, _from, _to, actualSendAmount, _data, _operatorData, _enforceERC777); } }
contract VSCToken is VOWToken { using SafeMath for uint256; address public immutable vowContract; mapping(address => bool) public canLift; mapping(address => bool) public skipTier1Burn; uint256[2] public tier1BurnVSC; event LogTier1BurnVSCUpdated(uint256[2] ratio); event LogLiftPermissionSet(address indexed liftingAddress, bool canLift); event LogSkipTier1BurnSet(address indexed skipTier1BurnAddress, bool skipTier1Burn); constructor(string memory _name, string memory _symbol, uint256[2] memory _initialVSCUSD, address _vowContract) VOWToken(_name, _symbol, 0, _initialVSCUSD) public { vowContract = _vowContract; ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC777_TOKENS_RECIPIENT_HASH, address(this)); tier1BurnVSC = [0, 1]; // Default to no burn: ie burn 0 VSC for every 1 VSC sent on tier 1 setSkipTier1Burn(address(this), true); } modifier onlyLifter() { require(canLift[msg.sender], "onlyLifter"); _; } function setLiftPermission(address _liftingAddress, bool _canLift) external onlyOwner addressNotNull(_liftingAddress) { canLift[_liftingAddress] = _canLift; emit LogLiftPermissionSet(_liftingAddress, _canLift); } function setTier1BurnVSC(uint256 _numVSCBurned, uint256 _numVSCSent) external onlyOwner { require(_numVSCSent != 0, "Invalid burn ratio: div by zero"); require(_numVSCSent >= _numVSCBurned, "Invalid burn ratio: above 100%"); tier1BurnVSC = [_numVSCBurned, _numVSCSent]; emit LogTier1BurnVSCUpdated(tier1BurnVSC); } function lift(address _liftAccount, uint256 _amount, bytes calldata _data) external onlyLifter { address tier2ScalingManager = partnerContracts[keccak256(abi.encodePacked("FTScalingManager"))]; this.operatorSend(_liftAccount, tier2ScalingManager, _amount , _data, ""); } function setSkipTier1Burn(address _skipTier1BurnAddress, bool _skipTier1Burn) public onlyOwner addressNotNull(_skipTier1BurnAddress) { skipTier1Burn[_skipTier1BurnAddress] = _skipTier1Burn; emit LogSkipTier1BurnSet(_skipTier1BurnAddress, _skipTier1Burn); } function doSend(address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _enforceERC777) internal virtual override { uint256 actualSendAmount = _amount; if (!skipTier1Burn[_from] && !skipTier1Burn[_to]) { uint256 burnAmount = _amount.mul(tier1BurnVSC[0]).div(tier1BurnVSC[1]); doBurn(_operator, _from, burnAmount, _data, _operatorData); actualSendAmount = actualSendAmount.sub(burnAmount); } super.doSend(_operator, _from, _to, actualSendAmount, _data, _operatorData, _enforceERC777); } }
2,493
40
// Set King
king = msg.sender; players[king].roundLastPlayed = round; crownedTime = now; NewKingBid(now, king, msg.value, mainPot, bonusPot);
king = msg.sender; players[king].roundLastPlayed = round; crownedTime = now; NewKingBid(now, king, msg.value, mainPot, bonusPot);
22,079
200
// claim wpc. every can call this function, but transfer token to
function claim() public { uint256 piggyBal = piggy.balanceOf(address(this)); for (uint256 i = 0; i < fundingHolders.length; i++) { FundingHolderInfo storage fhi = fundingHolders[i]; uint _amount = piggyBal.mul(fhi.ratio).div(100); safePiggyTransfer(fhi.addr, _amount); } }
function claim() public { uint256 piggyBal = piggy.balanceOf(address(this)); for (uint256 i = 0; i < fundingHolders.length; i++) { FundingHolderInfo storage fhi = fundingHolders[i]; uint _amount = piggyBal.mul(fhi.ratio).div(100); safePiggyTransfer(fhi.addr, _amount); } }
517
18
// The method of accepting payments, if a zero payment has come, then we start the procedure for refundingthe interest on the deposit, if the payment is not empty, we record the number of broadcasts on the contractand the payment time /
function createDeposit() private{ if(msg.value > 0){ if (balances[msg.sender] == 0){ emit NewInvestor(msg.sender, msg.value); allBeneficiaries+=1; } if(getDepositMultiplier() > 0 && now >= time[msg.sender].add(dividendsTime) ){ receivePayment(); } balances[msg.sender] = balances[msg.sender].add(msg.value); time[msg.sender] = now; allDeposits+=msg.value; emit NewDeposit(msg.sender, msg.value); }else{ receivePayment(); } }
function createDeposit() private{ if(msg.value > 0){ if (balances[msg.sender] == 0){ emit NewInvestor(msg.sender, msg.value); allBeneficiaries+=1; } if(getDepositMultiplier() > 0 && now >= time[msg.sender].add(dividendsTime) ){ receivePayment(); } balances[msg.sender] = balances[msg.sender].add(msg.value); time[msg.sender] = now; allDeposits+=msg.value; emit NewDeposit(msg.sender, msg.value); }else{ receivePayment(); } }
24,957
160
// bond
Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this)));
Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this)));
31,282
71
// ========== RESTRICTED FUNCTIONS - Curator / migrator callable ========== / [DISABLED FOR SPACE CONCERNS. ALSO, HARD TO GET UNIQUE TOKEN IDS DURING MIGRATIONS?]Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can).
// function migrator_stakeLocked_for(address staker_address, uint256 token_id, uint256 secs, uint256 start_timestamp) external isMigrating { // require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); // _stakeLocked(staker_address, msg.sender, token_id, secs, start_timestamp); // }
// function migrator_stakeLocked_for(address staker_address, uint256 token_id, uint256 secs, uint256 start_timestamp) external isMigrating { // require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); // _stakeLocked(staker_address, msg.sender, token_id, secs, start_timestamp); // }
11,572
55
// Grants the contract deployer the default admin role./
constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); }
constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); }
29,715
8
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false; _;
onlyAmbassadors = false; _;
49,929
4
// Move an existing element into the vacated key slot.
self.data[self.keys[self.keys.length - 1]].keyIndex = e.keyIndex; self.keys[e.keyIndex - 1] = self.keys[self.keys.length - 1]; self.keys.length -= 1; delete self.data[key]; return true;
self.data[self.keys[self.keys.length - 1]].keyIndex = e.keyIndex; self.keys[e.keyIndex - 1] = self.keys[self.keys.length - 1]; self.keys.length -= 1; delete self.data[key]; return true;
38,602
180
// Mints `quantity` tokens and transfers them to `to`. Requirements: - there must be `quantity` tokens remaining unminted in the total collection.- `to` cannot be the zero address.- `quantity` cannot be larger than the max batch size.
* Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); }
* Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); }
6,603
174
// change in reward is current balance - remaining reward + earned
uint256 bal = IERC20(reward.reward_token).balanceOf(address(this)); uint256 d_reward = bal.sub(reward.reward_remaining); d_reward = d_reward.add(IRewardStaking(reward.reward_pool).earned(address(this))); uint256 I = reward.reward_integral; if (supply > 0) { I = I + d_reward.mul(1e20).div(supply); }
uint256 bal = IERC20(reward.reward_token).balanceOf(address(this)); uint256 d_reward = bal.sub(reward.reward_remaining); d_reward = d_reward.add(IRewardStaking(reward.reward_pool).earned(address(this))); uint256 I = reward.reward_integral; if (supply > 0) { I = I + d_reward.mul(1e20).div(supply); }
45,682
14
// OVERRIDDEN PUBLIC WRITE CONTRACT FUNCTIONS: OpenSea's Royalty Filterer Implementation.
function approve( address operator, uint256 tokenId
function approve( address operator, uint256 tokenId
12,420
49
// Track and future validation
buddyListMints[_receiver] += 1; _mint(_receiver, _tokenId); totalSupply++;
buddyListMints[_receiver] += 1; _mint(_receiver, _tokenId); totalSupply++;
29,820
5
// _index observer index in storage return address of the observer with provided index/
function getObserverAtIndex(uint _index) public view returns(address) { return daoStorage.getObserverAtIndex(_index); }
function getObserverAtIndex(uint _index) public view returns(address) { return daoStorage.getObserverAtIndex(_index); }
10,281
28
// LE
ambassadorsMaxPremine[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = 0x41F29054E7c0BC59a8AF10f3a6e7C0E53B334e05;
ambassadorsMaxPremine[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = 0x41F29054E7c0BC59a8AF10f3a6e7C0E53B334e05;
15,335
21
// @inheritdoc IAccessManager
function expiration() public view virtual returns (uint32) { return 1 weeks; }
function expiration() public view virtual returns (uint32) { return 1 weeks; }
870
21
// Accept admin right over the timelock. / solhint-disable-next-line private-vars-leading-underscore
function __acceptAdmin() public { _timelock.acceptAdmin(); }
function __acceptAdmin() public { _timelock.acceptAdmin(); }
9,487
78
// range: [0, 2112 - 1] resolution: 1 / 2112
struct uq112x112 { uint224 _x; }
struct uq112x112 { uint224 _x; }
45,705
46
// enough confirmations: reset and run interior.
delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true;
delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true;
23,836
318
// We must manually initialize Ownable
UnlockOwnable.__initializeOwnable(_unlockOwner);
UnlockOwnable.__initializeOwnable(_unlockOwner);
13,535
56
// fetchPrice(): Returns the latest price obtained from the Oracle. Called by Liquity functions that require a current price. Also callable by anyone externally. Non-view function - it stores the last good price seen by Liquity. Uses a main oracle (Chainlink) and a fallback oracle (Tellor) in case Chainlink fails. If both fail,it uses the last good price seen by Liquity./
function fetchPrice() external override returns (uint) { // Get current and previous price data from Chainlink, and current price data from Tellor ChainlinkResponse memory chainlinkResponse = _getCurrentChainlinkResponse(); ChainlinkResponse memory prevChainlinkResponse = _getPrevChainlinkResponse(chainlinkResponse.roundId, chainlinkResponse.decimals); TellorResponse memory tellorResponse = _getCurrentTellorResponse(); // --- CASE 1: System fetched last price from Chainlink --- if (status == Status.chainlinkWorking) { // If Chainlink is broken, try Tellor if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) { // If Tellor is broken then both oracles are untrusted, so return the last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } /* * If Tellor is only frozen but otherwise returning valid data, return the last good price. * Tellor may need to be tipped to return current data. */ if (_tellorIsFrozen(tellorResponse)) { _changeStatus(Status.usingTellorChainlinkUntrusted); return lastGoodPrice; } // If Chainlink is broken and Tellor is working, switch to Tellor and return current Tellor price _changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse); } // If Chainlink is frozen, try Tellor if (_chainlinkIsFrozen(chainlinkResponse)) { // If Tellor is broken too, remember Tellor broke, and return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); return lastGoodPrice; } // If Tellor is frozen or working, remember Chainlink froze, and switch to Tellor _changeStatus(Status.usingTellorChainlinkFrozen); if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // If Tellor is working, use it return _storeTellorPrice(tellorResponse); } // If Chainlink price has changed by > 50% between two consecutive rounds, compare it to Tellor's price if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) { // If Tellor is broken, both oracles are untrusted, and return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // If Tellor is frozen, switch to Tellor and return last good price if (_tellorIsFrozen(tellorResponse)) { _changeStatus(Status.usingTellorChainlinkUntrusted); return lastGoodPrice; } /* * If Tellor is live and both oracles have a similar price, conclude that Chainlink's large price deviation between * two consecutive rounds was likely a legitmate market price movement, and so continue using Chainlink */ if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) { return _storeChainlinkPrice(chainlinkResponse); } // If Tellor is live but the oracles differ too much in price, conclude that Chainlink's initial price deviation was // an oracle failure. Switch to Tellor, and use Tellor price _changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse); } // If Chainlink is working and Tellor is broken, remember Tellor is broken if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); } // If Chainlink is working, return Chainlink current price (no status change) return _storeChainlinkPrice(chainlinkResponse); } // --- CASE 2: The system fetched last price from Tellor --- if (status == Status.usingTellorChainlinkUntrusted) { // If both Tellor and Chainlink are live, unbroken, and reporting similar prices, switch back to Chainlink if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } /* * If Tellor is only frozen but otherwise returning valid data, just return the last good price. * Tellor may need to be tipped to return current data. */ if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // Otherwise, use Tellor price return _storeTellorPrice(tellorResponse); } // --- CASE 3: Both oracles were untrusted at the last price fetch --- if (status == Status.bothOraclesUntrusted) { /* * If both oracles are now live, unbroken and similar price, we assume that they are reporting * accurately, and so we switch back to Chainlink. */ if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } // Otherwise, return the last good price - both oracles are still untrusted (no status change) return lastGoodPrice; } // --- CASE 4: Using Tellor, and Chainlink is frozen --- if (status == Status.usingTellorChainlinkFrozen) { if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) { // If both Oracles are broken, return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // If Chainlink is broken, remember it and switch to using Tellor _changeStatus(Status.usingTellorChainlinkUntrusted); if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // If Tellor is working, return Tellor current price return _storeTellorPrice(tellorResponse); } if (_chainlinkIsFrozen(chainlinkResponse)) { // if Chainlink is frozen and Tellor is broken, remember Tellor broke, and return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); return lastGoodPrice; } // If both are frozen, just use lastGoodPrice if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // if Chainlink is frozen and Tellor is working, keep using Tellor (no status change) return _storeTellorPrice(tellorResponse); } // if Chainlink is live and Tellor is broken, remember Tellor broke, and return Chainlink price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); return _storeChainlinkPrice(chainlinkResponse); } // If Chainlink is live and Tellor is frozen, just use last good price (no status change) since we have no basis for comparison if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // If Chainlink is live and Tellor is working, compare prices. Switch to Chainlink // if prices are within 5%, and return Chainlink price. if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } // Otherwise if Chainlink is live but price not within 5% of Tellor, distrust Chainlink, and return Tellor price _changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse); } // --- CASE 5: Using Chainlink, Tellor is untrusted --- if (status == Status.usingChainlinkTellorUntrusted) { // If Chainlink breaks, now both oracles are untrusted if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // If Chainlink is frozen, return last good price (no status change) if (_chainlinkIsFrozen(chainlinkResponse)) { return lastGoodPrice; } // If Chainlink and Tellor are both live, unbroken and similar price, switch back to chainlinkWorking and return Chainlink price if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } // If Chainlink is live but deviated >50% from it's previous price and Tellor is still untrusted, switch // to bothOraclesUntrusted and return last good price if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // Otherwise if Chainlink is live and deviated <50% from it's previous price and Tellor is still untrusted, // return Chainlink price (no status change) return _storeChainlinkPrice(chainlinkResponse); } }
function fetchPrice() external override returns (uint) { // Get current and previous price data from Chainlink, and current price data from Tellor ChainlinkResponse memory chainlinkResponse = _getCurrentChainlinkResponse(); ChainlinkResponse memory prevChainlinkResponse = _getPrevChainlinkResponse(chainlinkResponse.roundId, chainlinkResponse.decimals); TellorResponse memory tellorResponse = _getCurrentTellorResponse(); // --- CASE 1: System fetched last price from Chainlink --- if (status == Status.chainlinkWorking) { // If Chainlink is broken, try Tellor if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) { // If Tellor is broken then both oracles are untrusted, so return the last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } /* * If Tellor is only frozen but otherwise returning valid data, return the last good price. * Tellor may need to be tipped to return current data. */ if (_tellorIsFrozen(tellorResponse)) { _changeStatus(Status.usingTellorChainlinkUntrusted); return lastGoodPrice; } // If Chainlink is broken and Tellor is working, switch to Tellor and return current Tellor price _changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse); } // If Chainlink is frozen, try Tellor if (_chainlinkIsFrozen(chainlinkResponse)) { // If Tellor is broken too, remember Tellor broke, and return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); return lastGoodPrice; } // If Tellor is frozen or working, remember Chainlink froze, and switch to Tellor _changeStatus(Status.usingTellorChainlinkFrozen); if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // If Tellor is working, use it return _storeTellorPrice(tellorResponse); } // If Chainlink price has changed by > 50% between two consecutive rounds, compare it to Tellor's price if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) { // If Tellor is broken, both oracles are untrusted, and return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // If Tellor is frozen, switch to Tellor and return last good price if (_tellorIsFrozen(tellorResponse)) { _changeStatus(Status.usingTellorChainlinkUntrusted); return lastGoodPrice; } /* * If Tellor is live and both oracles have a similar price, conclude that Chainlink's large price deviation between * two consecutive rounds was likely a legitmate market price movement, and so continue using Chainlink */ if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) { return _storeChainlinkPrice(chainlinkResponse); } // If Tellor is live but the oracles differ too much in price, conclude that Chainlink's initial price deviation was // an oracle failure. Switch to Tellor, and use Tellor price _changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse); } // If Chainlink is working and Tellor is broken, remember Tellor is broken if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); } // If Chainlink is working, return Chainlink current price (no status change) return _storeChainlinkPrice(chainlinkResponse); } // --- CASE 2: The system fetched last price from Tellor --- if (status == Status.usingTellorChainlinkUntrusted) { // If both Tellor and Chainlink are live, unbroken, and reporting similar prices, switch back to Chainlink if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } /* * If Tellor is only frozen but otherwise returning valid data, just return the last good price. * Tellor may need to be tipped to return current data. */ if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // Otherwise, use Tellor price return _storeTellorPrice(tellorResponse); } // --- CASE 3: Both oracles were untrusted at the last price fetch --- if (status == Status.bothOraclesUntrusted) { /* * If both oracles are now live, unbroken and similar price, we assume that they are reporting * accurately, and so we switch back to Chainlink. */ if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } // Otherwise, return the last good price - both oracles are still untrusted (no status change) return lastGoodPrice; } // --- CASE 4: Using Tellor, and Chainlink is frozen --- if (status == Status.usingTellorChainlinkFrozen) { if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) { // If both Oracles are broken, return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // If Chainlink is broken, remember it and switch to using Tellor _changeStatus(Status.usingTellorChainlinkUntrusted); if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // If Tellor is working, return Tellor current price return _storeTellorPrice(tellorResponse); } if (_chainlinkIsFrozen(chainlinkResponse)) { // if Chainlink is frozen and Tellor is broken, remember Tellor broke, and return last good price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); return lastGoodPrice; } // If both are frozen, just use lastGoodPrice if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // if Chainlink is frozen and Tellor is working, keep using Tellor (no status change) return _storeTellorPrice(tellorResponse); } // if Chainlink is live and Tellor is broken, remember Tellor broke, and return Chainlink price if (_tellorIsBroken(tellorResponse)) { _changeStatus(Status.usingChainlinkTellorUntrusted); return _storeChainlinkPrice(chainlinkResponse); } // If Chainlink is live and Tellor is frozen, just use last good price (no status change) since we have no basis for comparison if (_tellorIsFrozen(tellorResponse)) {return lastGoodPrice;} // If Chainlink is live and Tellor is working, compare prices. Switch to Chainlink // if prices are within 5%, and return Chainlink price. if (_bothOraclesSimilarPrice(chainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } // Otherwise if Chainlink is live but price not within 5% of Tellor, distrust Chainlink, and return Tellor price _changeStatus(Status.usingTellorChainlinkUntrusted); return _storeTellorPrice(tellorResponse); } // --- CASE 5: Using Chainlink, Tellor is untrusted --- if (status == Status.usingChainlinkTellorUntrusted) { // If Chainlink breaks, now both oracles are untrusted if (_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // If Chainlink is frozen, return last good price (no status change) if (_chainlinkIsFrozen(chainlinkResponse)) { return lastGoodPrice; } // If Chainlink and Tellor are both live, unbroken and similar price, switch back to chainlinkWorking and return Chainlink price if (_bothOraclesLiveAndUnbrokenAndSimilarPrice(chainlinkResponse, prevChainlinkResponse, tellorResponse)) { _changeStatus(Status.chainlinkWorking); return _storeChainlinkPrice(chainlinkResponse); } // If Chainlink is live but deviated >50% from it's previous price and Tellor is still untrusted, switch // to bothOraclesUntrusted and return last good price if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; } // Otherwise if Chainlink is live and deviated <50% from it's previous price and Tellor is still untrusted, // return Chainlink price (no status change) return _storeChainlinkPrice(chainlinkResponse); } }
4,356
4
// if no data in map will get 0 index and zeroInfo.
return _subscribers[orderId];
return _subscribers[orderId];
11,233
63
// Get a reference to the project's ERC20 tickets.
ITickets _tickets = ticketsOf[_projectId];
ITickets _tickets = ticketsOf[_projectId];
17,993
34
// One more has been issued
series.issuedCount++; itemTransferred(nodehash, itemIndex, 0x0, owner); return true;
series.issuedCount++; itemTransferred(nodehash, itemIndex, 0x0, owner); return true;
51,042
244
// Called when royalty is transferred to the receiver. This emits the RoyaltiesReceived event as we want the NFT contract itself to contain the event for easy tracking by royalty receivers._royaltyRecipient - The address of who is entitled to theroyalties as specified by royaltyInfo()._buyer - If known, the address buying the NFT on a secondary sale. 0x0 if not known._tokenId - the ID of the ERC-721 token that was sold_tokenPaid - The address of the ERC-20 token used to pay the royalty fee amount. Set to 0x0 if paid in the native asset (ETH)._amount - The amount being paid to the
function onRoyaltiesReceived(address _royaltyRecipient, address _buyer, uint256 _tokenId, address _tokenPaid, uint256 _amount, bytes32 _metadata) external returns (bytes4);
function onRoyaltiesReceived(address _royaltyRecipient, address _buyer, uint256 _tokenId, address _tokenPaid, uint256 _amount, bytes32 _metadata) external returns (bytes4);
5,554
319
// Returns the validator address at `_index`. Assumes `_index` is less than the number of validators _metadata ABI encoded Multisig ISM metadata. _index The index of the validator to return.return The validator address at `_index`. /
function validatorAt(bytes calldata _metadata, uint256 _index) internal pure returns (address)
function validatorAt(bytes calldata _metadata, uint256 _index) internal pure returns (address)
19,139
18
// Gets a factory contract address factoryType The type of factory to be checked version Version of the factory to be checkedreturn factory Address of the factory contract /
function getFactoryVersion(bytes32 factoryType, uint8 version) external view override returns (address factory)
function getFactoryVersion(bytes32 factoryType, uint8 version) external view override returns (address factory)
29,113
40
// add various whitelist addresses _addresses Array of ethereum addresses /
function addManyToWhitelist(address[] _addresses) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { allowedAddresses[_addresses[i]] = true; emit WhitelistUpdated(now, "Added", _addresses[i]); } }
function addManyToWhitelist(address[] _addresses) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { allowedAddresses[_addresses[i]] = true; emit WhitelistUpdated(now, "Added", _addresses[i]); } }
29,473
73
// Finally, postRelayedCall is executed, with the relayedCall execution's status and a charge estimate We now determine how much the recipient will be charged, to pass this value to postRelayedCall for accurate accounting.
vars.data = abi.encodeWithSelector( IPaymaster.postRelayedCall.selector, vars.recipientContext, vars.relayedCallSuccess, totalInitialGas - gasleft(), /*gasUseWithoutPost*/ relayRequest.relayData ); { (bool successPost,bytes memory ret) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.postRelayedCallGasLimit}(vars.data);
vars.data = abi.encodeWithSelector( IPaymaster.postRelayedCall.selector, vars.recipientContext, vars.relayedCallSuccess, totalInitialGas - gasleft(), /*gasUseWithoutPost*/ relayRequest.relayData ); { (bool successPost,bytes memory ret) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.postRelayedCallGasLimit}(vars.data);
70,172
5
// Calculates the average of two numbers. Since these are integers, averages of an even and odd number cannot be represented, and will be rounded down./
function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); }
function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); }
52,642
16
// Function to process the L2 withdrawal/amount How many $LORDS were sent from L2/l1Recipient Recipient of the (de)bridged $LORDS
function withdraw(uint256 amount, address l1Recipient) external { uint256[] memory payload = new uint256[](4); payload[0] = PROCESS_WITHDRAWAL; payload[1] = uint256(uint160(l1Recipient)); (payload[2], payload[3]) = splitUint256(amount); // The call to consumeMessageFromL2 will succeed only if a // matching L2->L1 message exists and is ready for consumption. IStarknetCore(starknet).consumeMessageFromL2(l2Bridge, payload); IERC20Like(l1Token).transfer(l1Recipient, amount); emit LogWithdrawal(l1Recipient, amount); }
function withdraw(uint256 amount, address l1Recipient) external { uint256[] memory payload = new uint256[](4); payload[0] = PROCESS_WITHDRAWAL; payload[1] = uint256(uint160(l1Recipient)); (payload[2], payload[3]) = splitUint256(amount); // The call to consumeMessageFromL2 will succeed only if a // matching L2->L1 message exists and is ready for consumption. IStarknetCore(starknet).consumeMessageFromL2(l2Bridge, payload); IERC20Like(l1Token).transfer(l1Recipient, amount); emit LogWithdrawal(l1Recipient, amount); }
23,113
49
// Payable address can receive Ether
address payable public software;
address payable public software;
16,253
63
// emit buy
emit Buy( order.orderNonce, order.outAsset.token, order.outAsset.tokenId, amount, order.maker, order.inAsset.token, order.inAsset.tokenId, order.inAsset.quantity, msg.sender,
emit Buy( order.orderNonce, order.outAsset.token, order.outAsset.tokenId, amount, order.maker, order.inAsset.token, order.inAsset.tokenId, order.inAsset.quantity, msg.sender,
55,028
7
// Returns the currently approved VioletID tokens to interact with Mauve/This defines the set of VioletID tokens that are used by Mauve to authorize/ certain interactions. More specifically, an account must own at least one of these tokens to/ become the owner of a LP NFT via transfer or withdraw funds in case/ the emergency mode is activated./ return The list of VioletID tokens that are accepted
function getMauveTokenIdsAllowedToInteract() external view returns (uint256[] memory);
function getMauveTokenIdsAllowedToInteract() external view returns (uint256[] memory);
37,053
76
// This is internal method for process meeting contains common logic._messageHash Message hash. _initialGas initial gas during progress process._proofProgress true if progress with proof, false if progresswith hashlock. _unlockSecret unlock secret to progress, zero in case of progress with proof returnbeneficiary_ Address to which the utility tokens will be transferred after minting.return stakeAmount_ Total amount for which the stake was initiated. The reward amount is deducted from the total amount and is given to the facilitator.return mintedAmount_ Actual minted amount, after deducting the reward from the total amount.return rewardAmount_ Reward amount that is transferred to facilitator /
function progressMintingInternal( bytes32 _messageHash, uint256 _initialGas, bool _proofProgress, bytes32 _unlockSecret ) private returns ( address beneficiary_,
function progressMintingInternal( bytes32 _messageHash, uint256 _initialGas, bool _proofProgress, bytes32 _unlockSecret ) private returns ( address beneficiary_,
42,986
75
// Transfer liquidity worth 150 ppdex to contract
IUniswapV2ERC20 lpToken = IUniswapV2ERC20(UniV2Address); uint lpAmount = MinLPTokensGolden(); require (lpToken.transferFrom(msg.sender, address(this), lpAmount), "Token Transfer failed");
IUniswapV2ERC20 lpToken = IUniswapV2ERC20(UniV2Address); uint lpAmount = MinLPTokensGolden(); require (lpToken.transferFrom(msg.sender, address(this), lpAmount), "Token Transfer failed");
5,008
113
// Finally, we restore the original length in order to not mutate `code`.
mstore(code, codeLength)
mstore(code, codeLength)
28,272
6
// topic: 0x9bbd2de400810774339120e2f8a2b517ed748595e944529bba8ebabf314d0591
event SetTransactionLimits(address[] addresses, uint256[] limits); event WithdrawRBTCTo(address indexed to, uint256 amount); event ToggledFunctionPaused(string functionId, bool prevFlag, bool newFlag);
event SetTransactionLimits(address[] addresses, uint256[] limits); event WithdrawRBTCTo(address indexed to, uint256 amount); event ToggledFunctionPaused(string functionId, bool prevFlag, bool newFlag);
23,597
13
// Set the address of the bonus pool, which provides tokens/during bonus periods if it contains sufficient PLG/_bonusPool Address of PLG holder
function setBonusPool(address _bonusPool) public onlyOwner { bonusPool = _bonusPool; }
function setBonusPool(address _bonusPool) public onlyOwner { bonusPool = _bonusPool; }
24,224
141
// Transfer to the underlying asset(ERC20)
if (_underlyingTokenAddress != address(0x0)) { require(msg.value == 0, "Log:InsurancePool:msg.value!=0"); TransferHelper.safeTransferFrom(_underlyingTokenAddress, msg.sender, address(this), amount); }
if (_underlyingTokenAddress != address(0x0)) { require(msg.value == 0, "Log:InsurancePool:msg.value!=0"); TransferHelper.safeTransferFrom(_underlyingTokenAddress, msg.sender, address(this), amount); }
45,575
2
// ========== ADD ========== // adds a new Note for a user, stores the front end & DAO rewards, and mints & stakes payout & rewards _userthe user that owns the Note _payoutthe amount of Pana due to the user _expirythe timestamp when the Note is redeemable _marketIDthe ID of the market deposited intoreturn index_the index of the Note in the user's array /
function addNote( address _user, uint256 _payout, uint48 _expiry, uint48 _marketID
function addNote( address _user, uint256 _payout, uint48 _expiry, uint48 _marketID
22,069
16
// Accessing to real labels defined by growers (they are actually fake in this contract)
mapping(uint => Label[]) public productCodeToRealLabels;
mapping(uint => Label[]) public productCodeToRealLabels;
52,628
140
// the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). Does not support burning tokens to address(0). Assumes that an owner cannot have more than the 2128 (max value of uint128) of supply /
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex = 0; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert('ERC721A: unable to determine the owner of token'); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token'); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), 'ERC721A: token already minted'); require(quantity > 0, 'ERC721A: quantity must be greater 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex = 0; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert('ERC721A: unable to determine the owner of token'); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token'); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), 'ERC721A: token already minted'); require(quantity > 0, 'ERC721A: quantity must be greater 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
9,716
33
// Returns total number of transactions after filers are applied./pending Include pending transactions./executed Include executed transactions./ return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed) public constant returns (uint count)
function getTransactionCount(bool pending, bool executed) public constant returns (uint count)
7,127
136
// Can't unstake less than 20 NXM.
if (unstakeAmount < 20 ether) return 0; for (uint256 i = 0; i < protocols.length; i++) { uint256 indUnstakeAmount = _protocolUnstakeable(protocols[i], unstakeAmount); if (indUnstakeAmount > 0) { amounts.push(indUnstakeAmount); unstakingProtocols.push(protocols[i]); }
if (unstakeAmount < 20 ether) return 0; for (uint256 i = 0; i < protocols.length; i++) { uint256 indUnstakeAmount = _protocolUnstakeable(protocols[i], unstakeAmount); if (indUnstakeAmount > 0) { amounts.push(indUnstakeAmount); unstakingProtocols.push(protocols[i]); }
19,909