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 >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); }
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 >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); }
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 swept with the current main UTXO of the recipient wallet./requestKey Request key built as/`keccak256(movingFundsTxHash | movingFundsOutputIndex)`./ return Details of the moved funds sweep request.
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 price for the bid /
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) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } }
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) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } }
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; uint256 public maxSupplyContractionPercent; uint256 public maxDeptRatioPercent;
uint256 public CHIPPriceOne; uint256 public CHIPPriceCeiling; uint256 public seigniorageSaved; uint256 public maxSupplyExpansionPercent; uint256 public maxSupplyExpansionPercentInDebtPhase; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint256 public maxSupplyContractionPercent; uint256 public maxDeptRatioPercent;
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) { uint256 wantAvailable = IERC20Upgradeable(want).balanceOf(_pool); uint256 ableToPullInUnderlying = MathUpgradeable.min(wantSupplied, wantAvailable); uint256 ableToPullInbToken = (ableToPullInUnderlying * 1 ether) / currentExchangeRate; if (ableToPullInbToken != 0) { IBorrowable(_pool).transfer(_pool, ableToPullInbToken); IBorrowable(_pool).redeem(address(this)); } wantSupplied = wantSuppliedToPool(_pool); } return wantSupplied; }
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) { uint256 wantAvailable = IERC20Upgradeable(want).balanceOf(_pool); uint256 ableToPullInUnderlying = MathUpgradeable.min(wantSupplied, wantAvailable); uint256 ableToPullInbToken = (ableToPullInUnderlying * 1 ether) / currentExchangeRate; if (ableToPullInbToken != 0) { IBorrowable(_pool).transfer(_pool, ableToPullInbToken); IBorrowable(_pool).redeem(address(this)); } wantSupplied = wantSuppliedToPool(_pool); } return wantSupplied; }
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 value of `dividendPerSharebalanceOf(_user)` is changed. To keep the `dividendOf(_user)` unchanged, we add a correction term: `dividendOf(_user) = dividendPerSharebalanceOf(_user) + dividendCorrectionOf(_user)`, where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: `dividendCorrectionOf(_user) = dividendPerShare(old balanceOf(_user)) - (new balanceOf(_user))`. So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
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(msg.sender, obligatedFees); withheldProtocolFees = 0; obligatedFees = 0; emit VaultClosedPermanently(); }
function closeVaultPermanently() external ifNotClosed onlyManager nonReentrant() whenNotPaused() { if(oToken != address(0)) revert oTokenNotCleared(); closedPermanently = true; IERC20(asset).safeTransfer(factory.admin(), withheldProtocolFees); IERC20(asset).safeTransfer(msg.sender, obligatedFees); withheldProtocolFees = 0; obligatedFees = 0; emit VaultClosedPermanently(); }
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 = newCommunityPoolAddress; }
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 = newCommunityPoolAddress; }
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 liquidity/data Any data passed through by the caller via the IUniswapV3PoolActionsmint call
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 { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } }
* 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 { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } }
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.Requires the msg sender to be the owner, approved, or operator _from current owner of the token _to address to receive the ownership of the given token ID _tokenId uint256 ID of the token to be transferred _data bytes data to send along with a safe transfer check /
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 for each epoch over which theprovided intervals span. groupMembershipHistoryIndex Group membership index from wherethe group should be found (For start block). validatorElectionLessers Lesser pointers for validator slashing. validatorElectionGreaters Greater pointers for validator slashing. validatorElectionIndices Vote indices for validator slashing. groupElectionLessers Lesser pointers for group slashing. groupElectionGreaters Greater pointers for group slashing. groupElectionIndices
function slash( uint256[] memory startBlocks, uint256[] memory endBlocks, uint256[] memory signerIndices, uint256 groupMembershipHistoryIndex, address[] memory validatorElectionLessers, address[] memory validatorElectionGreaters, uint256[] memory validatorElectionIndices, address[] memory groupElectionLessers, address[] memory groupElectionGreaters,
function slash( uint256[] memory startBlocks, uint256[] memory endBlocks, uint256[] memory signerIndices, uint256 groupMembershipHistoryIndex, address[] memory validatorElectionLessers, address[] memory validatorElectionGreaters, uint256[] memory validatorElectionIndices, address[] memory groupElectionLessers, address[] memory groupElectionGreaters,
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 _minterRoyalties, uint256 _creatorRoyalties ) public initializer { __Ownable_init(); creator = _creator; minter = _minter; minterRoyalties = _minterRoyalties; creatorRoyalties = _creatorRoyalties; } receive() external payable {} /** * @dev Send the royalties accumulated on the contract * to the minter and creator according to the royalties defined * when minting the token */ function retrieveRoyalties() external onlyOwner { uint256 totalRoyalties = minterRoyalties + creatorRoyalties; // From 0 to 10000 using 2 decimals (550 => 5.5%) uint256 creatorPercentage = (creatorRoyalties * 10000) / totalRoyalties; // Send the right amount to the creator payable(creator).sendValue( (creatorPercentage * address(this).balance) / 10000 ); // Send the remaining balance to the minter payable(minter).sendValue(address(this).balance); } /** * @dev Gets the creator associated to this contract */ function getCreator() external view returns (address) { return creator; } }
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 _minterRoyalties, uint256 _creatorRoyalties ) public initializer { __Ownable_init(); creator = _creator; minter = _minter; minterRoyalties = _minterRoyalties; creatorRoyalties = _creatorRoyalties; } receive() external payable {} /** * @dev Send the royalties accumulated on the contract * to the minter and creator according to the royalties defined * when minting the token */ function retrieveRoyalties() external onlyOwner { uint256 totalRoyalties = minterRoyalties + creatorRoyalties; // From 0 to 10000 using 2 decimals (550 => 5.5%) uint256 creatorPercentage = (creatorRoyalties * 10000) / totalRoyalties; // Send the right amount to the creator payable(creator).sendValue( (creatorPercentage * address(this).balance) / 10000 ); // Send the remaining balance to the minter payable(minter).sendValue(address(this).balance); } /** * @dev Gets the creator associated to this contract */ function getCreator() external view returns (address) { return creator; } }
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 value of a fee type changes. // IMPORTANT: it is possible for a third party to modify the SWAP and FLASH_LOAN fee type values directly in the // ProtocolFeesCollector, which will result in this event not being emitted despite their value changing. Such usage // of the ProtocolFeesCollector is however discouraged: all state-changing interactions with it should originate in // this contract. event ProtocolFeePercentageChanged(uint256 indexed feeType, uint256 percentage); /** * @dev Registers a new fee type in the system, making it queryable via `getFeeTypePercentage` and `getFeeTypeName`, * as well as configurable via `setFeeTypePercentage`. * * `feeType` can be any arbitrary value (that is not in use). * * It is not possible to de-register fee types, nor change their name or maximum value. */ function registerFeeType( uint256 feeType, string memory name, uint256 maximumValue, uint256 initialValue ) external; /** * @dev Returns true if `feeType` has been registered and can be queried. */ function isValidFeeType(uint256 feeType) external view returns (bool); /** * @dev Returns true if `value` is a valid percentage value for `feeType`. */ function isValidFeeTypePercentage(uint256 feeType, uint256 value) external view returns (bool); /** * @dev Sets the percentage value for `feeType` to `newValue`. * * IMPORTANT: it is possible for a third party to modify the SWAP and FLASH_LOAN fee type values directly in the * ProtocolFeesCollector, without invoking this function. This will result in the `ProtocolFeePercentageChanged` * event not being emitted despite their value changing. Such usage of the ProtocolFeesCollector is however * discouraged: only this contract should be granted permission to call `setSwapFeePercentage` and * `setFlashLoanFeePercentage`. */ function setFeeTypePercentage(uint256 feeType, uint256 newValue) external; /** * @dev Returns the current percentage value for `feeType`. This is the preferred mechanism for querying these - * whenever possible, use this fucntion instead of e.g. querying the ProtocolFeesCollector. */ function getFeeTypePercentage(uint256 feeType) external view returns (uint256); /** * @dev Returns `feeType`'s maximum value. */ function getFeeTypeMaximumPercentage(uint256 feeType) external view returns (uint256); /** * @dev Returns `feeType`'s name. */ function getFeeTypeName(uint256 feeType) external view returns (string memory); }
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 value of a fee type changes. // IMPORTANT: it is possible for a third party to modify the SWAP and FLASH_LOAN fee type values directly in the // ProtocolFeesCollector, which will result in this event not being emitted despite their value changing. Such usage // of the ProtocolFeesCollector is however discouraged: all state-changing interactions with it should originate in // this contract. event ProtocolFeePercentageChanged(uint256 indexed feeType, uint256 percentage); /** * @dev Registers a new fee type in the system, making it queryable via `getFeeTypePercentage` and `getFeeTypeName`, * as well as configurable via `setFeeTypePercentage`. * * `feeType` can be any arbitrary value (that is not in use). * * It is not possible to de-register fee types, nor change their name or maximum value. */ function registerFeeType( uint256 feeType, string memory name, uint256 maximumValue, uint256 initialValue ) external; /** * @dev Returns true if `feeType` has been registered and can be queried. */ function isValidFeeType(uint256 feeType) external view returns (bool); /** * @dev Returns true if `value` is a valid percentage value for `feeType`. */ function isValidFeeTypePercentage(uint256 feeType, uint256 value) external view returns (bool); /** * @dev Sets the percentage value for `feeType` to `newValue`. * * IMPORTANT: it is possible for a third party to modify the SWAP and FLASH_LOAN fee type values directly in the * ProtocolFeesCollector, without invoking this function. This will result in the `ProtocolFeePercentageChanged` * event not being emitted despite their value changing. Such usage of the ProtocolFeesCollector is however * discouraged: only this contract should be granted permission to call `setSwapFeePercentage` and * `setFlashLoanFeePercentage`. */ function setFeeTypePercentage(uint256 feeType, uint256 newValue) external; /** * @dev Returns the current percentage value for `feeType`. This is the preferred mechanism for querying these - * whenever possible, use this fucntion instead of e.g. querying the ProtocolFeesCollector. */ function getFeeTypePercentage(uint256 feeType) external view returns (uint256); /** * @dev Returns `feeType`'s maximum value. */ function getFeeTypeMaximumPercentage(uint256 feeType) external view returns (uint256); /** * @dev Returns `feeType`'s name. */ function getFeeTypeName(uint256 feeType) external view returns (string memory); }
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 is completed
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, liability still in the place but time counter is dropped and timestamp set to `now`.
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(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 deTokens = contractBalance * tokensForde / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(deTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
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() external view returns (address); function getLeveragedActions() external view returns (address); }
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() external view returns (address); function getLeveragedActions() external view returns (address); }
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 = balanceToShare(shareBalance); // 3. Update shares shares[id] = shares[id].add(share); totalShare = totalShare.add(share); rewardBalance = rewardBalance.add(masterChef.pendingCake(pid, address(this))); // 4. Deposit balance to PancakeMasterChef masterChef.enterStaking(shareBalance); // 5. Reset approve token address(farmingToken).safeApprove(address(masterChef), 0); emit AddShare(id, share); } }
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 = balanceToShare(shareBalance); // 3. Update shares shares[id] = shares[id].add(share); totalShare = totalShare.add(share); rewardBalance = rewardBalance.add(masterChef.pendingCake(pid, address(this))); // 4. Deposit balance to PancakeMasterChef masterChef.enterStaking(shareBalance); // 5. Reset approve token address(farmingToken).safeApprove(address(masterChef), 0); emit AddShare(id, share); } }
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)); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); }
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)); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); }
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. */ constructor(address _AdjudicatorAddress) public { AdjudicatorAddress = _AdjudicatorAddress; } modifier AdjudicatorOnly { require(msg.sender == AdjudicatorAddress, 'Only the NitroAdjudicator is authorized'); _; } // Public wrappers for internal methods: /** * @dev Manually set the holdings mapping to a given amount for a given channelId. Shortcuts the deposit workflow (ONLY USE IN A TESTING ENVIRONMENT) * @param channelId Unique identifier for a state channel. * @param amount The number of assets that should now be "escrowed: against channelId */ function setHoldings(bytes32 channelId, uint256 amount) external { holdings[channelId] = amount; } /** * @dev Sets the given assetOutcomeHash for the given channelId in the assetOutcomeHashes storage mapping, but circumvents the AdjudicatorOnly modifier (thereby allowing externally owned accounts to call the method). * @param channelId Unique identifier for a state channel. * @param assetOutcomeHash The keccak256 of the abi.encode of the Outcome. */ function setAssetOutcomeHashPermissionless(bytes32 channelId, bytes32 assetOutcomeHash) external returns (bool success) { _setAssetOutcomeHash(channelId, assetOutcomeHash); return true; } /** * @notice Transfers the funds escrowed against `channelId` to the beneficiaries of that channel. No checks performed against storage in this contract. Permissions have been bypassed for testing purposes. * @dev Transfers the funds escrowed against `channelId` and transfers them to the beneficiaries of that channel. No checks performed against storage in this contract. Permissions have been bypassed for testing purposes. * @param channelId Unique identifier for a state channel. * @param allocationBytes The abi.encode of AssetOutcome.Allocation */ function transferAllAdjudicatorOnly(bytes32 channelId, bytes calldata allocationBytes) external { _transferAll(channelId, allocationBytes); } /** * @dev Wrapper for otherwise internal function. Checks if a given destination is external (and can therefore have assets transferred to it) or not. * @param destination Destination to be checked. * @return True if the destination is external, false otherwise. */ function isExternalDestination(bytes32 destination) public pure returns (bool) { return _isExternalDestination(destination); } /** * @dev Wrapper for otherwise internal function. Converts an ethereum address to a nitro external destination. * @param participant The address to be converted. * @return The input address left-padded with zeros. */ function addressToBytes32(address participant) public pure returns (bytes32) { return _addressToBytes32(participant); } }
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. */ constructor(address _AdjudicatorAddress) public { AdjudicatorAddress = _AdjudicatorAddress; } modifier AdjudicatorOnly { require(msg.sender == AdjudicatorAddress, 'Only the NitroAdjudicator is authorized'); _; } // Public wrappers for internal methods: /** * @dev Manually set the holdings mapping to a given amount for a given channelId. Shortcuts the deposit workflow (ONLY USE IN A TESTING ENVIRONMENT) * @param channelId Unique identifier for a state channel. * @param amount The number of assets that should now be "escrowed: against channelId */ function setHoldings(bytes32 channelId, uint256 amount) external { holdings[channelId] = amount; } /** * @dev Sets the given assetOutcomeHash for the given channelId in the assetOutcomeHashes storage mapping, but circumvents the AdjudicatorOnly modifier (thereby allowing externally owned accounts to call the method). * @param channelId Unique identifier for a state channel. * @param assetOutcomeHash The keccak256 of the abi.encode of the Outcome. */ function setAssetOutcomeHashPermissionless(bytes32 channelId, bytes32 assetOutcomeHash) external returns (bool success) { _setAssetOutcomeHash(channelId, assetOutcomeHash); return true; } /** * @notice Transfers the funds escrowed against `channelId` to the beneficiaries of that channel. No checks performed against storage in this contract. Permissions have been bypassed for testing purposes. * @dev Transfers the funds escrowed against `channelId` and transfers them to the beneficiaries of that channel. No checks performed against storage in this contract. Permissions have been bypassed for testing purposes. * @param channelId Unique identifier for a state channel. * @param allocationBytes The abi.encode of AssetOutcome.Allocation */ function transferAllAdjudicatorOnly(bytes32 channelId, bytes calldata allocationBytes) external { _transferAll(channelId, allocationBytes); } /** * @dev Wrapper for otherwise internal function. Checks if a given destination is external (and can therefore have assets transferred to it) or not. * @param destination Destination to be checked. * @return True if the destination is external, false otherwise. */ function isExternalDestination(bytes32 destination) public pure returns (bool) { return _isExternalDestination(destination); } /** * @dev Wrapper for otherwise internal function. Converts an ethereum address to a nitro external destination. * @param participant The address to be converted. * @return The input address left-padded with zeros. */ function addressToBytes32(address participant) public pure returns (bytes32) { return _addressToBytes32(participant); } }
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 reserve for - lock for 6 months than can mint this amount of GCT uint constant public PRIVATE_SALE = 900000000e8; // total tokens for private sale uint constant public PROMOTION_PROGRAM = 1000000000e8; // total tokens for promotion program - 405,000,000 for referral and 595,000,000 for bounty uint constant public CROWDSALE_SUPPLY = 8100000000e8; // total tokens for crowdsale
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 reserve for - lock for 6 months than can mint this amount of GCT uint constant public PRIVATE_SALE = 900000000e8; // total tokens for private sale uint constant public PROMOTION_PROGRAM = 1000000000e8; // total tokens for promotion program - 405,000,000 for referral and 595,000,000 for bounty uint constant public CROWDSALE_SUPPLY = 8100000000e8; // total tokens for crowdsale
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[tempAddress]; apps[nameToIndex[appName]].constitute[tempIndex] = newCon; }
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[tempAddress]; apps[nameToIndex[appName]].constitute[tempIndex] = newCon; }
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 = etherCollateralImplementation_; emit NewEtherCollateralImplementation(etherCollateralImplementation); }
function newEtherCollateralImplementation(address etherCollateralImplementation_) external { require(msg.sender == factoryOwner, "Only factory owner"); require(etherCollateralImplementation_ != address(0), "No zero address for etherCollateralImplementation_"); etherCollateralImplementation = etherCollateralImplementation_; emit NewEtherCollateralImplementation(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]; _totalSupply = _totalSupply.sub(amount); _totalSupplyRewardEquivalent = _totalSupplyRewardEquivalent.sub(amountRewardEquivalent); _balances[msg.sender] = _balances[msg.sender].sub(amount); _balancesRewardEquivalent[msg.sender] = _balancesRewardEquivalent[msg.sender].sub(amountRewardEquivalent); IERC20(stakingLPToken).safeTransfer(msg.sender, amount); stakeAmounts[msg.sender][nonce] = 0; stakeAmountsRewardEquivalent[msg.sender][nonce] = 0; emit Withdrawn(msg.sender, amount); }
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]; _totalSupply = _totalSupply.sub(amount); _totalSupplyRewardEquivalent = _totalSupplyRewardEquivalent.sub(amountRewardEquivalent); _balances[msg.sender] = _balances[msg.sender].sub(amount); _balancesRewardEquivalent[msg.sender] = _balancesRewardEquivalent[msg.sender].sub(amountRewardEquivalent); IERC20(stakingLPToken).safeTransfer(msg.sender, amount); stakeAmounts[msg.sender][nonce] = 0; stakeAmountsRewardEquivalent[msg.sender][nonce] = 0; emit Withdrawn(msg.sender, amount); }
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 to get the total value /// @param sqrtRatioX96 The square root price X96 for which to calculate the principal amounts /// @return amount0 The total amount of token0 including principal and fees /// @return amount1 The total amount of token1 including principal and fees function total( INonfungiblePositionManager positionManager, uint256 tokenId, uint160 sqrtRatioX96 ) internal view returns (uint256 amount0, uint256 amount1) { (uint256 amount0Principal, uint256 amount1Principal) = principal(positionManager, tokenId, sqrtRatioX96); (uint256 amount0Fee, uint256 amount1Fee) = fees(positionManager, tokenId); return (amount0Principal + amount0Fee, amount1Principal + amount1Fee); } /// @notice Calculates the principal (currently acting as liquidity) owed to the token owner in the event /// that the position is burned /// @param positionManager The Uniswap V3 NonfungiblePositionManager /// @param tokenId The tokenId of the token for which to get the total principal owed /// @param sqrtRatioX96 The square root price X96 for which to calculate the principal amounts /// @return amount0 The principal amount of token0 /// @return amount1 The principal amount of token1 function principal( INonfungiblePositionManager positionManager, uint256 tokenId, uint160 sqrtRatioX96 ) internal view returns (uint256 amount0, uint256 amount1) { (, , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = positionManager.positions(tokenId); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } struct FeeParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint128 liquidity; uint256 positionFeeGrowthInside0LastX128; uint256 positionFeeGrowthInside1LastX128; uint256 tokensOwed0; uint256 tokensOwed1; } /// @notice Calculates the total fees owed to the token owner /// @param positionManager The Uniswap V3 NonfungiblePositionManager /// @param tokenId The tokenId of the token for which to get the total fees owed /// @return amount0 The amount of fees owed in token0 /// @return amount1 The amount of fees owed in token1 function fees(INonfungiblePositionManager positionManager, uint256 tokenId) internal view returns (uint256 amount0, uint256 amount1) { ( , , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 positionFeeGrowthInside0LastX128, uint256 positionFeeGrowthInside1LastX128, uint256 tokensOwed0, uint256 tokensOwed1 ) = positionManager.positions(tokenId); return _fees( positionManager, FeeParams({ token0: token0, token1: token1, fee: fee, tickLower: tickLower, tickUpper: tickUpper, liquidity: liquidity, positionFeeGrowthInside0LastX128: positionFeeGrowthInside0LastX128, positionFeeGrowthInside1LastX128: positionFeeGrowthInside1LastX128, tokensOwed0: tokensOwed0, tokensOwed1: tokensOwed1 }) ); } function _fees(INonfungiblePositionManager positionManager, FeeParams memory feeParams) private view returns (uint256 amount0, uint256 amount1) { (uint256 poolFeeGrowthInside0LastX128, uint256 poolFeeGrowthInside1LastX128) = _getFeeGrowthInside( IUniswapV3Pool( PoolAddress.computeAddress( positionManager.factory(), PoolAddress.PoolKey({token0: feeParams.token0, token1: feeParams.token1, fee: feeParams.fee}) ) ), feeParams.tickLower, feeParams.tickUpper ); amount0 = FullMath.mulDiv( poolFeeGrowthInside0LastX128 - feeParams.positionFeeGrowthInside0LastX128, feeParams.liquidity, FixedPoint128.Q128 ) + feeParams.tokensOwed0; amount1 = FullMath.mulDiv( poolFeeGrowthInside1LastX128 - feeParams.positionFeeGrowthInside1LastX128, feeParams.liquidity, FixedPoint128.Q128 ) + feeParams.tokensOwed1; } function _getFeeGrowthInside( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper ) private view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { (, int24 tickCurrent, , , , , ) = pool.slot0(); (, , uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128, , , , ) = pool.ticks(tickLower); (, , uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128, , , , ) = pool.ticks(tickUpper); if (tickCurrent < tickLower) { feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } else if (tickCurrent < tickUpper) { uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128(); uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128(); feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } else { feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128; feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128; } } }
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 to get the total value /// @param sqrtRatioX96 The square root price X96 for which to calculate the principal amounts /// @return amount0 The total amount of token0 including principal and fees /// @return amount1 The total amount of token1 including principal and fees function total( INonfungiblePositionManager positionManager, uint256 tokenId, uint160 sqrtRatioX96 ) internal view returns (uint256 amount0, uint256 amount1) { (uint256 amount0Principal, uint256 amount1Principal) = principal(positionManager, tokenId, sqrtRatioX96); (uint256 amount0Fee, uint256 amount1Fee) = fees(positionManager, tokenId); return (amount0Principal + amount0Fee, amount1Principal + amount1Fee); } /// @notice Calculates the principal (currently acting as liquidity) owed to the token owner in the event /// that the position is burned /// @param positionManager The Uniswap V3 NonfungiblePositionManager /// @param tokenId The tokenId of the token for which to get the total principal owed /// @param sqrtRatioX96 The square root price X96 for which to calculate the principal amounts /// @return amount0 The principal amount of token0 /// @return amount1 The principal amount of token1 function principal( INonfungiblePositionManager positionManager, uint256 tokenId, uint160 sqrtRatioX96 ) internal view returns (uint256 amount0, uint256 amount1) { (, , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = positionManager.positions(tokenId); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } struct FeeParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint128 liquidity; uint256 positionFeeGrowthInside0LastX128; uint256 positionFeeGrowthInside1LastX128; uint256 tokensOwed0; uint256 tokensOwed1; } /// @notice Calculates the total fees owed to the token owner /// @param positionManager The Uniswap V3 NonfungiblePositionManager /// @param tokenId The tokenId of the token for which to get the total fees owed /// @return amount0 The amount of fees owed in token0 /// @return amount1 The amount of fees owed in token1 function fees(INonfungiblePositionManager positionManager, uint256 tokenId) internal view returns (uint256 amount0, uint256 amount1) { ( , , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 positionFeeGrowthInside0LastX128, uint256 positionFeeGrowthInside1LastX128, uint256 tokensOwed0, uint256 tokensOwed1 ) = positionManager.positions(tokenId); return _fees( positionManager, FeeParams({ token0: token0, token1: token1, fee: fee, tickLower: tickLower, tickUpper: tickUpper, liquidity: liquidity, positionFeeGrowthInside0LastX128: positionFeeGrowthInside0LastX128, positionFeeGrowthInside1LastX128: positionFeeGrowthInside1LastX128, tokensOwed0: tokensOwed0, tokensOwed1: tokensOwed1 }) ); } function _fees(INonfungiblePositionManager positionManager, FeeParams memory feeParams) private view returns (uint256 amount0, uint256 amount1) { (uint256 poolFeeGrowthInside0LastX128, uint256 poolFeeGrowthInside1LastX128) = _getFeeGrowthInside( IUniswapV3Pool( PoolAddress.computeAddress( positionManager.factory(), PoolAddress.PoolKey({token0: feeParams.token0, token1: feeParams.token1, fee: feeParams.fee}) ) ), feeParams.tickLower, feeParams.tickUpper ); amount0 = FullMath.mulDiv( poolFeeGrowthInside0LastX128 - feeParams.positionFeeGrowthInside0LastX128, feeParams.liquidity, FixedPoint128.Q128 ) + feeParams.tokensOwed0; amount1 = FullMath.mulDiv( poolFeeGrowthInside1LastX128 - feeParams.positionFeeGrowthInside1LastX128, feeParams.liquidity, FixedPoint128.Q128 ) + feeParams.tokensOwed1; } function _getFeeGrowthInside( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper ) private view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { (, int24 tickCurrent, , , , , ) = pool.slot0(); (, , uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128, , , , ) = pool.ticks(tickLower); (, , uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128, , , , ) = pool.ticks(tickUpper); if (tickCurrent < tickLower) { feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } else if (tickCurrent < tickUpper) { uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128(); uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128(); feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } else { feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128; feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128; } } }
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