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
63
// uint256 public initreward = 12501e18;
uint256 public starttime = 1599829200; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public totalMinted = 0;
uint256 public starttime = 1599829200; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public totalMinted = 0;
22,826
194
// credit for this implementation goes to https:github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.solL687
function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x10000000...
function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x10000000...
4,565
26
// If we do not know the Partnership contract yet,
if (partnershipContracts[_hisContract].authorization == PartnershipAuthorization.Unknown) {
if (partnershipContracts[_hisContract].authorization == PartnershipAuthorization.Unknown) {
26,677
76
// Collection of all moved funds sweep requests indexed by/ `keccak256(movingFundsTxHash | movingFundsOutputIndex)`./ The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin/ internally) and `movingFundsOutputIndex` an `uint32`. Each entry/ is actually an UTXO representing the moved funds and is supposed/ to be swe...
function movedFundsSweepRequests(uint256 requestKey) external view returns (MovingFunds.MovedFundsSweepRequest memory)
function movedFundsSweepRequests(uint256 requestKey) external view returns (MovingFunds.MovedFundsSweepRequest memory)
10,753
114
// Liquidity management functions/Internal functions for safely managing liquidity in Uniswap V3
interface ILiquidityManagement is IUniswapV3MintCallback { function factory() external view returns (IUniswapV3Factory); }
interface ILiquidityManagement is IUniswapV3MintCallback { function factory() external view returns (IUniswapV3Factory); }
32,681
130
// Place a bid for an ERC1155 token. Tokens can have multiple bids by different users.Users can have only one bid per token.If the user places a bid and has an active bid for that token,the older one will be replaced with the new one. _tokenId - Thetoken id _index - The index of tokens being transferred _price - The pr...
function placeBid(uint256 _tokenId, uint32 _index, uint256 _price) external;
function placeBid(uint256 _tokenId, uint32 _index, uint256 _price) external;
37,778
339
// Send surplus of ETH back to the sender
msg.sender.transferETH(msg.value.sub(S.withdrawalFeeETH), gasleft());
msg.sender.transferETH(msg.value.sub(S.withdrawalFeeETH), gasleft());
26,474
14
// Empty internal constructor, to prevent people from mistakenly deploying an instance of this contract, which should be used via inheritance.
constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; }
constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; }
5,570
145
// Debug code for checking wallet 3 set/get
function getWallet3() public view returns (address) { return _feeAddrWallet3; }
function getWallet3() public view returns (address) { return _feeAddrWallet3; }
16,426
175
// Emits each time when borrower increases borrowed amount
event IncreaseBorrowedAmount(address indexed borrower, uint256 amount);
event IncreaseBorrowedAmount(address indexed borrower, uint256 amount);
15,452
34
// define starting value (here, we take the share of the first address)
address firstSealerAddress = election.decryptedShareWallet[0]; uint256 res = election.decryptedShareMapping[firstSealerAddress].share;
address firstSealerAddress = election.decryptedShareWallet[0]; uint256 res = election.decryptedShareMapping[firstSealerAddress].share;
23,114
3
// Bit mask used to parse out the token ID value.
uint256 private constant _BITMASK_TOKEN_ID = (1 << 16) - 1;
uint256 private constant _BITMASK_TOKEN_ID = (1 << 16) - 1;
34,844
69
// Returns fee wallet/
function getFeeWallet() external view returns(address){ return _feeWallet; }
function getFeeWallet() external view returns(address){ return _feeWallet; }
16,612
312
// Method allowing this owner, or an editor of the registry, to flag a token/registry the registry to flag/tokenId the tokenId/reason the reason to flag
function flagToken( address registry, uint256 tokenId, string memory reason
function flagToken( address registry, uint256 tokenId, string memory reason
44,363
16
// { <epoch> : {<user> : <collateralAmount> }
mapping(uint256 => mapping(address => uint256)) public mintRequestsPerEpoch;
mapping(uint256 => mapping(address => uint256)) public mintRequestsPerEpoch;
1,568
143
// Price Ratios, to x decimal places hencedecimals, dependent on the size of the denominator. Ratios are relative to eth, amount of ether for a single token, ie. ETH / GNO == 0.2 Ether per 1 Gnosis
uint256 orderPrice; // The price the maker is willing to accept uint256 offeredPrice; // The offer the taker has given uint256 decimals = _makerOrder.offerToken_ == address(0) ? __flooredLog10__(_makerOrder.wantTokenTotal_) : __flooredLog10__(_makerOrder.offerTokenTotal_);
uint256 orderPrice; // The price the maker is willing to accept uint256 offeredPrice; // The offer the taker has given uint256 decimals = _makerOrder.offerToken_ == address(0) ? __flooredLog10__(_makerOrder.wantTokenTotal_) : __flooredLog10__(_makerOrder.offerTokenTotal_);
8,747
22
// Setter for the name of an account. name The name to set. /
function setName(string memory name) public { require(isAccount(msg.sender), "Unknown account"); Account storage account = accounts[msg.sender]; account.name = name; emit AccountNameSet(msg.sender, name); }
function setName(string memory name) public { require(isAccount(msg.sender), "Unknown account"); Account storage account = accounts[msg.sender]; account.name = name; emit AccountNameSet(msg.sender, name); }
20,107
75
// Price call entry configuration structure
// struct Config { // // Single query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 singleFee; // // Double query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 doubleFee; // // The normal state flag of the call address. 0 // uint8 normalFlag; // }
// struct Config { // // Single query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 singleFee; // // Double query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 doubleFee; // // The normal state flag of the call address. 0 // uint8 normalFlag; // }
42,637
18
// Basic tokenBasic version of StandardToken, with no allowances /
contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /* * Fix for the ERC20 short address attack */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onl...
contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /* * Fix for the ERC20 short address attack */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onl...
31,814
40
// Perform the delegatecall, make sure to pass all available gas.
let success := delegatecall(gas(), implementation, 0x0, calldatasize(), 0x0, 0x0)
let success := delegatecall(gas(), implementation, 0x0, calldatasize(), 0x0, 0x0)
35,397
4
// Only bets higher that 0.1 ETH have a chance to win jackpot.
uint256 constant MIN_JACKPOT_BET = 0.1 ether;
uint256 constant MIN_JACKPOT_BET = 0.1 ether;
42,154
218
// Activates a reserve asset The address of the underlying asset of the reserve /
function activateReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveActivated(asset); }
function activateReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveActivated(asset); }
21,696
4
// Price.
uint256 public CHIPPriceOne; uint256 public CHIPPriceCeiling; uint256 public seigniorageSaved; uint256 public maxSupplyExpansionPercent; uint256 public maxSupplyExpansionPercentInDebtPhase; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint25...
uint256 public CHIPPriceOne; uint256 public CHIPPriceCeiling; uint256 public seigniorageSaved; uint256 public maxSupplyExpansionPercent; uint256 public maxSupplyExpansionPercentInDebtPhase; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint25...
13,359
1
// add an address to the whitelist addr addressreturn true if the address was added to the whitelist, false if the address was already in the whitelist/
function addAddressToWhitelist(address addr) public onlyOwner returns (bool){ if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); return true; } return false; }
function addAddressToWhitelist(address addr) public onlyOwner returns (bool){ if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); return true; } return false; }
26,902
522
// Calculate denominator for row 108: x - g^108z.
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x880))) mstore(add(productsPtr, 0x540), partialProduct) mstore(add(valuesPtr, 0x540), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x880))) mstore(add(productsPtr, 0x540), partialProduct) mstore(add(valuesPtr, 0x540), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
29,154
28
// create a modifier so that people cannot call the addCitizen() function twice
modifier isntCitizenYet() { // check if the addressExists field of the citizen calling this function is false require(citizens[msg.sender].addressExists == false); _; }
modifier isntCitizenYet() { // check if the addressExists field of the citizen calling this function is false require(citizens[msg.sender].addressExists == false); _; }
43,646
0
// solhint-disable
function toAddress(bytes memory b) internal pure returns (address payable a) { require(b.length == 20); assembly { a := div(mload(add(b, 32)), exp(256, 12)) // cspell:disable-line } }
function toAddress(bytes memory b) internal pure returns (address payable a) { require(b.length == 20); assembly { a := div(mload(add(b, 32)), exp(256, 12)) // cspell:disable-line } }
24,255
36
// Attempts to remove all want supplied to a pool, returns the amount left /
function withdrawFromPool(address _pool) external returns (uint256) { _onlyKeeper(); require(usedPools.contains(_pool), "Pool not used"); uint256 currentExchangeRate = IBorrowable(_pool).exchangeRate(); uint256 wantSupplied = wantSuppliedToPool(_pool); if (wantSupplied != 0) ...
function withdrawFromPool(address _pool) external returns (uint256) { _onlyKeeper(); require(usedPools.contains(_pool), "Pool not used"); uint256 currentExchangeRate = IBorrowable(_pool).exchangeRate(); uint256 wantSupplied = wantSuppliedToPool(_pool); if (wantSupplied != 0) ...
17,160
120
// About dividendCorrection: If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: `dividendOf(_user) = dividendPerSharebalanceOf(_user)`. When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), `dividendOf(_user)` should not be changed, but the computed...
mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol)
mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol)
1,106
168
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
_prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
28,191
70
// require(tokens[tokenAddress].status == TokenStatus.Unknown, "Cannot register more than one time");
Token memory token; if (activate) { token.status = TokenStatus.Active; } else {
Token memory token; if (activate) { token.status = TokenStatus.Active; } else {
2,411
27
// Close the vault permanently/Manager closes the vault permanently, preventing new deposits and use of the vault
function closeVaultPermanently() external ifNotClosed onlyManager nonReentrant() whenNotPaused() { if(oToken != address(0)) revert oTokenNotCleared(); closedPermanently = true; IERC20(asset).safeTransfer(factory.admin(), withheldProtocolFees); IERC20(asset).safeTransfer(...
function closeVaultPermanently() external ifNotClosed onlyManager nonReentrant() whenNotPaused() { if(oToken != address(0)) revert oTokenNotCleared(); closedPermanently = true; IERC20(asset).safeTransfer(factory.admin(), withheldProtocolFees); IERC20(asset).safeTransfer(...
35,600
285
// Allows owner of the contract to set CommunityPool address for gas reimbursement.Requirements:- `msg.sender` must be granted as DEFAULT_ADMIN_ROLE.- Address of CommunityPool contract must not be null. /
function setCommunityPool(ICommunityPool newCommunityPoolAddress) external override { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller"); require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set"); communityPool = newCommunityPoolAdd...
function setCommunityPool(ICommunityPool newCommunityPoolAddress) external override { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller"); require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set"); communityPool = newCommunityPoolAdd...
72,481
40
// Unfreeze ALL token transfers.May only be called by smart contract owner. /
function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } }
function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } }
16,080
807
// Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process./x The unsigned 60.18-decimal fixed-point number to convert./ return result The same number in basic integer form.
function toUint(uint256 x) internal pure returns (uint256 result) { unchecked { result = x / SCALE; } }
function toUint(uint256 x) internal pure returns (uint256 result) { unchecked { result = x / SCALE; } }
71,009
147
// return : whether has rebalanced or not /
function rebalance() external returns (bool);
function rebalance() external returns (bool);
61,485
335
// Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Poolmint./In the implementation you must pay to the pool for the minted liquidity./amount0 The amount of token0 due to the pool for the minted liquidity/amount1 The amount of token1 due to the pool for the minted ...
function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data
function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data
1,442
85
// (Location + 1) of each NFT in its owner&39;s list/Nomenclature: this[key] = value/If value != 0, _tokensOfOwnerWithSubstitutions[owner][value - 1] = nftId/If value == 0, _tokensOfOwnerWithSubstitutions[owner][key - 1] = nftId/assert(2256-1 is not a valid NFT)/See commented out code in constructor, saves hella gas
mapping (uint256 => uint256) private _ownedTokensIndexWithSubstitutions;
mapping (uint256 => uint256) private _ownedTokensIndexWithSubstitutions;
47,335
156
// res += val(coefficients[12] + coefficients[13]adjustments[2]).
res := addmod(res, mulmod(val, add(/*coefficients[12]*/ mload(0x5c0), mulmod(/*coefficients[13]*/ mload(0x5e0),
res := addmod(res, mulmod(val, add(/*coefficients[12]*/ mload(0x5c0), mulmod(/*coefficients[13]*/ mload(0x5e0),
17,480
25
// Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeaco...
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeaco...
7,658
19
// ERC20Basic Simpler version of ERC20 interface /
contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); }
contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); }
40,183
113
// Approval check is skipped if the caller of transferFrom is the NFT contract.
if (msg.sender != _nftAddress) { _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); }
if (msg.sender != _nftAddress) { _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); }
76,163
61
// Safely transfers the ownership of a given token ID to another addressIf the target address is a contract, it must implement `onERC721Received`,which is called upon a safe transfer, and return the magic value`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,the transfer is reverted.Req...
function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public
function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public
46,160
361
// See {IERC165-supportsInterface}. _Available since v3.4._ /
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
13,067
18
// Slashes a validator that did not sign any blocks for at least `slashableDowntime`. startBlocks A list of interval start blocks for which signature bitmaps have alreadybeen set. endBlocks A list of interval end blocks for which signature bitmaps have alreadybeen set. signerIndices The index of the provided validator ...
function slash( uint256[] memory startBlocks, uint256[] memory endBlocks, uint256[] memory signerIndices, uint256 groupMembershipHistoryIndex, address[] memory validatorElectionLessers, address[] memory validatorElectionGreaters, uint256[] memory validatorElectionIndices, address[] mem...
function slash( uint256[] memory startBlocks, uint256[] memory endBlocks, uint256[] memory signerIndices, uint256 groupMembershipHistoryIndex, address[] memory validatorElectionLessers, address[] memory validatorElectionGreaters, uint256[] memory validatorElectionIndices, address[] mem...
12,575
27
// Function to check the amount of tokens than an owner allowed to a spender. account address The address which owns the funds. spender address The address which will spend the funds.return A uint specifing the amount of tokens still avaible for the spender. /
function allowance(address account, address spender) public view returns (uint remaining) { return allowed[account][spender]; }
function allowance(address account, address spender) public view returns (uint remaining) { return allowed[account][spender]; }
18,562
3
// Lets an admin airdrop tokens to a list of recipients./ TODO: verify this function works (it was auto-genereated)
function airdrop( address[] calldata _receivers, uint256[] calldata _tokenIds, uint256[] calldata _quantities, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof, bytes memory _data
function airdrop( address[] calldata _receivers, uint256[] calldata _tokenIds, uint256[] calldata _quantities, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof, bytes memory _data
11,559
43
// if cursor was head of bucket
if(checkPoints[bucket].head == cursor){
if(checkPoints[bucket].head == cursor){
53,851
142
// Contract meant to receive the royalties for a giventoken of Piano King Private and then splitting it betweenthe minter and the creator when sending the fundsIt is an implementation meant to be used via a proxyin Piano King Private contract /
contract PianoKingPrivateSplitter is OwnableUpgradeable { using AddressUpgradeable for address payable; address private creator; address private minter; uint256 private minterRoyalties; uint256 private creatorRoyalties; function initiliaze( address _creator, address _minter, uint256 _minterRoya...
contract PianoKingPrivateSplitter is OwnableUpgradeable { using AddressUpgradeable for address payable; address private creator; address private minter; uint256 private minterRoyalties; uint256 private creatorRoyalties; function initiliaze( address _creator, address _minter, uint256 _minterRoya...
67,122
122
// Source of truth for all Protocol Fee percentages, that is, how much the protocol charges certain actions. Someof these values may also be retrievable from other places (such as the swap fee percentage), but this is thepreferred source nonetheless. /
interface IProtocolFeePercentagesProvider { // All fee percentages are 18-decimal fixed point numbers, so e.g. 1e18 = 100% and 1e16 = 1%. // Emitted when a new fee type is registered. event ProtocolFeeTypeRegistered(uint256 indexed feeType, string name, uint256 maximumPercentage); // Emitted when the ...
interface IProtocolFeePercentagesProvider { // All fee percentages are 18-decimal fixed point numbers, so e.g. 1e18 = 100% and 1e16 = 1%. // Emitted when a new fee type is registered. event ProtocolFeeTypeRegistered(uint256 indexed feeType, string name, uint256 maximumPercentage); // Emitted when the ...
29,103
110
// 如果张数为0的话就移除列表
if (ownerCardNum[_from] == 0) { removeCardOwnersList(_from); }
if (ownerCardNum[_from] == 0) { removeCardOwnersList(_from); }
20,047
196
// get the black scholes premium of the option and adjust premium based on steth <-> eth exchange rate
premium = DSMath.wmul( GnosisAuction.getOTokenPremium( otokenAddress, optionsPremiumPricer, premiumDiscount ), IWSTETH(collateralAsset).stEthPerToken() ); require(premium > 0, "!premium");
premium = DSMath.wmul( GnosisAuction.getOTokenPremium( otokenAddress, optionsPremiumPricer, premiumDiscount ), IWSTETH(collateralAsset).stEthPerToken() ); require(premium > 0, "!premium");
21,000
1
// Call `_updateFilledState()` but first set `filled[order]` to/`orderTakerAssetFilledAmount`.
function testUpdateFilledState( LibOrder.Order memory order, address takerAddress, bytes32 orderHash, uint256 orderTakerAssetFilledAmount, LibFillResults.FillResults memory fillResults ) public payable
function testUpdateFilledState( LibOrder.Order memory order, address takerAddress, bytes32 orderHash, uint256 orderTakerAssetFilledAmount, LibFillResults.FillResults memory fillResults ) public payable
47,909
168
// Parse the body
vm.timestamp = encodedVM.toUint32(index); index += 4; vm.nonce = encodedVM.toUint32(index); index += 4; vm.emitterChainId = encodedVM.toUint16(index); index += 2; vm.emitterAddress = encodedVM.toBytes32(index);
vm.timestamp = encodedVM.toUint32(index); index += 4; vm.nonce = encodedVM.toUint32(index); index += 4; vm.emitterChainId = encodedVM.toUint16(index); index += 2; vm.emitterAddress = encodedVM.toBytes32(index);
11,945
7
// Handle incoming ether. /
receive() external payable { // solhint-disable-previous-line no-empty-blocks }
receive() external payable { // solhint-disable-previous-line no-empty-blocks }
9,688
170
// Hash of all the strategies array in the system at the time when reallocation was set for index/this array is used for the whole reallocation period even if a strategy gets exploited when reallocating./ This way we can remove the strategy from the system and not breaking the flow of the reallocaton/ Resets when DHW i...
bytes32 internal reallocationStrategiesHash;
bytes32 internal reallocationStrategiesHash;
34,205
52
// safeApprove should only be called when setting an initial allowance,or when resetting it to zero. To increase and decrease it, use'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value));
require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value));
27,083
0
// Virtual wallet
require(self.find_virtual_wallet[_to] == address(0x0)); //Make sure these wallets don't just disappear self.find_virtual_wallet[_from] = address(0x0); self.find_virtual_wallet[_to] = _wallet; WalletOwnershipChangedEvent(_wallet, _from, _to); return true;
require(self.find_virtual_wallet[_to] == address(0x0)); //Make sure these wallets don't just disappear self.find_virtual_wallet[_from] = address(0x0); self.find_virtual_wallet[_to] = _wallet; WalletOwnershipChangedEvent(_wallet, _from, _to); return true;
13,954
63
// We have the following approach: when liability is created we store timestamp and size of liability. If the subsequent trade will deepen this liability or won't fully cover it timestamp will not change. However once outstandingAmount is covered we check whether balance on that asset is positive or not. If not, liabil...
struct Liability { address asset; uint64 timestamp; uint192 outstandingAmount; }
struct Liability { address asset; uint64 timestamp; uint192 outstandingAmount; }
8,344
168
// Array of price sheets
PriceSheet[] sheets;
PriceSheet[] sheets;
12,584
23
// Migrates the tokens hold by this contract to another address receiver Address to receive the migrated tokens /
function migrate(address receiver) external nonReentrant onlyOwner whenPaused { if (receiver == address(0)) revert Errors.ZeroAddress(); _migrate(receiver); }
function migrate(address receiver) external nonReentrant onlyOwner whenPaused { if (receiver == address(0)) revert Errors.ZeroAddress(); _migrate(receiver); }
25,098
34
// Address of token administrator
address public adminAddr;
address public adminAddr;
10,730
134
// Require msg.sender to be the creator of the token id /
modifier creatorOnly(uint256 _id) { require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED"); _; }
modifier creatorOnly(uint256 _id) { require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED"); _; }
4,995
988
// Check balance
uint _b = token.balanceOf(address(this)); if (_b < _r) { uint _withdraw = _r.sub(_b); controller.withdraw(address(token), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(_b); if (_diff < _withdraw) { _r = _b.add(_diff); }
uint _b = token.balanceOf(address(this)); if (_b < _r) { uint _withdraw = _r.sub(_b); controller.withdraw(address(token), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(_b); if (_diff < _withdraw) { _r = _b.add(_diff); }
35,864
95
// Create arrays for effectIds and durations
effectIds = new uint256[](activeEffectsCount); durations = new uint256[](activeEffectsCount);
effectIds = new uint256[](activeEffectsCount); durations = new uint256[](activeEffectsCount);
506
136
// Halve the amount of de tokens
uint256 deTokens = contractBalance * tokensForde / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(deTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(ini...
uint256 deTokens = contractBalance * tokensForde / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(deTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(ini...
5,185
49
// See {IERC721-getApproved}.
function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) { revert CustomErrors.TokenNotFound(); }
function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) { revert CustomErrors.TokenNotFound(); }
7,690
158
// EGG tokens created per block.
uint256 public eggPerBlock;
uint256 public eggPerBlock;
1,369
13
// check if tokens are being transferred to this cash contract
if(receiver == address(this)){
if(receiver == address(this)){
51,384
21
// 25%
_widthdraw(madWallet, ((balance * 10) / 100));
_widthdraw(madWallet, ((balance * 10) / 100));
18,400
292
// Optimised for front-end Address Provider interface
interface IAppAddressProvider { function getDataCompressor() external view returns (address); function getGearToken() external view returns (address); function getWethToken() external view returns (address); function getWETHGateway() external view returns (address); function getPriceOracle() ext...
interface IAppAddressProvider { function getDataCompressor() external view returns (address); function getGearToken() external view returns (address); function getWethToken() external view returns (address); function getWETHGateway() external view returns (address); function getPriceOracle() ext...
15,511
147
// Get current and next Set dollar values
uint256 currentSetDollarValue = allocator.calculateCollateralSetValue( currentCollateralSet ); uint256 nextSetDollarValue = allocator.calculateCollateralSetValue( nextSet );
uint256 currentSetDollarValue = allocator.calculateCollateralSetValue( currentCollateralSet ); uint256 nextSetDollarValue = allocator.calculateCollateralSetValue( nextSet );
37,496
40
// Internal function to stake all outstanding LP tokens to the given position ID.
function _addShare(uint256 id) internal { uint256 shareBalance = actualFarmingTokenBalance(); if (shareBalance > 0) { // 1. Approve token to be spend by masterChef address(farmingToken).safeApprove(address(masterChef), uint256(-1)); // 2. Convert balance to share uint256 share = balan...
function _addShare(uint256 id) internal { uint256 shareBalance = actualFarmingTokenBalance(); if (shareBalance > 0) { // 1. Approve token to be spend by masterChef address(farmingToken).safeApprove(address(masterChef), uint256(-1)); // 2. Convert balance to share uint256 share = balan...
9,220
13
// notify OnValueChanged eventOnValueChanged(recipient, indextokens[str_index].id);
return true;
return true;
29,129
98
// Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/sendtokens. _beneficiary Address receiving the tokens _tokenAmount Number of tokens to be purchased /
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { // deliverTokens token.safeTransfer(_beneficiary, _tokenAmount); }
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { // deliverTokens token.safeTransfer(_beneficiary, _tokenAmount); }
16,659
6
// https:github.com/axiomzen/cryptokitties/issues/244
if ((bigT - smallT == 1) && smallT % 2 == 0) {
if ((bigT - smallT == 1) && smallT % 2 == 0) {
12,388
134
// This method can be used by the controller to extract mistakenly sent tokens to this contract. _token The address of the token contract that you want to recover set to 0 in case you want to extract ether. /
function claimTokens(address _token) external onlyController { if (_token == address(0)) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(address(uint160(_token))); uint balance = token.balanceOf(address(this)); ...
function claimTokens(address _token) external onlyController { if (_token == address(0)) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(address(uint160(_token))); uint balance = token.balanceOf(address(this)); ...
36,117
156
// Pull the creator address before removing the auction.
address curator = auctions[auctionId].curator;
address curator = auctions[auctionId].curator;
27,794
45
// Requires sender to be certified.
modifier only_certified(address who) { require (CERTIFIER.certified(who)); _; }
modifier only_certified(address who) { require (CERTIFIER.certified(who)); _; }
33,049
33
// Returns smart contract information /
function getContractInfo() external view returns (address, address, uint256, uint256, uint256)
function getContractInfo() external view returns (address, address, uint256, uint256, uint256)
39,238
86
// Reward token to Reward per token mapping. Calculated and stored at last drip update
mapping(address => uint256) public rewardPerTokenStored;
mapping(address => uint256) public rewardPerTokenStored;
29,761
9
// This contract extends the AssetHolder contract to enable it to be more easily unit-tested. It exposes public or external functions that set storage variables or wrap otherwise internal functions. It should not be deployed in a production environment./
contract TESTAssetHolder is AssetHolder { address AdjudicatorAddress; /** * @notice Constructor function storing the AdjudicatorAddress. * @dev Constructor function storing the AdjudicatorAddress. * @param _AdjudicatorAddress Address of an Adjudicator contract, supplied at deploy-time. */ ...
contract TESTAssetHolder is AssetHolder { address AdjudicatorAddress; /** * @notice Constructor function storing the AdjudicatorAddress. * @dev Constructor function storing the AdjudicatorAddress. * @param _AdjudicatorAddress Address of an Adjudicator contract, supplied at deploy-time. */ ...
5,189
35
// -------------------------------------------------- TOKENS-----------------------------------------------------------------------------------------------------------------
uint constant public CAPPED_SUPPLY = 20000000000e8; // maximum of GCT token uint constant public TEAM_RESERVE = 2000000000e8; // total tokens team can claim - certain amount of GCT will mint for each claim stage uint constant public COMPANY_RESERVE = 8000000000e8; // total tokens company ...
uint constant public CAPPED_SUPPLY = 20000000000e8; // maximum of GCT token uint constant public TEAM_RESERVE = 2000000000e8; // total tokens team can claim - certain amount of GCT will mint for each claim stage uint constant public COMPANY_RESERVE = 8000000000e8; // total tokens company ...
30,064
324
// handle the transfer of reward tokens via `transferFrom` to reduce the number of transactions required and ensure correctness of the _reward amount
IERC20Upgradeable(_rewardsToken).safeTransferFrom( msg.sender, address(this), _reward ); cumulativeDistributed[_rewardsToken] += _reward; emit RewardAdded( msg.sender, _rewardsToken,
IERC20Upgradeable(_rewardsToken).safeTransferFrom( msg.sender, address(this), _reward ); cumulativeDistributed[_rewardsToken] += _reward; emit RewardAdded( msg.sender, _rewardsToken,
41,764
25
// it can update by yourself
function _update(string memory appName,string memory constituteName,address newCon) internal { address tempAddress = getAddress(appName,constituteName); require( tempAddress != address(0),"OS/update/getAddress/zero_address"); uint256 tempIndex = apps[nameToIndex[appName]].constituteIndex[tem...
function _update(string memory appName,string memory constituteName,address newCon) internal { address tempAddress = getAddress(appName,constituteName); require( tempAddress != address(0),"OS/update/getAddress/zero_address"); uint256 tempIndex = apps[nameToIndex[appName]].constituteIndex[tem...
49,254
17
// State // Initialized boolean /
bool private _initialized;
bool private _initialized;
13,442
313
// RANDOMNESSSS /
function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed, randomNumber ))); }
function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed, randomNumber ))); }
55,863
44
// will pay right away without creating Debt
reserves[getsCollateral][asset_id] += debtAmount; reserves[getsDebt][asset_id] -= debtAmount;
reserves[getsCollateral][asset_id] += debtAmount; reserves[getsDebt][asset_id] -= debtAmount;
40,017
55
// _fundValueAfterPMFees is checked to be non-zero when total supply is non-zero
cycleState[cycleIndex].convertedDeposits = SafeCast.toUint128(requestedDeposits * currentTotalSupply / _fundValueAfterPMFees);
cycleState[cycleIndex].convertedDeposits = SafeCast.toUint128(requestedDeposits * currentTotalSupply / _fundValueAfterPMFees);
33,357
10
// Put a panda up for auction./Does some ownership trickery to create auctions in one tx.
function createSaleAuction( uint256 _pandaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused
function createSaleAuction( uint256 _pandaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused
50,561
11
// lets the owner change the current EtherCollateral implementationetherCollateralImplementation_ the address of the new implementation/
function newEtherCollateralImplementation(address etherCollateralImplementation_) external { require(msg.sender == factoryOwner, "Only factory owner"); require(etherCollateralImplementation_ != address(0), "No zero address for etherCollateralImplementation_"); etherCollateralImplementation ...
function newEtherCollateralImplementation(address etherCollateralImplementation_) external { require(msg.sender == factoryOwner, "Only factory owner"); require(etherCollateralImplementation_ != address(0), "No zero address for etherCollateralImplementation_"); etherCollateralImplementation ...
48,346
13
// erc-20 token to lock
address public token;
address public token;
63,812
3
// FUND has 9 decimals /
function decimals() public view override returns (uint8) { return decs; }
function decimals() public view override returns (uint8) { return decs; }
15,067
99
// Add product
productIndex += 1; Product memory product = Product( productIndex, _name, _verification, _descLink, ProductStatus.Open, _userId, _gallery );
productIndex += 1; Product memory product = Product( productIndex, _name, _verification, _descLink, ProductStatus.Open, _userId, _gallery );
34,904
42
// Constructor instantiates token supply and allocates balanace to the owner. /
function BitImageToken() public { name = "Bitimage Token"; symbol = "BIM"; decimals = 18; released = false; totalSupply = 10000000000 ether; balances[msg.sender] = totalSupply; Transfer(address(0), msg.sender, totalSupply); }
function BitImageToken() public { name = "Bitimage Token"; symbol = "BIM"; decimals = 18; released = false; totalSupply = 10000000000 ether; balances[msg.sender] = totalSupply; Transfer(address(0), msg.sender, totalSupply); }
40,623
62
// A user can withdraw its staking tokens even if there is no rewards tokens on the contract account
function withdraw(uint256 nonce) public override nonReentrant { require(stakeAmounts[msg.sender][nonce] > 0, "StakingLPRewardFixedAPY: This stake nonce was withdrawn"); uint amount = stakeAmounts[msg.sender][nonce]; uint amountRewardEquivalent = stakeAmountsRewardEquivalent[msg.sender][nonce...
function withdraw(uint256 nonce) public override nonReentrant { require(stakeAmounts[msg.sender][nonce] > 0, "StakingLPRewardFixedAPY: This stake nonce was withdrawn"); uint amount = stakeAmounts[msg.sender][nonce]; uint amountRewardEquivalent = stakeAmountsRewardEquivalent[msg.sender][nonce...
44,664
9
// Returns information about the token value held in a Uniswap V3 NFT
library PositionValue { /// @notice Returns the total amounts of token0 and token1, i.e. the sum of fees and principal /// that a given nonfungible position manager token is worth /// @param positionManager The Uniswap V3 NonfungiblePositionManager /// @param tokenId The tokenId of the token for which t...
library PositionValue { /// @notice Returns the total amounts of token0 and token1, i.e. the sum of fees and principal /// that a given nonfungible position manager token is worth /// @param positionManager The Uniswap V3 NonfungiblePositionManager /// @param tokenId The tokenId of the token for which t...
25,751
16
// Set the global token for a contract. /
function setGlobalEffectToken(address _contract, address _token) external { require(hasRole(MODIFIER_ROLE, _msgSender()) || hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Slaps!"); globalEffectTokenForContract[_contract] = IERC20(_token); }
function setGlobalEffectToken(address _contract, address _token) external { require(hasRole(MODIFIER_ROLE, _msgSender()) || hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Slaps!"); globalEffectTokenForContract[_contract] = IERC20(_token); }
29,975
274
// Prize Pool ticket. Can only be set once by calling `setTicket()`.
ITicket internal ticket;
ITicket internal ticket;
49,809
58
// Returns bonuses based on the current totalSupply in percentsAn investor gets the bonus based on the current totalSupply valueeven if the resulting totalSupply after an investment corresponds to different bonus /
function getCurrentBonus() public constant returns (uint){ if(totalSupply < 7000000 * (10 ** decimals)) return 180; if(totalSupply < 14000000 * (10 ** decimals)) return 155; return 140; }
function getCurrentBonus() public constant returns (uint){ if(totalSupply < 7000000 * (10 ** decimals)) return 180; if(totalSupply < 14000000 * (10 ** decimals)) return 155; return 140; }
43,031