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
12
// old LP token should not be in this contract, or it will get stuck
uint256 _bal = token.balanceOf(address(this)); if(_bal > 0) { token.safeTransfer(strategy, _bal); }
uint256 _bal = token.balanceOf(address(this)); if(_bal > 0) { token.safeTransfer(strategy, _bal); }
5,244
127
// Internal functionality
function _mint( address recipient, uint256 tokenId, uint256 price
function _mint( address recipient, uint256 tokenId, uint256 price
35,749
177
// list of possible ingredients
string[] private main = ["Almonds","Apples","Asparagus","Avocado","Bananas","Basil","Bay Leaf","Beans","Beef","Beer","Beets","Bell Peppers","Blueberries","Bourbon","Bread","Broccoli","Broth","Brussel Sprouts","Butter","Buttermilk","Cabbage","Cane Berries","Cardamon","Carrots","Cauliflower","Celery","Cheddar","Cheese","Cherries","Chervil","Chicken","Chickpeas","Chili","Chives","Chocolate","Cider","Cilantro","Cinnamon","Cloves","Coconut","Cod","Coriander","Corn","Cornstarch","Cranberries","Cream","Cucumber","Cumin","Dill","Dough","Duck","Eggplant","Eggs","Fennel","Fish","Flour","Fruit","Garlic","Ginger","Goat","Grapes","Green Beans","Greens","Herbs","Herring","Honey","Horseradish","Juice","Kale","Kiwi","Lamb","Leafy Greens","Leaves","Leeks","Lemon","Lemongrass","Lentils","Lettuce","Lime","Mackerel","Mangos","Maple","Margarine","Marjoram","Meat","Milk","Mint","Mushrooms","Mustard","Noodles","Nutmeg","Nuts","Oats","Oil","Olive","Onions","Oranges","Oregano","Paprika","Parmesan","Parsley","Parsnips","Peaches","Peanut","Pears","Peas","Pepper","Peppermint","Perch","Pineapple","Pollock","Pork","Potatoes","Pumpkin","Rabbit","Radishes","Raisins","Rhubarb","Rice","Rice Noodles","Rosemary","Saffron","Salmon","Salt","Sardines","Scallions","Seabass","Seeds","Sesame","Sodium","Soy","Spinach","Stock","Strawberries","Sugar","Sweet Potatos","Syrup","Tarragon","Thyme","Tofu","Tomatoes","Tuna","Turkey","Turmeric","Turnips","Vanilla","Vegetables","Vinegar","Walnuts","Wasabi","Watermelon","Wheat","Water","Wine","Yeast","Yogurt","Zucchini"];
string[] private main = ["Almonds","Apples","Asparagus","Avocado","Bananas","Basil","Bay Leaf","Beans","Beef","Beer","Beets","Bell Peppers","Blueberries","Bourbon","Bread","Broccoli","Broth","Brussel Sprouts","Butter","Buttermilk","Cabbage","Cane Berries","Cardamon","Carrots","Cauliflower","Celery","Cheddar","Cheese","Cherries","Chervil","Chicken","Chickpeas","Chili","Chives","Chocolate","Cider","Cilantro","Cinnamon","Cloves","Coconut","Cod","Coriander","Corn","Cornstarch","Cranberries","Cream","Cucumber","Cumin","Dill","Dough","Duck","Eggplant","Eggs","Fennel","Fish","Flour","Fruit","Garlic","Ginger","Goat","Grapes","Green Beans","Greens","Herbs","Herring","Honey","Horseradish","Juice","Kale","Kiwi","Lamb","Leafy Greens","Leaves","Leeks","Lemon","Lemongrass","Lentils","Lettuce","Lime","Mackerel","Mangos","Maple","Margarine","Marjoram","Meat","Milk","Mint","Mushrooms","Mustard","Noodles","Nutmeg","Nuts","Oats","Oil","Olive","Onions","Oranges","Oregano","Paprika","Parmesan","Parsley","Parsnips","Peaches","Peanut","Pears","Peas","Pepper","Peppermint","Perch","Pineapple","Pollock","Pork","Potatoes","Pumpkin","Rabbit","Radishes","Raisins","Rhubarb","Rice","Rice Noodles","Rosemary","Saffron","Salmon","Salt","Sardines","Scallions","Seabass","Seeds","Sesame","Sodium","Soy","Spinach","Stock","Strawberries","Sugar","Sweet Potatos","Syrup","Tarragon","Thyme","Tofu","Tomatoes","Tuna","Turkey","Turmeric","Turnips","Vanilla","Vegetables","Vinegar","Walnuts","Wasabi","Watermelon","Wheat","Water","Wine","Yeast","Yogurt","Zucchini"];
25,132
66
// oods_coefficients[46]/ mload(add(context, 0x7d00)), res += c_47(f_6(x) - f_6(g^251z)) / (x - g^251z).
res := add( res, mulmod(mulmod(/*(x - g^251 * z)^(-1)*/ mload(add(denominatorsPtr, 0x700)),
res := add( res, mulmod(mulmod(/*(x - g^251 * z)^(-1)*/ mload(add(denominatorsPtr, 0x700)),
76,980
341
// point = g^2.
point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME)
point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME)
3,299
52
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); }
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); }
1,595
176
// Returns amount available for transfer
function _withdraw(uint _amount) private returns (uint) { uint bal = IERC20(underlying).balanceOf(address(this)); if (bal >= _amount) { return _amount; } uint redeemAmount = _amount - bal; /* c = collateral ratio s = supplied b = borrowed r = amount to redeem x = amount to repay where r <= s - b (can't redeem more than unleveraged supply) and x <= b (can't repay more than borrowed) and (b - x) / (s - x - r) <= c (stay below c after redeem and repay) so pick x such that (b - cs + cr) / (1 - c) <= x <= b when b <= cs left side of equation above <= cr / (1 - c) so pick x such that cr / (1 - c) <= x <= b */ uint supplied = _getSupplied(); uint borrowed = _getBorrowed(); uint marketCol = _getMarketCollateralRatio(); uint safeCol = _getSafeCollateralRatio(marketCol); uint unleveraged = supplied.sub(borrowed); // r <= s - b if (redeemAmount > unleveraged) { redeemAmount = unleveraged; } // cr / (1 - c) <= x <= b uint repayAmount = redeemAmount.mul(safeCol).div(uint(1e18).sub(safeCol)); if (repayAmount > borrowed) { repayAmount = borrowed; } _deleverage(supplied.sub(repayAmount)); _redeem(redeemAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); if (balAfter < _amount) { return balAfter; } return _amount; }
function _withdraw(uint _amount) private returns (uint) { uint bal = IERC20(underlying).balanceOf(address(this)); if (bal >= _amount) { return _amount; } uint redeemAmount = _amount - bal; /* c = collateral ratio s = supplied b = borrowed r = amount to redeem x = amount to repay where r <= s - b (can't redeem more than unleveraged supply) and x <= b (can't repay more than borrowed) and (b - x) / (s - x - r) <= c (stay below c after redeem and repay) so pick x such that (b - cs + cr) / (1 - c) <= x <= b when b <= cs left side of equation above <= cr / (1 - c) so pick x such that cr / (1 - c) <= x <= b */ uint supplied = _getSupplied(); uint borrowed = _getBorrowed(); uint marketCol = _getMarketCollateralRatio(); uint safeCol = _getSafeCollateralRatio(marketCol); uint unleveraged = supplied.sub(borrowed); // r <= s - b if (redeemAmount > unleveraged) { redeemAmount = unleveraged; } // cr / (1 - c) <= x <= b uint repayAmount = redeemAmount.mul(safeCol).div(uint(1e18).sub(safeCol)); if (repayAmount > borrowed) { repayAmount = borrowed; } _deleverage(supplied.sub(repayAmount)); _redeem(redeemAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); if (balAfter < _amount) { return balAfter; } return _amount; }
41,572
198
// check fees has been well received do the action and assertion in one to save a variable
require(collectForREQBurning(fees));
require(collectForREQBurning(fees));
47,270
16
// Function updating maximum minting amount per account - available to owner_newmaxMintAmount The maximum mint amount per account Requirements: - the newmaxMintAmount is greater than zero/
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { require(_newmaxMintAmount > 0, "Max mint amount entered is zero"); maxMintAmount = _newmaxMintAmount; }
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { require(_newmaxMintAmount > 0, "Max mint amount entered is zero"); maxMintAmount = _newmaxMintAmount; }
15,340
6
// need to update qr code for 1155
function verifyData( bytes memory signature, uint256 tokenId, string memory code
function verifyData( bytes memory signature, uint256 tokenId, string memory code
27,056
1
// Log game result (heads 0 or tails 1) in order to display it on frontend
event GameResult(uint8 side);
event GameResult(uint8 side);
21,382
575
// Repays debt with the native and or synthetic token.// An approval is required to transfer native tokens to the transmuter.
function repay(uint256 _parentAmount, uint256 _childAmount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); if (_parentAmount > 0) { token.safeTransferFrom(msg.sender, address(this), _parentAmount); _distributeToTransmuter(_parentAmount); } if (_childAmount > 0) { xtoken.burnFrom(msg.sender, _childAmount); //lower debt cause burn xtoken.lowerHasMinted(_childAmount); } uint256 _totalAmount = _parentAmount.add(_childAmount); _cdp.totalDebt = _cdp.totalDebt.sub(_totalAmount, ""); emit TokensRepaid(msg.sender, _parentAmount, _childAmount); }
function repay(uint256 _parentAmount, uint256 _childAmount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); if (_parentAmount > 0) { token.safeTransferFrom(msg.sender, address(this), _parentAmount); _distributeToTransmuter(_parentAmount); } if (_childAmount > 0) { xtoken.burnFrom(msg.sender, _childAmount); //lower debt cause burn xtoken.lowerHasMinted(_childAmount); } uint256 _totalAmount = _parentAmount.add(_childAmount); _cdp.totalDebt = _cdp.totalDebt.sub(_totalAmount, ""); emit TokensRepaid(msg.sender, _parentAmount, _childAmount); }
3,251
2
// query child and parent is associated child: address of the child parent: address of the parentreturn child and parent is associated /
function isParent(address child,address parent) external view returns(bool);
function isParent(address child,address parent) external view returns(bool);
5,895
23
// The array of ``tokenId``'s that are waiting for the `Locked` event to be emitted /
uint256[] private tokensToLock;
uint256[] private tokensToLock;
28,923
10
// This is y = x2^(-n).
uint256 y = x >> n;
uint256 y = x >> n;
3,544
193
// View function to see pending SPECTREs on frontend.
function pendingSpectre(uint256 _pid, address _user) external view returns (uint256)
function pendingSpectre(uint256 _pid, address _user) external view returns (uint256)
45,092
229
// helper for sell Balancer pool/
function sellBalancerPool( uint256 _amount, IERC20 _poolToken, bytes calldata _additionalData ) private returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount
function sellBalancerPool( uint256 _amount, IERC20 _poolToken, bytes calldata _additionalData ) private returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount
8,819
0
// MIN_BLOCK_ISSUANCE_LIMIT: {rTok/block} 10k whole RTok
uint192 constant MAX_ISSUANCE_RATE = 1e18; // {1}
uint192 constant MAX_ISSUANCE_RATE = 1e18; // {1}
31,499
17
// Maximum length we support
require(length <= 999999);
require(length <= 999999);
8,222
60
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
8,375
93
// validate of the passed in `_param.subscriptionId` points at a valid subscription
require(_subscriptionId < getSubscriptionsAt(_clubId, _tierId).length, "!SUBSCRIPTION - subscription not found with `_param.subscriptionId`");
require(_subscriptionId < getSubscriptionsAt(_clubId, _tierId).length, "!SUBSCRIPTION - subscription not found with `_param.subscriptionId`");
5,407
35
// ------------------------------------------------------------------------ Query to get the total staking of the user_user wallet address of the staker ------------------------------------------------------------------------
function YourTotalStakingTillToday(address _user) external view returns(uint256 _totalStaking){ return users[_user].totalDeposits; }
function YourTotalStakingTillToday(address _user) external view returns(uint256 _totalStaking){ return users[_user].totalDeposits; }
4,381
311
// all existing Curve metapools are paired with 3pool
Curve3poolAllocation public immutable curve3poolAllocation;
Curve3poolAllocation public immutable curve3poolAllocation;
65,507
35
// reduces the total supply by the amount of that users in that swap
self.total_supply = self.total_supply.sub(party_swap_balance);
self.total_supply = self.total_supply.sub(party_swap_balance);
49,927
177
// Transactions are After Transaction Root, Plus 64 Bytes (for bytes type metadata from ABI Encoding)
let transactions := safeAdd(transactionRoot, transactionRootLength)
let transactions := safeAdd(transactionRoot, transactionRootLength)
21,507
10
// When a deposit is initiated on L1, the L1 Bridge transfers the NFT to itself for future withdrawals. slither-disable-next-line reentrancy-events, reentrancy-benign
IERC721(_l1Token).transferFrom(_from, address(this), _tokenId);
IERC721(_l1Token).transferFrom(_from, address(this), _tokenId);
21,438
7
// ------------------------------------------------------------------------ Don't accept ETH ------------------------------------------------------------------------
function () external payable { revert(); }
function () external payable { revert(); }
14,785
209
// Lock additional ether as collateral to agreement cdp contract _amount collateral amount for additional lockreturnOperation success /
function lockAdditionalCollateral(uint _amount) external payable onlyBorrower beforeStatus(Statuses.Closed) returns(bool _success) { if (!isETH) { erc20TokenContract(collateralType).transferFrom(msg.sender, address(this), _amount); } if (isStatus(Statuses.Active)) { if (isETH) { require(msg.value == _amount, "Agreement: ether sent doesn\'t coinside with required"); _lockETH(collateralType, cdpId, msg.value); } else { _lockERC20(collateralType, cdpId, _amount, true); } } collateralAmount = collateralAmount.add(_amount); emit AdditionalCollateralLocked(_amount); _monitorRisky(); return true; }
function lockAdditionalCollateral(uint _amount) external payable onlyBorrower beforeStatus(Statuses.Closed) returns(bool _success) { if (!isETH) { erc20TokenContract(collateralType).transferFrom(msg.sender, address(this), _amount); } if (isStatus(Statuses.Active)) { if (isETH) { require(msg.value == _amount, "Agreement: ether sent doesn\'t coinside with required"); _lockETH(collateralType, cdpId, msg.value); } else { _lockERC20(collateralType, cdpId, _amount, true); } } collateralAmount = collateralAmount.add(_amount); emit AdditionalCollateralLocked(_amount); _monitorRisky(); return true; }
41,164
126
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR);
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR);
9,129
42
// determine the trading ratio if swapping between tokens of differing supplies. (1% = 1% as an example)
if(token2TotalSupply > token1TotalSupply){ tradingRatio = token2TotalSupply / token1TotalSupply; amountToSend = token1Balance * tradingRatio; // multiply if V2 supply is higher than V1 } else if (token1TotalSupply > token2TotalSupply){
if(token2TotalSupply > token1TotalSupply){ tradingRatio = token2TotalSupply / token1TotalSupply; amountToSend = token1Balance * tradingRatio; // multiply if V2 supply is higher than V1 } else if (token1TotalSupply > token2TotalSupply){
43,321
2
// NOTE: this ds_slot must be the shared if you want to share storage with another contract under the proxy umbrella NOTE: this ds_slot must be unique if you want to NOT share storage with another contract under the proxy umbrella ds_slot = keccak256("diamond.storage.ninja.authentication");
assembly { ds_slot := 0x23c99902bd20175af7869f805847c34572dcf321a973ed1a88e16e09df61afe6 }
assembly { ds_slot := 0x23c99902bd20175af7869f805847c34572dcf321a973ed1a88e16e09df61afe6 }
12,272
16
// Decrease amount of GAM tokens that can be minted _burnedAmount The amount of unminted tokens to be burned /
function burnUnmintedTokens(uint256 _burnedAmount) public onlyOwner returns (bool success){ require(_burnedAmount <= _unmintedTokens); _unmintedTokens = _unmintedTokens.sub(_burnedAmount); emit Burn(msg.sender, _burnedAmount); return true; }
function burnUnmintedTokens(uint256 _burnedAmount) public onlyOwner returns (bool success){ require(_burnedAmount <= _unmintedTokens); _unmintedTokens = _unmintedTokens.sub(_burnedAmount); emit Burn(msg.sender, _burnedAmount); return true; }
46,702
3
// for investors, we can whitelist addresses in order they can mint generals
mapping(address => bool) whitelist; string private constant COMMANDER = "bafybeick7bj677i3fhq5upoc2vplu4gmgmgdpacbtahx6f4uqkgl7dattq"; //rank 1 string private constant GENERAL = "bafybeidzfegfpn24lpjkf235tdhqvk26b2bsr7ye7sj2ggsodxk4rs25ju"; //rank 2 string private constant SOLDIER = "bafybeiceynivdpcrnu633gmcyp36x4lw7avehpznbjx5i62a52nqh2lk5i"; //rank 3 string private constant ARMY = "bafybeihn4y3bf364ihww2ogzpqavuryhjaeakvpk6ci7rrkjj4mmsqjpae"; //image for platform uint256 private constant COMMANDER_MINT = 5000000 * 1e18; //5,000,000 x 10^18 uint256 private constant GENERAL_MINT = 500000 * 1e18; // 500,000 x 10^18 uint256 private constant SOLDIER_MINT = 1000 * 1e18; // 1,000 x 10^18
mapping(address => bool) whitelist; string private constant COMMANDER = "bafybeick7bj677i3fhq5upoc2vplu4gmgmgdpacbtahx6f4uqkgl7dattq"; //rank 1 string private constant GENERAL = "bafybeidzfegfpn24lpjkf235tdhqvk26b2bsr7ye7sj2ggsodxk4rs25ju"; //rank 2 string private constant SOLDIER = "bafybeiceynivdpcrnu633gmcyp36x4lw7avehpznbjx5i62a52nqh2lk5i"; //rank 3 string private constant ARMY = "bafybeihn4y3bf364ihww2ogzpqavuryhjaeakvpk6ci7rrkjj4mmsqjpae"; //image for platform uint256 private constant COMMANDER_MINT = 5000000 * 1e18; //5,000,000 x 10^18 uint256 private constant GENERAL_MINT = 500000 * 1e18; // 500,000 x 10^18 uint256 private constant SOLDIER_MINT = 1000 * 1e18; // 1,000 x 10^18
31,531
12
// getting bytecode of feature created farming pool
bytes memory bytecode = abi.encodePacked(type(FarmingRewards).creationCode, abi.encode( address(this), _deployer, _rewardToken, _stakingToken, _rewardAmount, _startDate, _endDate, _epochDuration, _minimumStakingExitTime
bytes memory bytecode = abi.encodePacked(type(FarmingRewards).creationCode, abi.encode( address(this), _deployer, _rewardToken, _stakingToken, _rewardAmount, _startDate, _endDate, _epochDuration, _minimumStakingExitTime
18,228
150
// Get amount of stake required to raise a dispute /
function getDisputeResolutionParams() public view returns (uint256) { return tokenStakeForDispute; }
function getDisputeResolutionParams() public view returns (uint256) { return tokenStakeForDispute; }
44,047
146
// Gets the last applicable timestamp for this reward period /
function lastTimeRewardApplicable() public view returns (uint256)
function lastTimeRewardApplicable() public view returns (uint256)
5,361
20
// Enable garden creations to be fully open to the public (no need of Ishtar gate anymore)
bool public override gardenCreationIsOpen;
bool public override gardenCreationIsOpen;
75,525
134
// ============ Internal Functions ============ /
function _getNonCaller(address _signerOne, address _signerTwo) internal view returns(address) { return msg.sender == _signerOne ? _signerTwo : _signerOne; }
function _getNonCaller(address _signerOne, address _signerTwo) internal view returns(address) { return msg.sender == _signerOne ? _signerTwo : _signerOne; }
59,966
242
// initialize - sets current address of ContractManager of SkaleManager newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager /
function initialize( IContractManager newContractManagerOfSkaleManager ) public virtual initializer
function initialize( IContractManager newContractManagerOfSkaleManager ) public virtual initializer
37,122
33
// update amountRedeemable
amountRedeemable = success ? amountRedeemable - amountToRedeem : amountRedeemable;
amountRedeemable = success ? amountRedeemable - amountToRedeem : amountRedeemable;
12,067
5
// ---------- Contracts ----------
IERC20Burnable public immutable JAMON; IJamonRouter public immutable ROUTER; IAcornBank public immutable BANK;
IERC20Burnable public immutable JAMON; IJamonRouter public immutable ROUTER; IAcornBank public immutable BANK;
25,444
867
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
10,183
15
// pyro in vaults
balance = balance.add(IBEP20(autoSharkPyroPool).balanceOf(_voter)); return balance;
balance = balance.add(IBEP20(autoSharkPyroPool).balanceOf(_voter)); return balance;
51,603
97
// rate Number of token units a buyer gets per weitoken unit. So, if you are using a rate of 1 with a ERC20Detailed tokenwith 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. wallet Address where collected funds will be forwarded to token Address of the token being sold /
constructor ( uint256 rate, address payable wallet, DANACHO token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; }
constructor ( uint256 rate, address payable wallet, DANACHO token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; }
20,537
16
// lost tokens go to the first payee
tokenContract.transfer(payees[0], balance);
tokenContract.transfer(payees[0], balance);
138
92
// Caller must be approved by the Vault's Authorizer
function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); }
function setSwapFeePercentage(uint256 swapFeePercentage) external virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); }
3,047
19
// Les électeurs inscrits votent pour leurs propositions préférées. /
function vote(uint proposalId) external isWhitelisted { require(workflowStatus == WorkflowStatus.VotingSessionStarted, "Vote pas en cours"); require(!whitelist[msg.sender].hasVoted, "Deja vote"); require(proposalId < proposals.length , "Id de proposition invalide"); whitelist[msg.sender].votedProposalId = proposalId; whitelist[msg.sender].hasVoted = true; proposals[proposalId].voteCount++; emit Voted(msg.sender, proposalId); }
function vote(uint proposalId) external isWhitelisted { require(workflowStatus == WorkflowStatus.VotingSessionStarted, "Vote pas en cours"); require(!whitelist[msg.sender].hasVoted, "Deja vote"); require(proposalId < proposals.length , "Id de proposition invalide"); whitelist[msg.sender].votedProposalId = proposalId; whitelist[msg.sender].hasVoted = true; proposals[proposalId].voteCount++; emit Voted(msg.sender, proposalId); }
23,896
40
// every participant has an account index, the winners are picked from here all winners are picked in order from the single random intneeds to be cleared after every game
mapping (uint => mapping (uint => address)) participants; // game number => counter => address uint256[] prizes = [0.04 ether, 0.02 ether, 0.01 ether, 5 finney, 5 finney, 5 finney, 5 finney, 5 finney];
mapping (uint => mapping (uint => address)) participants; // game number => counter => address uint256[] prizes = [0.04 ether, 0.02 ether, 0.01 ether, 5 finney, 5 finney, 5 finney, 5 finney, 5 finney];
43,940
116
// Needs to be true if migration started
require(isMigrationInitiated, "Migration is not initiated");
require(isMigrationInitiated, "Migration is not initiated");
16,809
19
// Get token id by its address
uint16 tokenId = governance.validateTokenAddress(address(_token)); uint256 balance_before = _token.balanceOf(address(this)); require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012"); // token transfer failed deposit uint256 balance_after = _token.balanceOf(address(this)); uint128 deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before)); registerDeposit(tokenId, deposit_amount, _franklinAddr);
uint16 tokenId = governance.validateTokenAddress(address(_token)); uint256 balance_before = _token.balanceOf(address(this)); require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012"); // token transfer failed deposit uint256 balance_after = _token.balanceOf(address(this)); uint128 deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before)); registerDeposit(tokenId, deposit_amount, _franklinAddr);
7,086
71
// ============ State Variables ============
mapping (address => bool) public authorized;
mapping (address => bool) public authorized;
67,160
139
// https:github.com/quantstamp/sushiswap-security-review 3.4 fixed.
function _transfer(address sender, address recipient, uint256 amount) internal override(ERC20) { _moveDelegates(_delegates[sender], _delegates[recipient], amount); ERC20._transfer(sender, recipient, amount); }
function _transfer(address sender, address recipient, uint256 amount) internal override(ERC20) { _moveDelegates(_delegates[sender], _delegates[recipient], amount); ERC20._transfer(sender, recipient, amount); }
33,044
89
// This function is used to calculate the amount of tokens that can be issued. The amount of oTokens is determined by:oTokensIssued<= collateralAmtcollateralToStrikePrice / (proportionstrikePrice) collateralAmt The amount of collateral proportion The proportion of the collateral to pay out. If 100% of collateralshould be paid out, pass in Number(1, 0). The proportion might be less than 100% ifyou are calculating fees. /
function calculateOTokens(uint256 collateralAmt, Number memory proportion) internal view returns (uint256)
function calculateOTokens(uint256 collateralAmt, Number memory proportion) internal view returns (uint256)
46,386
253
// Extracts the previous block's hash from a block header/Block headers do NOT include block number :(/_header The header/ returnThe previous block's hash (little-endian)
function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(4, 32); }
function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(4, 32); }
31,936
51
// returns the upkeep privilege config /
function getUpkeepPrivilegeConfig(uint256 upkeepId) external view returns (bytes memory) { return s_upkeepPrivilegeConfig[upkeepId]; }
function getUpkeepPrivilegeConfig(uint256 upkeepId) external view returns (bytes memory) { return s_upkeepPrivilegeConfig[upkeepId]; }
19,005
159
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. This method is included for ERC20 compatibility. `increaseAllowance` and `decreaseAllowance` should be used instead.Changing an allowance with this method brings the risk that someone may transfer both the old and the new allowance - if they are both greater than zero - if a transfer transaction is mined before the later approve() call is mined. _spender The address which will spend the funds. _value The amount of tokens to be spent. /
function approve(address _spender, uint256 _value) public override returns (bool)
function approve(address _spender, uint256 _value) public override returns (bool)
25,950
17
// tokenId => Side => OrderBook
mapping(uint256 => mapping(Side => OrderBook)) private _markets;
mapping(uint256 => mapping(Side => OrderBook)) private _markets;
18,501
1
// constructor() ERC721("Timeshare", "TSBO") {}
function initialize() public initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Ownable_init_unchained(); __ERC721_init("Timeshare", "SHARE"); __ERC721Enumerable_init_unchained(); __ERC721Holder_init_unchained(); }
function initialize() public initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Ownable_init_unchained(); __ERC721_init("Timeshare", "SHARE"); __ERC721Enumerable_init_unchained(); __ERC721Holder_init_unchained(); }
4,541
46
// id brokers
mapping(bytes32 => address[]) public brokers;
mapping(bytes32 => address[]) public brokers;
21,561
66
// fallback function can be used to buy tokens
function () public payable { buyPhaseTokens(msg.sender); }
function () public payable { buyPhaseTokens(msg.sender); }
8,571
3
// Emits an {OwnershipTransferred} event. newOwner The address of the new owner of the contract. Using the zero address means renouncing ownership. /
function transferOwnership(address newOwner) external;
function transferOwnership(address newOwner) external;
35,983
20
// Price for member sales
uint256 membersSalePrice;
uint256 membersSalePrice;
17,259
15
// offset the bitboard to scan from `bucketIndex`.
bb = bb >> (0xff ^ bucketIndex); // bb >> (255 - bucketIndex) if(bb > 0) { unchecked { return (bucket << 8) | (bucketIndex - bb.bitScanForward256()); }
bb = bb >> (0xff ^ bucketIndex); // bb >> (255 - bucketIndex) if(bb > 0) { unchecked { return (bucket << 8) | (bucketIndex - bb.bitScanForward256()); }
28,258
6
// not sure what was returned: don't mark as success
default { }
default { }
13,445
64
// Gets investment asset active Status of a given currency. /
function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) { return allInvestmentAssets[curr].status; }
function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) { return allInvestmentAssets[curr].status; }
7,930
310
// We leave the round number as non-zero to save on gas for subsequent writes
withdrawals[msg.sender].shares = 0; vaultState.queuedWithdrawShares = uint128( uint256(vaultState.queuedWithdrawShares).sub(withdrawalShares) ); uint256 withdrawAmount = ShareMath.sharesToAsset( withdrawalShares, roundPricePerShare[withdrawalRound], vaultParams.decimals
withdrawals[msg.sender].shares = 0; vaultState.queuedWithdrawShares = uint128( uint256(vaultState.queuedWithdrawShares).sub(withdrawalShares) ); uint256 withdrawAmount = ShareMath.sharesToAsset( withdrawalShares, roundPricePerShare[withdrawalRound], vaultParams.decimals
25,100
328
// write first slot back, it can be still partially occupied, it can also be full
sstore(loc, v256)
sstore(loc, v256)
50,525
160
// Position Set Protocol Collection of helper functions for handling and updating AmorToken Positions CHANGELOG: - Updated editExternalPosition to work when no external position is associated with module /
library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the AmorToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(IAmorToken _AmorToken, address _component) internal view returns(bool) { return _AmorToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the AmorToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(IAmorToken _AmorToken, address _component) internal view returns(bool) { return _AmorToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the AmorToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(IAmorToken _AmorToken, address _component, uint256 _unit) internal view returns(bool) { return _AmorToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the AmorToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( IAmorToken _AmorToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _AmorToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the AmorToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _AmorToken Address of AmorToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(IAmorToken _AmorToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_AmorToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_AmorToken, _component)) { _AmorToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_AmorToken, _component)) { _AmorToken.removeComponent(_component); } } _AmorToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _AmorToken AmorToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( IAmorToken _AmorToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_AmorToken.isComponent(_component)) { _AmorToken.addComponent(_component); _AmorToken.addExternalPositionModule(_component, _module); } else if (!_AmorToken.isExternalPositionModule(_component, _module)) { _AmorToken.addExternalPositionModule(_component, _module); } _AmorToken.editExternalPositionUnit(_component, _module, _newUnit); _AmorToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_AmorToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _AmorToken.getExternalPositionModules(_component); if (_AmorToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _AmorToken.removeComponent(_component); } _AmorToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _AmorTokenSupply Supply of AmorToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _AmorTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _AmorTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _AmorTokenSupply Supply of AmorToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _AmorTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_AmorTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _AmorToken Address of the AmorToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(IAmorToken _AmorToken, address _component) internal view returns(uint256) { int256 positionUnit = _AmorToken.getDefaultPositionRealUnit(_component); return _AmorToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _AmorToken Address of the AmorToken * @param _component Address of the component * @param _setTotalSupply Current AmorToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( IAmorToken _AmorToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_AmorToken)); uint256 positionUnit = _AmorToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_AmorToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes AmorToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _AmorTokenSupply Supply of AmorToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of AmorToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _AmorTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_AmorTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_AmorTokenSupply); } }
library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the AmorToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(IAmorToken _AmorToken, address _component) internal view returns(bool) { return _AmorToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the AmorToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(IAmorToken _AmorToken, address _component) internal view returns(bool) { return _AmorToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the AmorToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(IAmorToken _AmorToken, address _component, uint256 _unit) internal view returns(bool) { return _AmorToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the AmorToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( IAmorToken _AmorToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _AmorToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the AmorToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _AmorToken Address of AmorToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(IAmorToken _AmorToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_AmorToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_AmorToken, _component)) { _AmorToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_AmorToken, _component)) { _AmorToken.removeComponent(_component); } } _AmorToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _AmorToken AmorToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( IAmorToken _AmorToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_AmorToken.isComponent(_component)) { _AmorToken.addComponent(_component); _AmorToken.addExternalPositionModule(_component, _module); } else if (!_AmorToken.isExternalPositionModule(_component, _module)) { _AmorToken.addExternalPositionModule(_component, _module); } _AmorToken.editExternalPositionUnit(_component, _module, _newUnit); _AmorToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_AmorToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _AmorToken.getExternalPositionModules(_component); if (_AmorToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _AmorToken.removeComponent(_component); } _AmorToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _AmorTokenSupply Supply of AmorToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _AmorTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _AmorTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _AmorTokenSupply Supply of AmorToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _AmorTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_AmorTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _AmorToken Address of the AmorToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(IAmorToken _AmorToken, address _component) internal view returns(uint256) { int256 positionUnit = _AmorToken.getDefaultPositionRealUnit(_component); return _AmorToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _AmorToken Address of the AmorToken * @param _component Address of the component * @param _setTotalSupply Current AmorToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( IAmorToken _AmorToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_AmorToken)); uint256 positionUnit = _AmorToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_AmorToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes AmorToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _AmorTokenSupply Supply of AmorToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of AmorToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _AmorTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_AmorTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_AmorTokenSupply); } }
21,951
387
// delegations will never be deleted to index in this array may be used like delegation id
Delegation[] public delegations;
Delegation[] public delegations;
52,793
12
// transfer token for a specified address_to The address to transfer to._value The amount to be transferred./
function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
50,276
191
// public functionplayer submit betonly if game is active & bet is valid can query oraclize and set player vars /
function playerRollDice(uint rollUnder) public payable gameIsActive betIsValid(msg.value, rollUnder)
function playerRollDice(uint rollUnder) public payable gameIsActive betIsValid(msg.value, rollUnder)
69,137
33
// For determining which interface to use
bool isMultiToken = amounts.length == tokenIds.length;
bool isMultiToken = amounts.length == tokenIds.length;
55,728
13
// get the winer address
winer = players[winerIndex];
winer = players[winerIndex];
4,914
23
// Checks if the symbols on reel 2 and 3 are the same and update pos to the corresponding position
if (r2 == r3) pos = 1; payout = (_wager * payouts[r1][pos]); _reels[i] = [r1, r2, r3]; _payouts[i] = payout; _totalPayout += payout;
if (r2 == r3) pos = 1; payout = (_wager * payouts[r1][pos]); _reels[i] = [r1, r2, r3]; _payouts[i] = payout; _totalPayout += payout;
20,277
194
// The block number when yoda mining starts.
uint256 public START_BLOCK; uint256 public constant PERCENT_LOCK_BONUS_REWARD = 75; // lock 75% of bounus reward in 1 year uint256 public constant PERCENT_FOR_DEV = 10; // 10% reward for dev
uint256 public START_BLOCK; uint256 public constant PERCENT_LOCK_BONUS_REWARD = 75; // lock 75% of bounus reward in 1 year uint256 public constant PERCENT_FOR_DEV = 10; // 10% reward for dev
9,089
0
// Counter && Safe Math
using Counters for Counters.Counter; using SafeMath for uint256;
using Counters for Counters.Counter; using SafeMath for uint256;
30,425
44
// get total invested in ETH
function getTotalInvestedEther() external view returns (uint);
function getTotalInvestedEther() external view returns (uint);
47,923
52
// Resume withdrawals /
function resumeWithdrawals() public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to resume withdrawals"); WITHRAWALS_PAUSED = false; emit WithdrawalsResumed(); }
function resumeWithdrawals() public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to resume withdrawals"); WITHRAWALS_PAUSED = false; emit WithdrawalsResumed(); }
41,294
32
// The auction participants.
mapping (address => uint) public participants;
mapping (address => uint) public participants;
38,202
122
// Updates the Prize Strategy when tokens are transferred between holders./from The address the tokens are being transferred from (0 if minting)/to The address the tokens are being transferred to (0 if burning)/amount The amount of tokens being trasferred
function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) { if (from != address(0)) { uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from); // first accrue credit for their old balance uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0); if (from != to) { // if they are sending funds to someone else, we need to limit their accrued credit to their new balance newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance); } _updateCreditBalance(from, msg.sender, newCreditBalance); } if (to != address(0) && to != from) { _accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0); } // if we aren't minting if (from != address(0) && address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender); } }
function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) { if (from != address(0)) { uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from); // first accrue credit for their old balance uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0); if (from != to) { // if they are sending funds to someone else, we need to limit their accrued credit to their new balance newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance); } _updateCreditBalance(from, msg.sender, newCreditBalance); } if (to != address(0) && to != from) { _accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0); } // if we aren't minting if (from != address(0) && address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender); } }
7,030
29
// Test all token addresses at once
require( TokenRegistry(tokenRegistryAddress).areAllTokensRegistered(tokens) ); // "token not registered");
require( TokenRegistry(tokenRegistryAddress).areAllTokensRegistered(tokens) ); // "token not registered");
3,884
68
// The owner can update the rate (PDT to ETH)._ratethe new rate for converting PDT to ETH /
function setRate(uint _rate) public onlyOwner { require(_rate >= LOW_RANGE_RATE && _rate <= HIGH_RANGE_RATE); rate = _rate; }
function setRate(uint _rate) public onlyOwner { require(_rate >= LOW_RANGE_RATE && _rate <= HIGH_RANGE_RATE); rate = _rate; }
39,762
7
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory data) = token.call(
(bool success, bytes memory data) = token.call(
9,312
88
// heist character
if (_victimId==0){ narcoCore.incrementStat(_hijackerId, 5); // raidSuccessful }
if (_victimId==0){ narcoCore.incrementStat(_hijackerId, 5); // raidSuccessful }
35,586
4
// Chi is an atomic currency.It is not possible to have a fraction of a Chi. You are only able to haveinteger values of Chi tokens. /
uint256 public decimals = 0;
uint256 public decimals = 0;
39,112
195
// mint extra ALD to ald DAO
uint256 _percentageContributor = percentageContributor; if (percentageContributor > 0) { IALD(ald).mint(aldDAO, _bond.mul(_percentageContributor).div(PRECISION - _percentageContributor)); }
uint256 _percentageContributor = percentageContributor; if (percentageContributor > 0) { IALD(ald).mint(aldDAO, _bond.mul(_percentageContributor).div(PRECISION - _percentageContributor)); }
24,884
5
// Liquity
address LiquityProxyBorrowerOperations; address LUSD;
address LiquityProxyBorrowerOperations; address LUSD;
51,789
30
// Accept a certificate. /
function acceptCertificate(uint _id) external onlyIdentityPurpose(20002) { Document storage doc = documents[_id]; require(!doc.published && doc.docType >= 60000); // Add to index. doc.index = uint16(documentsIndex.push(_id).sub(1)); // Publish. doc.published = true; // Unpublish related experience, if published. if (documents[doc.related].published) { _deleteDocument(doc.related); } // Emit event. emit CertificateAccepted(doc.fileChecksum, doc.issuer, _id); }
function acceptCertificate(uint _id) external onlyIdentityPurpose(20002) { Document storage doc = documents[_id]; require(!doc.published && doc.docType >= 60000); // Add to index. doc.index = uint16(documentsIndex.push(_id).sub(1)); // Publish. doc.published = true; // Unpublish related experience, if published. if (documents[doc.related].published) { _deleteDocument(doc.related); } // Emit event. emit CertificateAccepted(doc.fileChecksum, doc.issuer, _id); }
11,375
128
// used to return the precise amount of tokens returned
_amount = tokenBalanceAfter - tokenBalanceBefore; withdrawTokens(tokenAddr, _to, _amount); return _amount;
_amount = tokenBalanceAfter - tokenBalanceBefore; withdrawTokens(tokenAddr, _to, _amount); return _amount;
32,618
12
// Setup the interface to the Blocklord contract
function setBLInterface(address newAddress) public onlyOwner { BL = BLInterface(newAddress); }
function setBLInterface(address newAddress) public onlyOwner { BL = BLInterface(newAddress); }
14,775
3
// Color of each token. /
mapping(uint256 => uint256) public pixelColor;
mapping(uint256 => uint256) public pixelColor;
48,995
53
// Transfers the ownership of an WAR from one address to another address/_from The current owner of the WAR/_to The new owner/_tokenId The WAR to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused
31,320
289
// If the lock is expired
if (thisStake.ending_timestamp <= block.timestamp) { // If the lock expired in the time since the last claim, the weight needs to be proportionately averaged this time if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time; uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp; // Average the pre-expiry lock multiplier uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2); // Get the weighted-average lock_multiplier // uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (MULTIPLIER_PRECISION * time_after_expiry); uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry); midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry); } else { // Otherwise, it needs to just be 1x // midpoint_lock_multiplier = MULTIPLIER_PRECISION; // Otherwise, it needs to just be 0x midpoint_lock_multiplier = 0; } }
if (thisStake.ending_timestamp <= block.timestamp) { // If the lock expired in the time since the last claim, the weight needs to be proportionately averaged this time if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = thisStake.ending_timestamp - accrue_start_time; uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp; // Average the pre-expiry lock multiplier uint256 pre_expiry_avg_multiplier = lockMultiplier(time_before_expiry / 2); // Get the weighted-average lock_multiplier // uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (MULTIPLIER_PRECISION * time_after_expiry); uint256 numerator = (pre_expiry_avg_multiplier * time_before_expiry) + (0 * time_after_expiry); midpoint_lock_multiplier = numerator / (time_before_expiry + time_after_expiry); } else { // Otherwise, it needs to just be 1x // midpoint_lock_multiplier = MULTIPLIER_PRECISION; // Otherwise, it needs to just be 0x midpoint_lock_multiplier = 0; } }
17,881
4
// Allows a user to supply asset tokens in exchange for yield-bearing tokens/ to be held in escrow by the Yield Service/amount The amount of asset tokens to be supplied
function _supply(uint256 amount) internal override { _token().safeApprove(address(cToken), amount); require(cToken.mint(amount) == 0, "CompoundPrizePool/mint-failed"); }
function _supply(uint256 amount) internal override { _token().safeApprove(address(cToken), amount); require(cToken.mint(amount) == 0, "CompoundPrizePool/mint-failed"); }
6,971
81
// Mints `quantity` tokens and transfers them to `to`. Requirements: - `to` cannot be the zero address.- `quantity` must be greater than 0.
* Emits a {Transfer} event for each mint. */ function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = ERC721AStorage.layout()._currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // `balance` and `numberMinted` have a maximum limit of 2**64. // `tokenId` has a maximum limit of 2**256. unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. ERC721AStorage.layout()._packedOwnerships[ startTokenId ] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 toMasked; uint256 end = startTokenId + quantity; // Use assembly to loop and emit the `Transfer` event for gas savings. // The duplicated `log4` removes an extra check and reduces stack juggling. // The assembly, together with the surrounding Solidity code, have been // delicately arranged to nudge the compiler into producing optimized opcodes. assembly { // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. toMasked := and(to, _BITMASK_ADDRESS) // Emit the `Transfer` event. log4( 0, // Start of data (0, since no data). 0, // End of data (0, since no data). _TRANSFER_EVENT_SIGNATURE, // Signature. 0, // `address(0)`. toMasked, // `to`. startTokenId // `tokenId`. ) // The `iszero(eq(,))` check ensures that large values of `quantity` // that overflows uint256 will make the loop run out of gas. // The compiler will optimize the `iszero` away for performance. for { let tokenId := add(startTokenId, 1) } iszero(eq(tokenId, end)) { tokenId := add(tokenId, 1) } { // Emit the `Transfer` event. Similar to above. log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); ERC721AStorage.layout()._currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
* Emits a {Transfer} event for each mint. */ function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = ERC721AStorage.layout()._currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // `balance` and `numberMinted` have a maximum limit of 2**64. // `tokenId` has a maximum limit of 2**256. unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. ERC721AStorage.layout()._packedOwnerships[ startTokenId ] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 toMasked; uint256 end = startTokenId + quantity; // Use assembly to loop and emit the `Transfer` event for gas savings. // The duplicated `log4` removes an extra check and reduces stack juggling. // The assembly, together with the surrounding Solidity code, have been // delicately arranged to nudge the compiler into producing optimized opcodes. assembly { // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. toMasked := and(to, _BITMASK_ADDRESS) // Emit the `Transfer` event. log4( 0, // Start of data (0, since no data). 0, // End of data (0, since no data). _TRANSFER_EVENT_SIGNATURE, // Signature. 0, // `address(0)`. toMasked, // `to`. startTokenId // `tokenId`. ) // The `iszero(eq(,))` check ensures that large values of `quantity` // that overflows uint256 will make the loop run out of gas. // The compiler will optimize the `iszero` away for performance. for { let tokenId := add(startTokenId, 1) } iszero(eq(tokenId, end)) { tokenId := add(tokenId, 1) } { // Emit the `Transfer` event. Similar to above. log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); ERC721AStorage.layout()._currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
10,877
0
// if totalSupply_ is 0, then unlimited supply
uint256 totalSupply; uint256 price; string description; uint256 maxPerWallet;
uint256 totalSupply; uint256 price; string description; uint256 maxPerWallet;
31,381
12
// set minimum amount and make sure ad hasnt expired
require(msg.value >= adPriceWeek); require(block.timestamp > purchaseTimestamp.add(purchaseSeconds));
require(msg.value >= adPriceWeek); require(block.timestamp > purchaseTimestamp.add(purchaseSeconds));
49,722
167
// RainbowToken with Governance.
contract RainbowToken is ERC20("RainbowToken", "RAINBOW"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from SUSHI code: // https://etherscan.io/address/0xc2edad668740f1aa35e4d8f227fb8e17dca888cd#code // Which is copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "RAINBOW::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "RAINBOW::delegateBySig: invalid nonce"); require(now <= expiry, "RAINBOW::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "RAINBOW::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying RAINBOWs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "RAINBOW::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract RainbowToken is ERC20("RainbowToken", "RAINBOW"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from SUSHI code: // https://etherscan.io/address/0xc2edad668740f1aa35e4d8f227fb8e17dca888cd#code // Which is copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "RAINBOW::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "RAINBOW::delegateBySig: invalid nonce"); require(now <= expiry, "RAINBOW::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "RAINBOW::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying RAINBOWs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "RAINBOW::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
67,649
116
// return the number of tokens in exporting state /
function countStatedTokens(State state) external view returns(uint256);
function countStatedTokens(State state) external view returns(uint256);
39,626
227
// Reference to other contracts
CarToken public token;
CarToken public token;
49,863