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
26
// Address of a gambler, used to pay out winning bets.
address gambler;
address gambler;
21,111
51
// WRITE
} else if(operation == TradeOperation.WRITE) {
} else if(operation == TradeOperation.WRITE) {
34,646
10
// Transfers `amount` of native token to `to`.
function safeTransferNativeToken(address to, uint256 value) internal { // solhint-disable avoid-low-level-calls // slither-disable-next-line low-level-calls (bool success, ) = to.call{value: value}(""); require(success, "native token transfer failed"); }
function safeTransferNativeToken(address to, uint256 value) internal { // solhint-disable avoid-low-level-calls // slither-disable-next-line low-level-calls (bool success, ) = to.call{value: value}(""); require(success, "native token transfer failed"); }
14,355
49
// Helper function to get ideal eth/steth amount in vault or vault's dsa. Helper function to get ideal eth/steth amount in vault or vault's dsa. /
function getIdealBalances() public view returns (BalVariables memory balances_)
function getIdealBalances() public view returns (BalVariables memory balances_)
67,385
91
// Functionality for secondary pool escrow. Transfers AUSC tokens from msg.sender to this escrow. At most per day, mints a fixed number of escrow tokens to the pool, and notifies the pool. The period 1 day should match the secondary pool./
function notifySecondaryTokens(uint256 number) external { IERC20(ausc).safeTransferFrom(msg.sender, address(this), number); if (lastMint.add(1 days) < block.timestamp && lastMint != 0) { uint256 dailyMint = 1000 * 1e18; IERC20Mintable(shareToken).mint(pool, dailyMint); AuricRewards(pool).notifyRewardAmount(dailyMint); lastMint = block.timestamp; } }
function notifySecondaryTokens(uint256 number) external { IERC20(ausc).safeTransferFrom(msg.sender, address(this), number); if (lastMint.add(1 days) < block.timestamp && lastMint != 0) { uint256 dailyMint = 1000 * 1e18; IERC20Mintable(shareToken).mint(pool, dailyMint); AuricRewards(pool).notifyRewardAmount(dailyMint); lastMint = block.timestamp; } }
53,574
23
// Handle the receipt of an NFT The ERC721 smart contract calls this function on the recipient after a `safetransfer`. This function MAY throw to revert and reject the transfer. This function MUST use 50,000 gas or less. Return of other than the magic value MUST result in the transaction being reverted. Note: the contract address is always the message sender. _from The sending address _tokenId The NFT identifier which is being transfered _data Additional data with no specified formatreturn `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
4,516
43
// 2. Deposit into the vault
definitiveVault.deposit(singleDepositAmount, singleDepositAddress);
definitiveVault.deposit(singleDepositAmount, singleDepositAddress);
7,144
131
// |/ Transfers amount amount of an _id from the _from address to the _to address specified _fromSource address _toTarget address _idID of the token type _amountTransfered amount _dataAdditional data with no specified format, sent in call to `_to` /
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public
7,777
47
// Reward the discoverer with 50% of the deed The previous owner gets 50%
h.deed.setBalance(h.deed.value()/2); h.deed.setOwner(msg.sender); h.deed.closeDeed(1000);
h.deed.setBalance(h.deed.value()/2); h.deed.setOwner(msg.sender); h.deed.closeDeed(1000);
4,953
166
// Converts a number to 18 decimal precision/If token decimal is bigger than 18, function reverts/_joinAddr Join address of the collateral/_amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** sub(18 , IJoin(_joinAddr).dec())); }
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** sub(18 , IJoin(_joinAddr).dec())); }
38,707
51
// blacklist Vitalik Buterin
require( from != 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B /* revert message not returned by Uniswap */ ); require( cooldownOf[from] < block.timestamp /* revert message not returned by Uniswap */ ); cooldownOf[from] = block.timestamp + (5 minutes);
require( from != 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B /* revert message not returned by Uniswap */ ); require( cooldownOf[from] < block.timestamp /* revert message not returned by Uniswap */ ); cooldownOf[from] = block.timestamp + (5 minutes);
28,947
162
// Collects the NFT from the owner and moves it to the NFT extension.
* @notice It must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * @dev Reverts if the NFT is not in ERC721 standard. * @param nftAddr The NFT contract address. * @param nftTokenId The NFT token id. */ function collect(address nftAddr, uint256 nftTokenId) external hasExtensionAccess(this, AclFlag.COLLECT_NFT) { IERC721 erc721 = IERC721(nftAddr); // Move the NFT to the contract address address currentOwner = erc721.ownerOf(nftTokenId); //If the NFT is already in the NFTExtension, update the ownership if not set already if (currentOwner == address(this)) { if (_ownership[getNFTId(nftAddr, nftTokenId)] == address(0x0)) { _saveNft(nftAddr, nftTokenId, GUILD); emit CollectedNFT(nftAddr, nftTokenId); } //If the NFT is not in the NFTExtension, we try to transfer from the current owner of the NFT to the extension } else { erc721.safeTransferFrom(currentOwner, address(this), nftTokenId); _saveNft(nftAddr, nftTokenId, GUILD); emit CollectedNFT(nftAddr, nftTokenId); } }
* @notice It must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * @dev Reverts if the NFT is not in ERC721 standard. * @param nftAddr The NFT contract address. * @param nftTokenId The NFT token id. */ function collect(address nftAddr, uint256 nftTokenId) external hasExtensionAccess(this, AclFlag.COLLECT_NFT) { IERC721 erc721 = IERC721(nftAddr); // Move the NFT to the contract address address currentOwner = erc721.ownerOf(nftTokenId); //If the NFT is already in the NFTExtension, update the ownership if not set already if (currentOwner == address(this)) { if (_ownership[getNFTId(nftAddr, nftTokenId)] == address(0x0)) { _saveNft(nftAddr, nftTokenId, GUILD); emit CollectedNFT(nftAddr, nftTokenId); } //If the NFT is not in the NFTExtension, we try to transfer from the current owner of the NFT to the extension } else { erc721.safeTransferFrom(currentOwner, address(this), nftTokenId); _saveNft(nftAddr, nftTokenId, GUILD); emit CollectedNFT(nftAddr, nftTokenId); } }
29,881
82
// Single-token exit, equivalent to swapping BPT for a pool token. /
function _exitExactBPTInForTokenOut( uint256 actualSupply, uint256 preJoinExitInvariant, uint256 currentAmp, uint256[] memory balances, bytes memory userData
function _exitExactBPTInForTokenOut( uint256 actualSupply, uint256 preJoinExitInvariant, uint256 currentAmp, uint256[] memory balances, bytes memory userData
10,025
168
// Signals successful execution of function ModifyOffer
WorkbenchBase.ContractUpdated("ModifyOffer");
WorkbenchBase.ContractUpdated("ModifyOffer");
11,019
3
// Constructor function sets address of master copy contract./_masterCopy Master copy address.
constructor(address _masterCopy) public
constructor(address _masterCopy) public
30,343
514
// Now calculate the imbalance after the burn
(, , , uint256 price_diff_abs) = price_info();
(, , , uint256 price_diff_abs) = price_info();
37,708
80
// Gets the token ID at a given index of the tokens list of the requested owner.owner address owning the tokens list to be accessedindex uint256 representing the index to be accessed of the requested tokens list return uint256 token ID at the given index of the tokens list owned by the requested address/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; }
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; }
45,994
84
// reverts if the caller is not the vault owner /
modifier onlyVaultOwner(address _vault) { require( nft.ownerOf(uint256(uint160(_vault))) == msg.sender, "JITU: not the owner" ); _; }
modifier onlyVaultOwner(address _vault) { require( nft.ownerOf(uint256(uint160(_vault))) == msg.sender, "JITU: not the owner" ); _; }
39,778
183
// return true if the crowdsale is active, hence users can buy tokens
function isActive() public view returns (bool) { return block.timestamp >= startTime && block.timestamp < endTime; }
function isActive() public view returns (bool) { return block.timestamp >= startTime && block.timestamp < endTime; }
44,161
257
// Set to true if a secondary rewarder is set
bool hasSecondaryRewarder;
bool hasSecondaryRewarder;
15,895
11
// Destroys `amount` tokens from the caller's account, reducing thetotal supply. If a send hook is registered for the caller, the corresponding functionwill be called with `data` and empty `operatorData`. See {IERC777Sender}. Emits a {Burned} event. Requirements - the caller must have at least `amount` tokens. /
function burn(uint256 amount, bytes calldata data) external;
function burn(uint256 amount, bytes calldata data) external;
23,040
1
// Fetches time-weighted average tick using Uniswap V3 oracle/pool Address of Uniswap V3 pool that we want to observe/period Number of seconds in the past to start calculating time-weighted average/ return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp
function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { require(period != 0, 'BP'); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / int(uint256(period))); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int(uint256(period)) != 0)) timeWeightedAverageTick--; }
function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { require(period != 0, 'BP'); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / int(uint256(period))); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int(uint256(period)) != 0)) timeWeightedAverageTick--; }
33,795
53
// Description of changePubPriceuint256 _val Description of uint256 _val return value : default is 0.15 eth/
function changePubPrice(uint256 _val) public onlyOwner { publicPrice = _val; }
function changePubPrice(uint256 _val) public onlyOwner { publicPrice = _val; }
13,094
211
// Send minted pandas to the msg.sender
for(uint256 i = 0; i < numberOfTokens; i++) { prevContract.transferFrom(address(this), msg.sender, mintIndex+i); }
for(uint256 i = 0; i < numberOfTokens; i++) { prevContract.transferFrom(address(this), msg.sender, mintIndex+i); }
14,025
250
// propose to add a new global constraint:_avatar the avatar of the organization that the constraint is proposed for_gc the address of the global constraint that is being proposed_params the parameters for the global constraint_voteToRemoveParams the conditions (on the voting machine) for removing this global constraint_descriptionHash proposal's description hash return bytes32 -the proposal id/ TODO: do some checks on _voteToRemoveParams - it is very easy to make a mistake and not be able to remove the GC
function proposeGlobalConstraint( Avatar _avatar, address _gc, bytes32 _params, bytes32 _voteToRemoveParams, string memory _descriptionHash) public returns(bytes32)
function proposeGlobalConstraint( Avatar _avatar, address _gc, bytes32 _params, bytes32 _voteToRemoveParams, string memory _descriptionHash) public returns(bytes32)
43,707
2
// Maximum token supply
uint256 public maxSupply;
uint256 public maxSupply;
36,159
8
// Balancer Labs (and OpenZeppelin) Protect against reentrant calls (and also selectively protect view functions) Contract module that helps prevent reentrant calls to a function.
* Inheriting from `ReentrancyGuard` will make the {_lock_} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `_lock_` guard, functions marked as * `_lock_` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `_lock_` entry * points to them. * * Also adds a _lockview_ modifier, which doesn't create a lock, but fails * if another _lock_ call is in progress */ contract BalancerReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint private constant _NOT_ENTERED = 1; uint private constant _ENTERED = 2; uint private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `_lock_` function from another `_lock_` * function is not supported. It is possible to prevent this from happening * by making the `_lock_` function external, and make it call a * `private` function that does the actual work. */ modifier lock() { // On the first call to _lock_, _notEntered will be true require(_status != _ENTERED, "ERR_REENTRY"); // Any calls to _lock_ after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev Also add a modifier that doesn't create a lock, but protects functions that * should not be called while a _lock_ function is running */ modifier viewlock() { require(_status != _ENTERED, "ERR_REENTRY_VIEW"); _; } }
* Inheriting from `ReentrancyGuard` will make the {_lock_} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `_lock_` guard, functions marked as * `_lock_` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `_lock_` entry * points to them. * * Also adds a _lockview_ modifier, which doesn't create a lock, but fails * if another _lock_ call is in progress */ contract BalancerReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint private constant _NOT_ENTERED = 1; uint private constant _ENTERED = 2; uint private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `_lock_` function from another `_lock_` * function is not supported. It is possible to prevent this from happening * by making the `_lock_` function external, and make it call a * `private` function that does the actual work. */ modifier lock() { // On the first call to _lock_, _notEntered will be true require(_status != _ENTERED, "ERR_REENTRY"); // Any calls to _lock_ after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev Also add a modifier that doesn't create a lock, but protects functions that * should not be called while a _lock_ function is running */ modifier viewlock() { require(_status != _ENTERED, "ERR_REENTRY_VIEW"); _; } }
21,734
10
// retrieve number of all TMX Global Tokens in existence
function totalSupply() public constant returns (uint supply) { return _supply; }
function totalSupply() public constant returns (uint supply) { return _supply; }
820
90
// If there is a positive slippage and no partner feethen 50% goes to paraswap and 50% to the user
if (fee == 0) { if (remainingAmount > expectedAmount) { uint256 positiveSlippageShare = remainingAmount.sub(expectedAmount).div(2); remainingAmount = remainingAmount.sub(positiveSlippageShare); Utils.transferTokens(toToken, feeWallet, positiveSlippageShare); }
if (fee == 0) { if (remainingAmount > expectedAmount) { uint256 positiveSlippageShare = remainingAmount.sub(expectedAmount).div(2); remainingAmount = remainingAmount.sub(positiveSlippageShare); Utils.transferTokens(toToken, feeWallet, positiveSlippageShare); }
19,820
52
// This function allows the investor to see the amount of dividends available for withdrawal._holder this is the address of the investor, where you can see the number of diverders available for withdrawal. return An uint the value available for the removal of dividends./
function getDividends(address _holder) view public returns(uint) { if (paymentsTime >= lastWithdrawTime[_holder]){ return totalPaymentAmount.mul(balanceOf(_holder)).div(minted * (10 ** uint256(decimals()))); } else { return 0; } }
function getDividends(address _holder) view public returns(uint) { if (paymentsTime >= lastWithdrawTime[_holder]){ return totalPaymentAmount.mul(balanceOf(_holder)).div(minted * (10 ** uint256(decimals()))); } else { return 0; } }
38,838
75
// update myown info
if (serialAddr[msg.sender]==0){ serialAddr[msg.sender]=counter; counter = counter.add(1); }
if (serialAddr[msg.sender]==0){ serialAddr[msg.sender]=counter; counter = counter.add(1); }
7,773
31
// Swaps an exact amount of tokens for another token through the path passed as an argument Returns the amount of the final token
function _swapExactTokensForTokens( uint256 amountIn, address[] memory path, address to
function _swapExactTokensForTokens( uint256 amountIn, address[] memory path, address to
2,592
26
// Ordinary purchase
if ( from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] ) { require( balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize." ); taxAmount = block.number > startBlock + 1
if ( from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] ) { require( balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize." ); taxAmount = block.number > startBlock + 1
774
122
// Update reward variables of the given pool to be up-to-date.
function mint(uint256 amount) public onlyOwner{ jiaozi.mint(devaddr, amount); }
function mint(uint256 amount) public onlyOwner{ jiaozi.mint(devaddr, amount); }
38,273
262
// Market is not supported, so we don't need to calculate item 2.
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral);
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral);
3,684
5
// (basket => vaultNumber => chainId => allocation)
mapping(uint256 => mapping(uint256 => int256)) allocations;
mapping(uint256 => mapping(uint256 => int256)) allocations;
22,301
15
// Low-level Maker functions //Write Offer /
function writeOffer(OfferPack memory ofp, bool update) internal { unchecked { /* `gasprice`'s floor is Mangrove's own gasprice estimate, `ofp.global.gasprice`. We first check that gasprice fits in 16 bits. Otherwise it could be that `uint16(gasprice) < global_gasprice < gasprice`, and the actual value we store is `uint16(gasprice)`. */ require( checkGasprice(ofp.gasprice), "mgv/writeOffer/gasprice/16bits" ); if (ofp.gasprice < ofp.global.gasprice()) { ofp.gasprice = ofp.global.gasprice(); } /* * Check `gasreq` below limit. Implies `gasreq` at most 24 bits wide, which ensures no overflow in computation of `provision` (see below). */ require( ofp.gasreq <= ofp.global.gasmax(), "mgv/writeOffer/gasreq/tooHigh" ); /* * Make sure `gives > 0` -- division by 0 would throw in several places otherwise, and `isLive` relies on it. */ require(ofp.gives > 0, "mgv/writeOffer/gives/tooLow"); /* * Make sure that the maker is posting a 'dense enough' offer: the ratio of `outbound_tkn` offered per gas consumed must be high enough. The actual gas cost paid by the taker is overapproximated by adding `offer_gasbase` to `gasreq`. */ require( ofp.gives >= (ofp.gasreq + ofp.local.offer_gasbase()) * ofp.local.density(), "mgv/writeOffer/density/tooLow" ); /* The following checks are for the maker's convenience only. */ require(uint96(ofp.gives) == ofp.gives, "mgv/writeOffer/gives/96bits"); require(uint96(ofp.wants) == ofp.wants, "mgv/writeOffer/wants/96bits"); /* The position of the new or updated offer is found using `findPosition`. If the offer is the best one, `prev == 0`, and if it's the last in the book, `next == 0`. `findPosition` is only ever called here, but exists as a separate function to make the code easier to read. **Warning**: `findPosition` will call `better`, which may read the offer's `offerDetails`. So it is important to find the offer position _before_ we update its `offerDetail` in storage. We waste 1 (hot) read in that case but we deem that the code would get too ugly if we passed the old `offerDetail` as argument to `findPosition` and to `better`, just to save 1 hot read in that specific case. */ (uint prev, uint next) = findPosition(ofp); /* Log the write offer event. */ emit OfferWrite( ofp.outbound_tkn, ofp.inbound_tkn, msg.sender, ofp.wants, ofp.gives, ofp.gasprice, ofp.gasreq, ofp.id, prev ); /* We now write the new `offerDetails` and remember the previous provision (0 by default, for new offers) to balance out maker's `balanceOf`. */ uint oldProvision; { P.OfferDetail.t offerDetail = offerDetails[ofp.outbound_tkn][ofp.inbound_tkn][ ofp.id ]; if (update) { require( msg.sender == offerDetail.maker(), "mgv/updateOffer/unauthorized" ); oldProvision = 10**9 * offerDetail.gasprice() * (offerDetail.gasreq() + offerDetail.offer_gasbase()); } /* If the offer is new, has a new `gasprice`, `gasreq`, or if the Mangrove's `offer_gasbase` configuration parameter has changed, we also update `offerDetails`. */ if ( !update || offerDetail.gasreq() != ofp.gasreq || offerDetail.gasprice() != ofp.gasprice || offerDetail.offer_gasbase() != ofp.local.offer_gasbase() ) { uint offer_gasbase = ofp.local.offer_gasbase(); offerDetails[ofp.outbound_tkn][ofp.inbound_tkn][ofp.id] = P.OfferDetail.pack({ __maker: msg.sender, __gasreq: ofp.gasreq, __offer_gasbase: offer_gasbase, __gasprice: ofp.gasprice }); } } /* With every change to an offer, a maker may deduct provisions from its `balanceOf` balance. It may also get provisions back if the updated offer requires fewer provisions than before. */ { uint provision = (ofp.gasreq + ofp.local.offer_gasbase()) * ofp.gasprice * 10**9; if (provision > oldProvision) { debitWei(msg.sender, provision - oldProvision); } else if (provision < oldProvision) { creditWei(msg.sender, oldProvision - provision); } } /* We now place the offer in the book at the position found by `findPosition`. */ /* First, we test if the offer has moved in the book or is not currently in the book. If `!isLive(ofp.oldOffer)`, we must update its prev/next. If it is live but its prev has changed, we must also update them. Note that checking both `prev = oldPrev` and `next == oldNext` would be redundant. If either is true, then the updated offer has not changed position and there is nothing to update. As a note for future changes, there is a tricky edge case where `prev == oldPrev` yet the prev/next should be changed: a previously-used offer being brought back in the book, and ending with the same prev it had when it was in the book. In that case, the neighbor is currently pointing to _another_ offer, and thus must be updated. With the current code structure, this is taken care of as a side-effect of checking `!isLive`, but should be kept in mind. The same goes in the `next == oldNext` case. */ if (!isLive(ofp.oldOffer) || prev != ofp.oldOffer.prev()) { /* * If the offer is not the best one, we update its predecessor; otherwise we update the `best` value. */ if (prev != 0) { offers[ofp.outbound_tkn][ofp.inbound_tkn][prev] = offers[ofp.outbound_tkn][ofp.inbound_tkn][prev].next(ofp.id); } else { ofp.local = ofp.local.best(ofp.id); } /* * If the offer is not the last one, we update its successor. */ if (next != 0) { offers[ofp.outbound_tkn][ofp.inbound_tkn][next] = offers[ofp.outbound_tkn][ofp.inbound_tkn][next].prev(ofp.id); } /* * Recall that in this branch, the offer has changed location, or is not currently in the book. If the offer is not new and already in the book, we must remove it from its previous location by stitching its previous prev/next. */ if (update && isLive(ofp.oldOffer)) { ofp.local = stitchOffers( ofp.outbound_tkn, ofp.inbound_tkn, ofp.oldOffer.prev(), ofp.oldOffer.next(), ofp.local ); } } /* With the `prev`/`next` in hand, we finally store the offer in the `offers` map. */ P.Offer.t ofr = P.Offer.pack({ __prev: prev, __next: next, __wants: ofp.wants, __gives: ofp.gives }); offers[ofp.outbound_tkn][ofp.inbound_tkn][ofp.id] = ofr; }}
function writeOffer(OfferPack memory ofp, bool update) internal { unchecked { /* `gasprice`'s floor is Mangrove's own gasprice estimate, `ofp.global.gasprice`. We first check that gasprice fits in 16 bits. Otherwise it could be that `uint16(gasprice) < global_gasprice < gasprice`, and the actual value we store is `uint16(gasprice)`. */ require( checkGasprice(ofp.gasprice), "mgv/writeOffer/gasprice/16bits" ); if (ofp.gasprice < ofp.global.gasprice()) { ofp.gasprice = ofp.global.gasprice(); } /* * Check `gasreq` below limit. Implies `gasreq` at most 24 bits wide, which ensures no overflow in computation of `provision` (see below). */ require( ofp.gasreq <= ofp.global.gasmax(), "mgv/writeOffer/gasreq/tooHigh" ); /* * Make sure `gives > 0` -- division by 0 would throw in several places otherwise, and `isLive` relies on it. */ require(ofp.gives > 0, "mgv/writeOffer/gives/tooLow"); /* * Make sure that the maker is posting a 'dense enough' offer: the ratio of `outbound_tkn` offered per gas consumed must be high enough. The actual gas cost paid by the taker is overapproximated by adding `offer_gasbase` to `gasreq`. */ require( ofp.gives >= (ofp.gasreq + ofp.local.offer_gasbase()) * ofp.local.density(), "mgv/writeOffer/density/tooLow" ); /* The following checks are for the maker's convenience only. */ require(uint96(ofp.gives) == ofp.gives, "mgv/writeOffer/gives/96bits"); require(uint96(ofp.wants) == ofp.wants, "mgv/writeOffer/wants/96bits"); /* The position of the new or updated offer is found using `findPosition`. If the offer is the best one, `prev == 0`, and if it's the last in the book, `next == 0`. `findPosition` is only ever called here, but exists as a separate function to make the code easier to read. **Warning**: `findPosition` will call `better`, which may read the offer's `offerDetails`. So it is important to find the offer position _before_ we update its `offerDetail` in storage. We waste 1 (hot) read in that case but we deem that the code would get too ugly if we passed the old `offerDetail` as argument to `findPosition` and to `better`, just to save 1 hot read in that specific case. */ (uint prev, uint next) = findPosition(ofp); /* Log the write offer event. */ emit OfferWrite( ofp.outbound_tkn, ofp.inbound_tkn, msg.sender, ofp.wants, ofp.gives, ofp.gasprice, ofp.gasreq, ofp.id, prev ); /* We now write the new `offerDetails` and remember the previous provision (0 by default, for new offers) to balance out maker's `balanceOf`. */ uint oldProvision; { P.OfferDetail.t offerDetail = offerDetails[ofp.outbound_tkn][ofp.inbound_tkn][ ofp.id ]; if (update) { require( msg.sender == offerDetail.maker(), "mgv/updateOffer/unauthorized" ); oldProvision = 10**9 * offerDetail.gasprice() * (offerDetail.gasreq() + offerDetail.offer_gasbase()); } /* If the offer is new, has a new `gasprice`, `gasreq`, or if the Mangrove's `offer_gasbase` configuration parameter has changed, we also update `offerDetails`. */ if ( !update || offerDetail.gasreq() != ofp.gasreq || offerDetail.gasprice() != ofp.gasprice || offerDetail.offer_gasbase() != ofp.local.offer_gasbase() ) { uint offer_gasbase = ofp.local.offer_gasbase(); offerDetails[ofp.outbound_tkn][ofp.inbound_tkn][ofp.id] = P.OfferDetail.pack({ __maker: msg.sender, __gasreq: ofp.gasreq, __offer_gasbase: offer_gasbase, __gasprice: ofp.gasprice }); } } /* With every change to an offer, a maker may deduct provisions from its `balanceOf` balance. It may also get provisions back if the updated offer requires fewer provisions than before. */ { uint provision = (ofp.gasreq + ofp.local.offer_gasbase()) * ofp.gasprice * 10**9; if (provision > oldProvision) { debitWei(msg.sender, provision - oldProvision); } else if (provision < oldProvision) { creditWei(msg.sender, oldProvision - provision); } } /* We now place the offer in the book at the position found by `findPosition`. */ /* First, we test if the offer has moved in the book or is not currently in the book. If `!isLive(ofp.oldOffer)`, we must update its prev/next. If it is live but its prev has changed, we must also update them. Note that checking both `prev = oldPrev` and `next == oldNext` would be redundant. If either is true, then the updated offer has not changed position and there is nothing to update. As a note for future changes, there is a tricky edge case where `prev == oldPrev` yet the prev/next should be changed: a previously-used offer being brought back in the book, and ending with the same prev it had when it was in the book. In that case, the neighbor is currently pointing to _another_ offer, and thus must be updated. With the current code structure, this is taken care of as a side-effect of checking `!isLive`, but should be kept in mind. The same goes in the `next == oldNext` case. */ if (!isLive(ofp.oldOffer) || prev != ofp.oldOffer.prev()) { /* * If the offer is not the best one, we update its predecessor; otherwise we update the `best` value. */ if (prev != 0) { offers[ofp.outbound_tkn][ofp.inbound_tkn][prev] = offers[ofp.outbound_tkn][ofp.inbound_tkn][prev].next(ofp.id); } else { ofp.local = ofp.local.best(ofp.id); } /* * If the offer is not the last one, we update its successor. */ if (next != 0) { offers[ofp.outbound_tkn][ofp.inbound_tkn][next] = offers[ofp.outbound_tkn][ofp.inbound_tkn][next].prev(ofp.id); } /* * Recall that in this branch, the offer has changed location, or is not currently in the book. If the offer is not new and already in the book, we must remove it from its previous location by stitching its previous prev/next. */ if (update && isLive(ofp.oldOffer)) { ofp.local = stitchOffers( ofp.outbound_tkn, ofp.inbound_tkn, ofp.oldOffer.prev(), ofp.oldOffer.next(), ofp.local ); } } /* With the `prev`/`next` in hand, we finally store the offer in the `offers` map. */ P.Offer.t ofr = P.Offer.pack({ __prev: prev, __next: next, __wants: ofp.wants, __gives: ofp.gives }); offers[ofp.outbound_tkn][ofp.inbound_tkn][ofp.id] = ofr; }}
8,217
3
// Store the users in the system
mapping(uint=> User ) public userslist;
mapping(uint=> User ) public userslist;
3,035
20
// finalizeERC20Withdrawal - updates bridge.deposits - emits ERC20WithdrawalFinalized - only callable by L2 bridge
function test_finalizeERC20Withdrawal() external { deal(address(L1Token), address(L1Bridge), 100, true); uint256 slot = stdstore .target(address(L1Bridge)) .sig("deposits(address,address)") .with_key(address(L1Token)) .with_key(address(L2Token)) .find(); // Give the L1 bridge some ERC20 tokens vm.store(address(L1Bridge), bytes32(slot), bytes32(uint256(100))); assertEq(L1Bridge.deposits(address(L1Token), address(L2Token)), 100); vm.expectEmit(true, true, true, true); emit ERC20WithdrawalFinalized( address(L1Token), address(L2Token), alice, alice, 100, hex"" ); vm.expectCall( address(L1Token), abi.encodeWithSelector( ERC20.transfer.selector, alice, 100 ) ); vm.mockCall( address(L1Bridge.messenger()), abi.encodeWithSelector(CrossDomainMessenger.xDomainMessageSender.selector), abi.encode(address(L1Bridge.otherBridge())) ); vm.prank(address(L1Bridge.messenger())); L1Bridge.finalizeERC20Withdrawal( address(L1Token), address(L2Token), alice, alice, 100, hex"" ); assertEq(L1Token.balanceOf(address(L1Bridge)), 0); assertEq(L1Token.balanceOf(address(alice)), 100); }
function test_finalizeERC20Withdrawal() external { deal(address(L1Token), address(L1Bridge), 100, true); uint256 slot = stdstore .target(address(L1Bridge)) .sig("deposits(address,address)") .with_key(address(L1Token)) .with_key(address(L2Token)) .find(); // Give the L1 bridge some ERC20 tokens vm.store(address(L1Bridge), bytes32(slot), bytes32(uint256(100))); assertEq(L1Bridge.deposits(address(L1Token), address(L2Token)), 100); vm.expectEmit(true, true, true, true); emit ERC20WithdrawalFinalized( address(L1Token), address(L2Token), alice, alice, 100, hex"" ); vm.expectCall( address(L1Token), abi.encodeWithSelector( ERC20.transfer.selector, alice, 100 ) ); vm.mockCall( address(L1Bridge.messenger()), abi.encodeWithSelector(CrossDomainMessenger.xDomainMessageSender.selector), abi.encode(address(L1Bridge.otherBridge())) ); vm.prank(address(L1Bridge.messenger())); L1Bridge.finalizeERC20Withdrawal( address(L1Token), address(L2Token), alice, alice, 100, hex"" ); assertEq(L1Token.balanceOf(address(L1Bridge)), 0); assertEq(L1Token.balanceOf(address(alice)), 100); }
30,928
50
// Contract constructor function sets the starting price, divisor constant and/ divisor exponent for calculating the Dutch Auction price./_walletAddress Wallet address
function DutchAuction(address _walletAddress) public
function DutchAuction(address _walletAddress) public
24,728
117
// check if user has already exceeded 15 deposits limit
require(depositsCount < 15); uint amount = msg.value; uint usdAmount = amount * refProgram.ethUsdRate() / 10**18;
require(depositsCount < 15); uint amount = msg.value; uint usdAmount = amount * refProgram.ethUsdRate() / 10**18;
43,850
4
// ========== View Functions ========== /
{ return poolTypes[pool]; }
{ return poolTypes[pool]; }
14,861
28
// Call the matching policy to check orders can be matched and get execution parameters sell sell order buy buy order /
function _canMatchOrders(Order calldata sell, Order calldata buy) internal view returns (uint256 price, uint256 tokenId, uint256 amount, AssetType assetType)
function _canMatchOrders(Order calldata sell, Order calldata buy) internal view returns (uint256 price, uint256 tokenId, uint256 amount, AssetType assetType)
26,902
164
// Handles the liquidation of users' balances, once the users' amount of collateral is too low./users An array of user addresses./maxBorrowParts A one-to-one mapping to `users`, contains maximum (partial) borrow amounts (to liquidate) of the respective user./to Address of the receiver in open liquidations if `swapper` is zero./swapper Contract address of the `ISwapper` implementation. Swappers are restricted for closed liquidations. See `setSwapper`./open True to perform a open liquidation else False.
function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper, bool open
function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper, bool open
6,781
145
// Returns the integer division of two unsigned integers. Reverts ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. /
function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); }
function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); }
108
18
// Get the claimable balance of a token ID. Javascript implementation on the front end/
function claimableBalanceOfTokenId(uint256 tokenId) public view returns (uint256) { return _claimableEth[tokenId]; }
function claimableBalanceOfTokenId(uint256 tokenId) public view returns (uint256) { return _claimableEth[tokenId]; }
4,799
38
// 4 - calculated Payout
uint calculatedPayout;
uint calculatedPayout;
53,438
17
// MintController The MintController contract manages minters for a contract thatimplements the MinterManagerInterface. It lets the owner designate certainaddresses as controllers, and these controllers then manage theminters by adding and removing minters, as well as modifying their mintingallowance. A controller may manage exactly one minter, but the same minteraddress may be managed by multiple controllers. MintController inherits from the Controller contract. It treats theController workers as minters. /
contract MintController is Controller { using SafeMath for uint256; /** * @title MinterManagementInterface * @notice MintController calls the minterManager to execute/record minter * management tasks, as well as to query the status of a minter address. */ MinterManagementInterface internal minterManager; event MinterManagerSet( address indexed _oldMinterManager, address indexed _newMinterManager ); event MinterConfigured( address indexed _msgSender, address indexed _minter, uint256 _allowance ); event MinterRemoved(address indexed _msgSender, address indexed _minter); event MinterAllowanceIncremented( address indexed _msgSender, address indexed _minter, uint256 _increment, uint256 _newAllowance ); event MinterAllowanceDecremented( address indexed msgSender, address indexed minter, uint256 decrement, uint256 newAllowance ); /** * @notice Initializes the minterManager. * @param _minterManager The address of the minterManager contract. */ constructor(address _minterManager) public { minterManager = MinterManagementInterface(_minterManager); } /** * @notice gets the minterManager */ function getMinterManager() external view returns (MinterManagementInterface) { return minterManager; } // onlyOwner functions /** * @notice Sets the minterManager. * @param _newMinterManager The address of the new minterManager contract. */ function setMinterManager(address _newMinterManager) public onlyOwner { emit MinterManagerSet(address(minterManager), _newMinterManager); minterManager = MinterManagementInterface(_newMinterManager); } // onlyController functions /** * @notice Removes the controller's own minter. */ function removeMinter() public onlyController returns (bool) { address minter = controllers[msg.sender]; emit MinterRemoved(msg.sender, minter); return minterManager.removeMinter(minter); } /** * @notice Enables the minter and sets its allowance. * @param _newAllowance New allowance to be set for minter. */ function configureMinter(uint256 _newAllowance) public onlyController returns (bool) { address minter = controllers[msg.sender]; emit MinterConfigured(msg.sender, minter, _newAllowance); return internal_setMinterAllowance(minter, _newAllowance); } /** * @notice Increases the minter's allowance if and only if the minter is an * active minter. * @dev An minter is considered active if minterManager.isMinter(minter) * returns true. */ function incrementMinterAllowance(uint256 _allowanceIncrement) public onlyController returns (bool) { require( _allowanceIncrement > 0, "Allowance increment must be greater than 0" ); address minter = controllers[msg.sender]; require( minterManager.isMinter(minter), "Can only increment allowance for minters in minterManager" ); uint256 currentAllowance = minterManager.minterAllowance(minter); uint256 newAllowance = currentAllowance.add(_allowanceIncrement); emit MinterAllowanceIncremented( msg.sender, minter, _allowanceIncrement, newAllowance ); return internal_setMinterAllowance(minter, newAllowance); } /** * @notice decreases the minter allowance if and only if the minter is * currently active. The controller can safely send a signed * decrementMinterAllowance() transaction to a minter and not worry * about it being used to undo a removeMinter() transaction. */ function decrementMinterAllowance(uint256 _allowanceDecrement) public onlyController returns (bool) { require( _allowanceDecrement > 0, "Allowance decrement must be greater than 0" ); address minter = controllers[msg.sender]; require( minterManager.isMinter(minter), "Can only decrement allowance for minters in minterManager" ); uint256 currentAllowance = minterManager.minterAllowance(minter); uint256 actualAllowanceDecrement = ( currentAllowance > _allowanceDecrement ? _allowanceDecrement : currentAllowance ); uint256 newAllowance = currentAllowance.sub(actualAllowanceDecrement); emit MinterAllowanceDecremented( msg.sender, minter, actualAllowanceDecrement, newAllowance ); return internal_setMinterAllowance(minter, newAllowance); } // Internal functions /** * @notice Uses the MinterManagementInterface to enable the minter and * set its allowance. * @param _minter Minter to set new allowance of. * @param _newAllowance New allowance to be set for minter. */ function internal_setMinterAllowance(address _minter, uint256 _newAllowance) internal returns (bool) { return minterManager.configureMinter(_minter, _newAllowance); } }
contract MintController is Controller { using SafeMath for uint256; /** * @title MinterManagementInterface * @notice MintController calls the minterManager to execute/record minter * management tasks, as well as to query the status of a minter address. */ MinterManagementInterface internal minterManager; event MinterManagerSet( address indexed _oldMinterManager, address indexed _newMinterManager ); event MinterConfigured( address indexed _msgSender, address indexed _minter, uint256 _allowance ); event MinterRemoved(address indexed _msgSender, address indexed _minter); event MinterAllowanceIncremented( address indexed _msgSender, address indexed _minter, uint256 _increment, uint256 _newAllowance ); event MinterAllowanceDecremented( address indexed msgSender, address indexed minter, uint256 decrement, uint256 newAllowance ); /** * @notice Initializes the minterManager. * @param _minterManager The address of the minterManager contract. */ constructor(address _minterManager) public { minterManager = MinterManagementInterface(_minterManager); } /** * @notice gets the minterManager */ function getMinterManager() external view returns (MinterManagementInterface) { return minterManager; } // onlyOwner functions /** * @notice Sets the minterManager. * @param _newMinterManager The address of the new minterManager contract. */ function setMinterManager(address _newMinterManager) public onlyOwner { emit MinterManagerSet(address(minterManager), _newMinterManager); minterManager = MinterManagementInterface(_newMinterManager); } // onlyController functions /** * @notice Removes the controller's own minter. */ function removeMinter() public onlyController returns (bool) { address minter = controllers[msg.sender]; emit MinterRemoved(msg.sender, minter); return minterManager.removeMinter(minter); } /** * @notice Enables the minter and sets its allowance. * @param _newAllowance New allowance to be set for minter. */ function configureMinter(uint256 _newAllowance) public onlyController returns (bool) { address minter = controllers[msg.sender]; emit MinterConfigured(msg.sender, minter, _newAllowance); return internal_setMinterAllowance(minter, _newAllowance); } /** * @notice Increases the minter's allowance if and only if the minter is an * active minter. * @dev An minter is considered active if minterManager.isMinter(minter) * returns true. */ function incrementMinterAllowance(uint256 _allowanceIncrement) public onlyController returns (bool) { require( _allowanceIncrement > 0, "Allowance increment must be greater than 0" ); address minter = controllers[msg.sender]; require( minterManager.isMinter(minter), "Can only increment allowance for minters in minterManager" ); uint256 currentAllowance = minterManager.minterAllowance(minter); uint256 newAllowance = currentAllowance.add(_allowanceIncrement); emit MinterAllowanceIncremented( msg.sender, minter, _allowanceIncrement, newAllowance ); return internal_setMinterAllowance(minter, newAllowance); } /** * @notice decreases the minter allowance if and only if the minter is * currently active. The controller can safely send a signed * decrementMinterAllowance() transaction to a minter and not worry * about it being used to undo a removeMinter() transaction. */ function decrementMinterAllowance(uint256 _allowanceDecrement) public onlyController returns (bool) { require( _allowanceDecrement > 0, "Allowance decrement must be greater than 0" ); address minter = controllers[msg.sender]; require( minterManager.isMinter(minter), "Can only decrement allowance for minters in minterManager" ); uint256 currentAllowance = minterManager.minterAllowance(minter); uint256 actualAllowanceDecrement = ( currentAllowance > _allowanceDecrement ? _allowanceDecrement : currentAllowance ); uint256 newAllowance = currentAllowance.sub(actualAllowanceDecrement); emit MinterAllowanceDecremented( msg.sender, minter, actualAllowanceDecrement, newAllowance ); return internal_setMinterAllowance(minter, newAllowance); } // Internal functions /** * @notice Uses the MinterManagementInterface to enable the minter and * set its allowance. * @param _minter Minter to set new allowance of. * @param _newAllowance New allowance to be set for minter. */ function internal_setMinterAllowance(address _minter, uint256 _newAllowance) internal returns (bool) { return minterManager.configureMinter(_minter, _newAllowance); } }
27,702
34
// Called by the payer to store the sent amount as credit to be pulled.dest The destination address of the funds.amount The amount to transfer./
function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); }
function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); }
22,731
20
// Deposit tokens into POS portal. When `depositor` deposits tokens into POS portal, tokens get locked into predicate contract. depositor Address who wants to deposit tokens depositReceiver Address (address) who wants to receive tokens on side chain rootToken Token which gets deposited depositData Extra data for deposit (amount for ERC20, token id for ERC721 etc.) [ABI encoded] /
function lockTokens( address depositor, address depositReceiver, address rootToken, bytes calldata depositData ) external;
function lockTokens( address depositor, address depositReceiver, address rootToken, bytes calldata depositData ) external;
22,914
100
// Sets crowdsale start and end time
function setTimes(uint256 _startTime, uint256 _endTime) public onlyOwner { require(_startTime <= _endTime); require(!hasEnded()); startTime = _startTime; endTime = _endTime; }
function setTimes(uint256 _startTime, uint256 _endTime) public onlyOwner { require(_startTime <= _endTime); require(!hasEnded()); startTime = _startTime; endTime = _endTime; }
14,434
0
// {ERC721} token, including:This contract uses {AccessControl} to lock permissioned functions using the Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs; address public marketplace; event ArtifactCreated( uint256 tokenID, address indexed creator, string metaDataUri );
mapping(uint256 => string) private _tokenURIs; address public marketplace; event ArtifactCreated( uint256 tokenID, address indexed creator, string metaDataUri );
16,754
30
// The context of msg.sender is this contract's address
require(xFUND.increaseAllowance(address(router), _amount), "failed to increase allowance"); return true;
require(xFUND.increaseAllowance(address(router), _amount), "failed to increase allowance"); return true;
37,224
9
// transfer
address token0Addr = IBorrowable(borrowable0Addr).underlying(); address token1Addr = IBorrowable(borrowable1Addr).underlying(); IERC20(token0Addr).transfer(msg.sender, IERC20(token0Addr).balanceOf(address(this))); IERC20(token1Addr).transfer(msg.sender, IERC20(token1Addr).balanceOf(address(this)));
address token0Addr = IBorrowable(borrowable0Addr).underlying(); address token1Addr = IBorrowable(borrowable1Addr).underlying(); IERC20(token0Addr).transfer(msg.sender, IERC20(token0Addr).balanceOf(address(this))); IERC20(token1Addr).transfer(msg.sender, IERC20(token1Addr).balanceOf(address(this)));
6,655
69
// this contract
destAddress); emit Swapped(address(cSrcToken), srcQty, address(cDestToken), destAmount); return destAmount;
destAddress); emit Swapped(address(cSrcToken), srcQty, address(cDestToken), destAmount); return destAmount;
18,934
170
// If the total supply is zero, finds and deletes the partition. Do not delete the _defaultPartition from totalPartitions.
if (totalSupplyByPartition[_partition] == 0 && _partition != defaultPartition) { _removePartitionFromTotalPartitions(_partition); }
if (totalSupplyByPartition[_partition] == 0 && _partition != defaultPartition) { _removePartitionFromTotalPartitions(_partition); }
27,284
10
// vesting
address public immutable vestingAddress; uint256 private immutable _vestingSupply;
address public immutable vestingAddress; uint256 private immutable _vestingSupply;
46,948
7
// Stakes tokens according to the vesting schedule. Low level function. Once here the allowance of tokens is taken for granted. _sender The sender of tokens to stake. _amount The amount of tokens to stake./
function _stakeTokens(address _sender, uint256 _amount) internal { /// @dev Maybe better to allow staking unil the cliff was reached. if (startDate == 0) { startDate = staking.timestampToLockDate(block.timestamp); } endDate = staking.timestampToLockDate(block.timestamp + duration); /// @dev Transfer the tokens to this contract. bool success = SOV.transferFrom(_sender, address(this), _amount); require(success); /// @dev Allow the staking contract to access them. SOV.approve(address(staking), _amount); staking.stakesBySchedule(_amount, cliff, duration, FOUR_WEEKS, address(this), tokenOwner); emit TokensStaked(_sender, _amount); }
function _stakeTokens(address _sender, uint256 _amount) internal { /// @dev Maybe better to allow staking unil the cliff was reached. if (startDate == 0) { startDate = staking.timestampToLockDate(block.timestamp); } endDate = staking.timestampToLockDate(block.timestamp + duration); /// @dev Transfer the tokens to this contract. bool success = SOV.transferFrom(_sender, address(this), _amount); require(success); /// @dev Allow the staking contract to access them. SOV.approve(address(staking), _amount); staking.stakesBySchedule(_amount, cliff, duration, FOUR_WEEKS, address(this), tokenOwner); emit TokensStaked(_sender, _amount); }
15,046
10
// Gets delegation info for the given operator./operator Address of the operator./ return createdAt The time when the delegation was created./ return undelegatedAt The time when undelegation has been requested./ If undelegation has not been requested, 0 is returned.
function getDelegationInfo(address operator) public view returns (uint256 createdAt, uint256 undelegatedAt)
function getDelegationInfo(address operator) public view returns (uint256 createdAt, uint256 undelegatedAt)
32,462
7
// This is a type for a single voter
struct voter { uint tokensBought; // The total no. of tokens this voter bought uint availableTokens; // Tokens that voter can use to vote bool[] tokensUsedPerCandidate; // Array to keep track candidates this voter voted. }
struct voter { uint tokensBought; // The total no. of tokens this voter bought uint availableTokens; // Tokens that voter can use to vote bool[] tokensUsedPerCandidate; // Array to keep track candidates this voter voted. }
9,406
8
// nothing to be done post-call. still, we must implement this method.
function post_relayed_call(address /*relay*/, address /*from*/, bytes memory /*encoded_function*/, bool /*success*/,
function post_relayed_call(address /*relay*/, address /*from*/, bytes memory /*encoded_function*/, bool /*success*/,
40,252
9
// query if the _libraryAddress is valid for sending msgs._userApplication - the user app address on this EVM chain
function getSendLibraryAddress( address _userApplication ) external view returns (address);
function getSendLibraryAddress( address _userApplication ) external view returns (address);
18,455
73
// Method to check whether a user is there in the whitelist or not
function checkUser(address user) onlyOwner public view returns (bool){ return whitelisted[user]; }
function checkUser(address user) onlyOwner public view returns (bool){ return whitelisted[user]; }
9,614
23
// Rebalance plug at level1+.level1 -> 50% remain into plug and 50% send to reward1level2+ -> 33.3% to plug 33.3% to reward1 and 33.3% to reward2 /
function _rebalanceAtLevel1Plus(uint256 _amount) internal { uint256 plugAmount = _getPlugBalance(tokenWant); uint256 amountToSend = _amount; if (plugLevel > 1) { amountToSend = amountToSend.mul(2); } if (plugAmount < amountToSend) { uint256 amountToRetrieveFromS = amountToSend.sub(plugAmount); uint256 amountToRedeem = amountToRetrieveFromS.div(_getRedeemPrice()).mul(ONE_18); strategy.redeemIdleToken(amountToRedeem); tokenStrategyAmounts[address(this)] = tokenStrategyAmounts[address(this)].sub(amountToRedeem); } // send to reward out 1 _transferToOutside(tokenWant, rewardOutOne, _amount); if (plugLevel > 1) { _transferToOutside(tokenWant, rewardOutTwo, _amount); } //send all remain token want from plug to idle strategy uint256 balanceLeft = plugAmount.sub(amountToSend); if (balanceLeft > 0) { _rebalanceAtLevel0(balanceLeft); } }
function _rebalanceAtLevel1Plus(uint256 _amount) internal { uint256 plugAmount = _getPlugBalance(tokenWant); uint256 amountToSend = _amount; if (plugLevel > 1) { amountToSend = amountToSend.mul(2); } if (plugAmount < amountToSend) { uint256 amountToRetrieveFromS = amountToSend.sub(plugAmount); uint256 amountToRedeem = amountToRetrieveFromS.div(_getRedeemPrice()).mul(ONE_18); strategy.redeemIdleToken(amountToRedeem); tokenStrategyAmounts[address(this)] = tokenStrategyAmounts[address(this)].sub(amountToRedeem); } // send to reward out 1 _transferToOutside(tokenWant, rewardOutOne, _amount); if (plugLevel > 1) { _transferToOutside(tokenWant, rewardOutTwo, _amount); } //send all remain token want from plug to idle strategy uint256 balanceLeft = plugAmount.sub(amountToSend); if (balanceLeft > 0) { _rebalanceAtLevel0(balanceLeft); } }
4,771
7
// Verify that (leaf, proof) matches the Merkle root
require(verify(merkleRoot, leaf, proof), "Not a valid leaf in the Merkle tree"); whitelistUsed[msg.sender] = true; whitelistRemaining[msg.sender] = totalAllocation;
require(verify(merkleRoot, leaf, proof), "Not a valid leaf in the Merkle tree"); whitelistUsed[msg.sender] = true; whitelistRemaining[msg.sender] = totalAllocation;
34,355
22
// ------------------------------------------------------------------------ Returns the amount of tokens approved by the owner that can be transferred to the spender's account ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) { require(_stopTrade != true); return allowed[tokenOwner][spender]; }
function allowance(address tokenOwner, address spender) public view returns (uint remaining) { require(_stopTrade != true); return allowed[tokenOwner][spender]; }
8,537
3
// result = result + num
function addToNumber(uint num) returns (uint) { result += num; NumberAdded(num); return result; }
function addToNumber(uint num) returns (uint) { result += num; NumberAdded(num); return result; }
6,901
15
// Checks to see if given address is market admin._checkaddress address that needs to be checked. return boolean. True if it's admin, False if it's not admin./
function isAdmin(address _checkaddress) public view returns(bool) { return(approvedAdmins[_checkaddress]); }
function isAdmin(address _checkaddress) public view returns(bool) { return(approvedAdmins[_checkaddress]); }
21,446
22
// Add the liquidity:
(uint256 amountA, uint256 amountB, uint256 lpTokens) = uniswapRouter
(uint256 amountA, uint256 amountB, uint256 lpTokens) = uniswapRouter
29,499
7
// This emit when interests amount per block is changed by the owner of the contract./ It emits with the old interests amount and the new interests amount.
event InterestRatePerBlockChanged(uint256 oldValue, uint256 newValue);
event InterestRatePerBlockChanged(uint256 oldValue, uint256 newValue);
4,827
51
// Create an indexing dispute for the arbitrator to resolve.The disputes are created in reference to an allocationIDThis function is called by a challenger that will need to `_deposit` atleast `minimumDeposit` GRT tokens. _allocationID The allocation to dispute _deposit Amount of tokens staked as deposit /
function createIndexingDispute(address _allocationID, uint256 _deposit) external override returns (bytes32)
function createIndexingDispute(address _allocationID, uint256 _deposit) external override returns (bytes32)
21,965
19
// Backup Eth address
ambassadors_[0xfd0494ce04a9B51c3DAA8b427ed842B7861dCF4e] = true;
ambassadors_[0xfd0494ce04a9B51c3DAA8b427ed842B7861dCF4e] = true;
17,644
29
// Checks modifier and allows transfer if tokens are not locked.
function transfer(address _to, uint _value) canTransfer(msg.sender, _value) { return super.transfer(_to, _value); }
function transfer(address _to, uint _value) canTransfer(msg.sender, _value) { return super.transfer(_to, _value); }
36,897
263
// Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. Get supply and borrows with interest accrued till the latest block
( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) {
( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) {
12,195
17
// Interface of the ERC20 standard /
interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
11,808
18
// it deposits DAI for the sale_amount: amount of DAI to deposit to sale (18 decimals) /
function deposit(uint256 _amount) external { require(started, 'Sale has not started'); require(!ended, 'Sale has ended'); require(whitelisted[msg.sender] == true, 'msg.sender is not whitelisted user'); UserInfo storage user = userInfo[msg.sender]; require( cap >= user.amount.add(_amount), 'new amount above user limit' ); user.amount = user.amount.add(_amount); totalRaisedDAI = totalRaisedDAI.add(_amount); uint payout = _amount.mul(1e18).div(price).div(1e9); // aROME to mint for _amount totalDebt = totalDebt.add(payout); DAI.safeTransferFrom( msg.sender, DAO, _amount ); IAlphaRome( address(aROME) ).mint( msg.sender, payout ); emit Deposit(msg.sender, _amount); }
function deposit(uint256 _amount) external { require(started, 'Sale has not started'); require(!ended, 'Sale has ended'); require(whitelisted[msg.sender] == true, 'msg.sender is not whitelisted user'); UserInfo storage user = userInfo[msg.sender]; require( cap >= user.amount.add(_amount), 'new amount above user limit' ); user.amount = user.amount.add(_amount); totalRaisedDAI = totalRaisedDAI.add(_amount); uint payout = _amount.mul(1e18).div(price).div(1e9); // aROME to mint for _amount totalDebt = totalDebt.add(payout); DAI.safeTransferFrom( msg.sender, DAO, _amount ); IAlphaRome( address(aROME) ).mint( msg.sender, payout ); emit Deposit(msg.sender, _amount); }
10,048
60
// Ask Witnet to confirm the token's image URI actually exists:
{ string[][] memory _args = new string[][](1); _args[0] = new string[](1); _args[0][0] = _imageURI; __requests.imageDigest = WitnetRequestTemplate(payable(address(witnetRequestImageDigest.clone()))); __requests.imageDigest.initialize(abi.encode( WitnetRequestTemplate.InitData({ args: _args, slaHash: _witnetSlaHash })
{ string[][] memory _args = new string[][](1); _args[0] = new string[](1); _args[0][0] = _imageURI; __requests.imageDigest = WitnetRequestTemplate(payable(address(witnetRequestImageDigest.clone()))); __requests.imageDigest.initialize(abi.encode( WitnetRequestTemplate.InitData({ args: _args, slaHash: _witnetSlaHash })
14,129
120
// ==========Other========== // Absorb any tokens that have been sent to the pool.If the token is not bound, it will be sent to the unboundtoken handler. /
function gulp(address token) external override _lock_ { Record storage record = _records[token]; uint256 balance = IERC20(token).balanceOf(address(this)); if (record.bound) { if (!record.ready) { uint256 minimumBalance = _minimumBalances[token]; if (balance >= minimumBalance) { _minimumBalances[token] = 0; record.ready = true; emit LOG_TOKEN_READY(token); uint256 additionalBalance = bsub(balance, minimumBalance); uint256 balRatio = bdiv(additionalBalance, minimumBalance); uint96 newDenorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio))); record.denorm = newDenorm; record.lastDenormUpdate = uint40(now); _totalWeight = badd(_totalWeight, newDenorm); emit LOG_DENORM_UPDATED(token, record.denorm); } } _records[token].balance = balance; } else { _pushUnderlying(token, address(_unbindHandler), balance); _unbindHandler.handleUnbindToken(token, balance); } }
function gulp(address token) external override _lock_ { Record storage record = _records[token]; uint256 balance = IERC20(token).balanceOf(address(this)); if (record.bound) { if (!record.ready) { uint256 minimumBalance = _minimumBalances[token]; if (balance >= minimumBalance) { _minimumBalances[token] = 0; record.ready = true; emit LOG_TOKEN_READY(token); uint256 additionalBalance = bsub(balance, minimumBalance); uint256 balRatio = bdiv(additionalBalance, minimumBalance); uint96 newDenorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio))); record.denorm = newDenorm; record.lastDenormUpdate = uint40(now); _totalWeight = badd(_totalWeight, newDenorm); emit LOG_DENORM_UPDATED(token, record.denorm); } } _records[token].balance = balance; } else { _pushUnderlying(token, address(_unbindHandler), balance); _unbindHandler.handleUnbindToken(token, balance); } }
12,400
5
// Initial state Add document state
addDocState = AddDocState.Disable;
addDocState = AddDocState.Disable;
11,863
135
// Essentially withdraw our equivalent share of the pool based on share value Users cannot choose which token they get. They get main token then collateral if available
require(share > 0, "Cannot withdraw 0"); require(totalSupply() > 0, "No value redeemable"); uint256 tokenTotal = totalSupply();
require(share > 0, "Cannot withdraw 0"); require(totalSupply() > 0, "No value redeemable"); uint256 tokenTotal = totalSupply();
9,262
25
// `gelerCompte? Interdit | Autorise` `cible` &224; envoyer et recevoir des tokens/cible L&39;adresse &224; geler./gele Bool&233;en gel&233;/pas gel&233;.
function gelerCompte ( address cible, bool gele ) proprioSeulement public { comptesGeles[cible] = gele; emit ComptesGeles ( cible, gele ); }
function gelerCompte ( address cible, bool gele ) proprioSeulement public { comptesGeles[cible] = gele; emit ComptesGeles ( cible, gele ); }
54,714
119
// The block number when ADR mining starts.
uint256 public startBlock;
uint256 public startBlock;
4,807
35
// The payout and fee addresses must be different
require(_payout != _fee);
require(_payout != _fee);
58,372
42
// Recipient of protocol fees
address public feeRecipient;
address public feeRecipient;
15,612
26
// allow update token type from owner wallet
function setTokenTypeAsOwner(address _token, string calldata _type) external onlyOwner{ // convert string to bytes32 bytes32 typeToBytes = stringToBytes32(_type); // flag token with new type getType[_token] = typeToBytes; isRegistred[_token] = true; // if new type unique add it to the list if(!isTypeRegistred[typeToBytes]){ isTypeRegistred[typeToBytes] = true; allTypes.push(typeToBytes); } }
function setTokenTypeAsOwner(address _token, string calldata _type) external onlyOwner{ // convert string to bytes32 bytes32 typeToBytes = stringToBytes32(_type); // flag token with new type getType[_token] = typeToBytes; isRegistred[_token] = true; // if new type unique add it to the list if(!isTypeRegistred[typeToBytes]){ isTypeRegistred[typeToBytes] = true; allTypes.push(typeToBytes); } }
31,768
11
// retrieves current royalty percent
function getRoyaltyPercentage() public view returns (uint16) { return _royaltyPercentage; }
function getRoyaltyPercentage() public view returns (uint16) { return _royaltyPercentage; }
44,878
23
// team funding: (tokenRaised_[_round] - (actualTokenRaised_ / 4)) 25% token refund to user.
return ( tokenRaised_, actualTokenRaised_ );
return ( tokenRaised_, actualTokenRaised_ );
11,970
115
// Returns the full capital allocation table
function capitalAllocation() public view returns (address[] _addresses, uint[] _amounts)
function capitalAllocation() public view returns (address[] _addresses, uint[] _amounts)
1,223
1
// Calculates the current borrow interest rate per block cash The total amount of cash the market has borrows The total amount of borrows the market has outstanding reserves The total amount of reserves the market hasreturn The borrow rate per block (as a percentage, and scaled by 1e18) /
function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256);
function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256);
16,075
52
// src/UnsafeMath64x64.sol/ pragma solidity ^0.5.0; /
library UnsafeMath64x64 { /** * Calculate x * y rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function us_mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; return int128 (result); } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function us_div (int128 x, int128 y) internal pure returns (int128) { int256 result = (int256 (x) << 64) / y; return int128 (result); } }
library UnsafeMath64x64 { /** * Calculate x * y rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function us_mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; return int128 (result); } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function us_div (int128 x, int128 y) internal pure returns (int128) { int256 result = (int256 (x) << 64) / y; return int128 (result); } }
41,939
49
// deposit fee
{ (address gather, uint256 bAmount0, uint256 bAmount1) = calcDepositFee(_pid); if(bAmount0 > 0) IERC20(token0).safeTransfer(gather, bAmount0); if(bAmount1 > 0) IERC20(token1).safeTransfer(gather, bAmount1); }
{ (address gather, uint256 bAmount0, uint256 bAmount1) = calcDepositFee(_pid); if(bAmount0 > 0) IERC20(token0).safeTransfer(gather, bAmount0); if(bAmount1 > 0) IERC20(token1).safeTransfer(gather, bAmount1); }
16,475
6
// checks that caller is either owner or keeper.
modifier onlyManager() { require(msg.sender == owner() || msg.sender == keeper, "!manager"); _; }
modifier onlyManager() { require(msg.sender == owner() || msg.sender == keeper, "!manager"); _; }
36,349
104
// pragma solidity ^0.6.7; // import "./interfaces/strategy.sol"; // import "./lib/erc20.sol"; // import "./lib/safe-math.sol"; /
contract MithMisJar is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; address public strategy; constructor(IStrategy _strategy) public ERC20( string(abi.encodePacked(ERC20(_strategy.want()).name(), "vault")), string(abi.encodePacked("v", ERC20(_strategy.want()).symbol())) ) { _setupDecimals(ERC20(_strategy.want()).decimals()); token = IERC20(_strategy.want()); strategy = address(_strategy); } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Custom logic in here for how much the jars allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { require(IStrategy(strategy).isWhitelisted(msg.sender), "Not whitelisted"); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getRatio() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } }
contract MithMisJar is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; address public strategy; constructor(IStrategy _strategy) public ERC20( string(abi.encodePacked(ERC20(_strategy.want()).name(), "vault")), string(abi.encodePacked("v", ERC20(_strategy.want()).symbol())) ) { _setupDecimals(ERC20(_strategy.want()).decimals()); token = IERC20(_strategy.want()); strategy = address(_strategy); } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Custom logic in here for how much the jars allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { require(IStrategy(strategy).isWhitelisted(msg.sender), "Not whitelisted"); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getRatio() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } }
30,405
0
// Private state variable
address payable public owner;
address payable public owner;
15,462
74
// rawReportContext consists of: 11-byte zero padding 16-byte configDigest 4-byte epoch 1-byte round
bytes16 configDigest = bytes16(r.rawReportContext << 88); require( r.hotVars.latestConfigDigest == configDigest, "configDigest mismatch" ); uint40 epochAndRound = uint40(uint256(r.rawReportContext));
bytes16 configDigest = bytes16(r.rawReportContext << 88); require( r.hotVars.latestConfigDigest == configDigest, "configDigest mismatch" ); uint40 epochAndRound = uint40(uint256(r.rawReportContext));
15,787
28
// Send BNB to manager
manager.transfer(amount);
manager.transfer(amount);
10,978
1
// gasOracle = AggregatorV3Interface(_gasPriceAgg);
token = IERC20(_token); gasLimit = _gasLimit;
token = IERC20(_token); gasLimit = _gasLimit;
18,979
5
// structure of patient info
struct patient { string name; string DOB; uint64 adhaar_number; address id; string gender; string contact_info; bytes32[] files;// hashes of file that belong to this user for display purpose address[] doctor_list; }
struct patient { string name; string DOB; uint64 adhaar_number; address id; string gender; string contact_info; bytes32[] files;// hashes of file that belong to this user for display purpose address[] doctor_list; }
11,036
32
// ChecksCheck that the token ID is in rangeWe use >= and <= to here because all of the token IDs are 0-indexed
require( tokenId >= tokenIdStart && tokenId <= tokenIdEnd, "TOKEN_ID_OUT_OF_RANGE" );
require( tokenId >= tokenIdStart && tokenId <= tokenIdEnd, "TOKEN_ID_OUT_OF_RANGE" );
4,912
50
// current recipient status should NOT be Terminated
require( recipients[recipient].recipientVestingStatus != Status.Terminated, "terminateRecipient: cannot terminate" );
require( recipients[recipient].recipientVestingStatus != Status.Terminated, "terminateRecipient: cannot terminate" );
13,084