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
|
|---|---|---|---|---|
219
|
// Group 0: No grouping
|
totalNumVotes += total[0];
numVotes += signed[0];
|
totalNumVotes += total[0];
numVotes += signed[0];
| 40,471
|
39
|
// update locked votes
|
function _updateLockedVotes() private inline {
uint32 maxVotes = 0;
optional(uint32, uint32) maxVotesOpt = _spentVotes.max();
if (maxVotesOpt.hasValue()) {
(uint32 votes, ) = maxVotesOpt.get();
maxVotes = votes;
}
if (_lockedVotes != maxVotes) {
_lockedVotes = maxVotes;
}
}
|
function _updateLockedVotes() private inline {
uint32 maxVotes = 0;
optional(uint32, uint32) maxVotesOpt = _spentVotes.max();
if (maxVotesOpt.hasValue()) {
(uint32 votes, ) = maxVotesOpt.get();
maxVotes = votes;
}
if (_lockedVotes != maxVotes) {
_lockedVotes = maxVotes;
}
}
| 39,221
|
76
|
// Get the ETH / USD price first, and cut it down to 1e6 precision
|
uint256 __eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
uint256 price_vs_eth = 0;
if (choice == PriceChoice.FRAX) {
price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH
}
|
uint256 __eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
uint256 price_vs_eth = 0;
if (choice == PriceChoice.FRAX) {
price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH
}
| 3,975
|
20
|
// Private function for spawning an eip-1167 minimal proxy using `CREATE2`./ Reverts with appropriate error string if deployment is unsuccessful./initCode bytes The spawner code and initialization calldata./safeSalt bytes32 A valid salt hashed with creator address./target address The expected address of the proxy./ return The address of the newly-spawned contract.
|
function _executeSpawnCreate2(bytes memory initCode, bytes32 safeSalt, address target) private returns (address spawnedContract) {
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
spawnedContract := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
safeSalt // pass in the salt value.
)
// pass along failure message from failed contract deployment and revert.
if iszero(spawnedContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// validate spawned instance matches target
require(spawnedContract == target, "attempted deployment to unexpected address");
// explicit return
return spawnedContract;
}
|
function _executeSpawnCreate2(bytes memory initCode, bytes32 safeSalt, address target) private returns (address spawnedContract) {
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
spawnedContract := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
safeSalt // pass in the salt value.
)
// pass along failure message from failed contract deployment and revert.
if iszero(spawnedContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// validate spawned instance matches target
require(spawnedContract == target, "attempted deployment to unexpected address");
// explicit return
return spawnedContract;
}
| 9,632
|
89
|
// Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds./ Caller must provide the answer history for each question, in reverse order/Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call./question_ids The IDs of the questions you want to claim for/lengths The number of history entries you will supply for each question ID/hist_hashes In a single list for all supplied questions, the hash of each history entry./addrs In a single list for all supplied questions, the address of each answerer or commitment sender/bonds In a
|
function claimMultipleAndWithdrawBalance(
bytes32[] question_ids, uint256[] lengths,
bytes32[] hist_hashes, address[] addrs, uint256[] bonds, bytes32[] answers
)
stateAny() // The finalization checks are done in the claimWinnings function
|
function claimMultipleAndWithdrawBalance(
bytes32[] question_ids, uint256[] lengths,
bytes32[] hist_hashes, address[] addrs, uint256[] bonds, bytes32[] answers
)
stateAny() // The finalization checks are done in the claimWinnings function
| 85,517
|
36
|
// transfer ownership
|
propertyIndexToOwner[_tokenId] = _to;
|
propertyIndexToOwner[_tokenId] = _to;
| 49,491
|
4
|
// total liquidity staking in the pool
|
uint256 totalLiquidity;
|
uint256 totalLiquidity;
| 29,376
|
208
|
// Info of each user that stakes LP tokens.
|
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
mapping (address => address) public referrerInfo;
mapping (address => uint) public whitelistContributed;
|
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
mapping (address => address) public referrerInfo;
mapping (address => uint) public whitelistContributed;
| 207
|
95
|
// If no new income is added for more than DISTRIBUTION_PERIOD blocks, then do not distribute any more rewards
|
function rewardRate() public view returns(uint) {
uint blocksElapsed = block.number - lastIncomeBlock;
if (blocksElapsed < DISTRIBUTION_PERIOD) {
return rewardRateStored;
} else {
return 0;
}
}
|
function rewardRate() public view returns(uint) {
uint blocksElapsed = block.number - lastIncomeBlock;
if (blocksElapsed < DISTRIBUTION_PERIOD) {
return rewardRateStored;
} else {
return 0;
}
}
| 38,873
|
44
|
// Mapping of assets that can only be borrowed by whitelist /
|
mapping(address => bool) public borrowRestricted;
|
mapping(address => bool) public borrowRestricted;
| 10,556
|
92
|
// Returns the staked information of specific token ids as an array of bytes. tokenIds - token ids to check againstreturn bytes[] /
|
function stakedInfoOf(
uint256[] memory tokenIds
|
function stakedInfoOf(
uint256[] memory tokenIds
| 9,722
|
292
|
// Pause the sale manually (Callable by owner only)/
|
function pauseSale() onlyOwner public {
isSalePaused = true;
}
|
function pauseSale() onlyOwner public {
isSalePaused = true;
}
| 35,089
|
1
|
// Location
|
mapping(uint256 => uint256) public padlock2location;
mapping(uint256 => bytes32) public padlock2location_extra_data;
mapping(uint256 => uint256) public location2padlock;
mapping(uint256 => uint256) public location2price_wei;
|
mapping(uint256 => uint256) public padlock2location;
mapping(uint256 => bytes32) public padlock2location_extra_data;
mapping(uint256 => uint256) public location2padlock;
mapping(uint256 => uint256) public location2price_wei;
| 7,717
|
0
|
// struct to store each token's traits
|
struct LlamaDog {
bool isLlama;
uint8 body;
uint8 hat;
uint8 eye;
uint8 mouth;
uint8 clothes;
uint8 tail;
uint8 alphaIndex;
}
|
struct LlamaDog {
bool isLlama;
uint8 body;
uint8 hat;
uint8 eye;
uint8 mouth;
uint8 clothes;
uint8 tail;
uint8 alphaIndex;
}
| 7,776
|
58
|
// checks only Oraclize address is calling/
|
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
|
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
| 53,705
|
0
|
// My shit
|
uint256 amount2B = 5000000000000000000000;
uint256 amount2Breturned = 4000000000000000000000;
|
uint256 amount2B = 5000000000000000000000;
uint256 amount2Breturned = 4000000000000000000000;
| 30,455
|
289
|
// Auction for NFT. VREX Lab Co., Ltd /
|
contract Auction is Pausable, AuctionBase {
/**
* @dev Removes all Ether from the contract to the NFT contract.
*/
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
nftAddress.transfer(address(this).balance);
}
/**
* @dev Creates and begins a new auction.
* @param _tokenId ID of the token to creat an auction, caller must be it's owner.
* @param _price Price of the token (in wei).
* @param _seller Seller of this token.
*/
function createAuction(
uint256 _tokenId,
uint256 _price,
address _seller
)
external
whenNotPaused
canBeStoredWith128Bits(_price)
{
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_price),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/**
* @dev Bids on an open auction, completing the auction and transferring
* ownership of the NFT if enough Ether is supplied.
* @param _tokenId - ID of token to bid on.
*/
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/**
* @dev Cancels an auction and returns the NFT to the current owner.
* @param _tokenId ID of the token on auction to cancel.
* @param _seller The seller's address.
*/
function cancelAuction(uint256 _tokenId, address _seller)
external
{
// Requires that this function should only be called from the
// `cancelSaleAuction()` of NFT ownership contract. This function gets
// the _seller directly from it's arguments, so if this check doesn't
// exist, then anyone can cancel the auction! OMG!
require(msg.sender == address(nonFungibleContract));
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(_seller == seller);
_cancelAuction(_tokenId, seller);
}
/**
* @dev Cancels an auction when the contract is paused.
* Only the owner may do this, and NFTs are returned to the seller.
* @param _tokenId ID of the token on auction to cancel.
*/
function cancelAuctionWhenPaused(uint256 _tokenId)
external
whenPaused
onlyOwner
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/**
* @dev Returns the auction information for an NFT
* @param _tokenId ID of the NFT on auction
*/
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 price,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.price,
auction.startedAt
);
}
/**
* @dev Returns the current price of the token on auction.
* @param _tokenId ID of the token
*/
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
|
contract Auction is Pausable, AuctionBase {
/**
* @dev Removes all Ether from the contract to the NFT contract.
*/
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
nftAddress.transfer(address(this).balance);
}
/**
* @dev Creates and begins a new auction.
* @param _tokenId ID of the token to creat an auction, caller must be it's owner.
* @param _price Price of the token (in wei).
* @param _seller Seller of this token.
*/
function createAuction(
uint256 _tokenId,
uint256 _price,
address _seller
)
external
whenNotPaused
canBeStoredWith128Bits(_price)
{
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_price),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/**
* @dev Bids on an open auction, completing the auction and transferring
* ownership of the NFT if enough Ether is supplied.
* @param _tokenId - ID of token to bid on.
*/
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/**
* @dev Cancels an auction and returns the NFT to the current owner.
* @param _tokenId ID of the token on auction to cancel.
* @param _seller The seller's address.
*/
function cancelAuction(uint256 _tokenId, address _seller)
external
{
// Requires that this function should only be called from the
// `cancelSaleAuction()` of NFT ownership contract. This function gets
// the _seller directly from it's arguments, so if this check doesn't
// exist, then anyone can cancel the auction! OMG!
require(msg.sender == address(nonFungibleContract));
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(_seller == seller);
_cancelAuction(_tokenId, seller);
}
/**
* @dev Cancels an auction when the contract is paused.
* Only the owner may do this, and NFTs are returned to the seller.
* @param _tokenId ID of the token on auction to cancel.
*/
function cancelAuctionWhenPaused(uint256 _tokenId)
external
whenPaused
onlyOwner
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/**
* @dev Returns the auction information for an NFT
* @param _tokenId ID of the NFT on auction
*/
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 price,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.price,
auction.startedAt
);
}
/**
* @dev Returns the current price of the token on auction.
* @param _tokenId ID of the token
*/
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
| 17,417
|
61
|
// Returns array with owner addresses, which confirmed transaction./transactionId Transaction ID./ return _confirmations Returns array of owner addresses.
|
function getConfirmations(uint transactionId)
public
view
returns (address[] memory _confirmations)
|
function getConfirmations(uint transactionId)
public
view
returns (address[] memory _confirmations)
| 7,517
|
130
|
// Copyright (C) udev 2020
|
interface IXEth is IERC20 {
function deposit() external payable;
function xlockerMint(uint256 wad, address dst) external;
function withdraw(uint256 wad) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
event XlockerMint(uint256 wad, address dst);
}
|
interface IXEth is IERC20 {
function deposit() external payable;
function xlockerMint(uint256 wad, address dst) external;
function withdraw(uint256 wad) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
event XlockerMint(uint256 wad, address dst);
}
| 17,170
|
70
|
// Performs a swap with a single Pool. If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokenstaken from the Pool, which must be greater than or equal to `limit`. If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokenssent to the Pool, which must be less than or equal to `limit`. Internal Balance usage and the recipient are determined by the `funds` struct. Emits a `Swap` event. /
|
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external returns (uint256 amountCalculated);
|
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external returns (uint256 amountCalculated);
| 10,091
|
199
|
// Fund token address for joining and redeeming/This is address is created when the fund is first created./ return Fund token address
|
function ioToken() public view returns (IERC20){
return IERC20(SmartPoolStorage.load().token);
}
|
function ioToken() public view returns (IERC20){
return IERC20(SmartPoolStorage.load().token);
}
| 22,228
|
0
|
// Call precompiled contract to copy data
|
ret := staticcall(0x10000, 0x04, add(arr, 0x20), length, add(arr, 0x21), length)
returndatacopy(add(result, 0x20), 0x00, length)
|
ret := staticcall(0x10000, 0x04, add(arr, 0x20), length, add(arr, 0x21), length)
returndatacopy(add(result, 0x20), 0x00, length)
| 51,183
|
783
|
// Allows owner to change max gas price/_maxGasPrice New max gas price
|
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
|
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
| 57,939
|
29
|
// Emit event
|
emit SetDeployerEvent(oldDeployer, newDeployer);
|
emit SetDeployerEvent(oldDeployer, newDeployer);
| 29,419
|
84
|
// Return the sell price of 1 individual token. /
|
function buyPrice()
public
view
returns(uint256)
|
function buyPrice()
public
view
returns(uint256)
| 3,273
|
2
|
// bytes4 private constant _iSTATIC_TOKEN_SUPPLY_ID = type(iStaticTokenSupply).interfaceId;bytes4 private constant _iTOKEN_IDENTIFIER_ID = type(iTokenIdentifier).interfaceId;
|
function _requireSupportsInterface(
address token
)private
|
function _requireSupportsInterface(
address token
)private
| 40,866
|
19
|
// Finally, we copy the constructorArgs to the end of the array. Unfortunately there is no way to avoid this copy, as it is not possible to tell Solidity where to store the result of `abi.encode()`.
|
uint256 constructorArgsDataPtr;
uint256 constructorArgsCodeDataPtr;
assembly {
constructorArgsDataPtr := add(constructorArgs, 32)
constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize)
}
|
uint256 constructorArgsDataPtr;
uint256 constructorArgsCodeDataPtr;
assembly {
constructorArgsDataPtr := add(constructorArgs, 32)
constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize)
}
| 24,439
|
171
|
// DefiMToken with Governance.
|
contract DefiMToken is ERC20("DefiMToken", "DEFIM"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2;
// ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
// balance of underlying SUSHIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2 ** 32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly {chainId := chainid()}
return chainId;
}
}
|
contract DefiMToken is ERC20("DefiMToken", "DEFIM"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2;
// ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
// balance of underlying SUSHIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2 ** 32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly {chainId := chainid()}
return chainId;
}
}
| 38,993
|
191
|
// setBaseTokenURIurl string of baseTokenURI/
|
function setBaseTokenURI(string memory url) public override onlyOwner() {
_baseTokenURI = url;
}
|
function setBaseTokenURI(string memory url) public override onlyOwner() {
_baseTokenURI = url;
}
| 58,952
|
85
|
// Increasing the withdrawn tokens by the investor. Увеличение количества выведенных средств инвестором;
|
withdrawn[msg.sender] = withdrawn[msg.sender].add(amountToWithdraw);
|
withdrawn[msg.sender] = withdrawn[msg.sender].add(amountToWithdraw);
| 40,039
|
11
|
// Library for figuring out the "tier" (1-7) of a dividend rate
|
library ZethrTierLibrary{
uint constant internal magnitude = 2**64;
function getTier(uint divRate) internal pure returns (uint){
// Tier logic
// Returns the index of the UsedBankrollAddresses which should be used to call into to withdraw tokens
// We can divide by magnitude
// Remainder is removed so we only get the actual number we want
uint actualDiv = divRate;
if (actualDiv >= 30){
return 6;
} else if (actualDiv >= 25){
return 5;
} else if (actualDiv >= 20){
return 4;
} else if (actualDiv >= 15){
return 3;
} else if (actualDiv >= 10){
return 2;
} else if (actualDiv >= 5){
return 1;
} else if (actualDiv >= 2){
return 0;
} else{
// Impossible
revert();
}
}
}
|
library ZethrTierLibrary{
uint constant internal magnitude = 2**64;
function getTier(uint divRate) internal pure returns (uint){
// Tier logic
// Returns the index of the UsedBankrollAddresses which should be used to call into to withdraw tokens
// We can divide by magnitude
// Remainder is removed so we only get the actual number we want
uint actualDiv = divRate;
if (actualDiv >= 30){
return 6;
} else if (actualDiv >= 25){
return 5;
} else if (actualDiv >= 20){
return 4;
} else if (actualDiv >= 15){
return 3;
} else if (actualDiv >= 10){
return 2;
} else if (actualDiv >= 5){
return 1;
} else if (actualDiv >= 2){
return 0;
} else{
// Impossible
revert();
}
}
}
| 13,767
|
1
|
// The Balancer Vault the protocol uses for managing user funds.
|
IVault public immutable vault;
|
IVault public immutable vault;
| 38,458
|
4
|
// ----------------------------- FUND INTERFACE -----------------------------
|
function buyTokens(
bytes32 _exchangeId,
ERC20Extended[] _tokens,
uint[] _amounts,
uint[] _minimumRates)
public onlyOwner returns(bool)
|
function buyTokens(
bytes32 _exchangeId,
ERC20Extended[] _tokens,
uint[] _amounts,
uint[] _minimumRates)
public onlyOwner returns(bool)
| 24,730
|
125
|
// early sell logic
|
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
|
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
| 2,575
|
4
|
// Creates a Chainlink request with the uint256 multiplier job
|
function requestEthereumPrice()
public
onlyOwner
|
function requestEthereumPrice()
public
onlyOwner
| 17,397
|
37
|
// ERC20
|
return true;
|
return true;
| 4,062
|
2
|
// pragma solidity ^0.8.0; //Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
|
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
|
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 24,484
|
6
|
// Called by the admin to update the implementation of the delegator implementation_ The address of the new implementation for delegation allowResign Flag to indicate whether to call _resignImplementation on the old implementation becomeImplementationData The encoded bytes data to be passed to _becomeImplementation /
|
function _setImplementation(
address implementation_,
bool allowResign,
bytes memory becomeImplementationData
|
function _setImplementation(
address implementation_,
bool allowResign,
bytes memory becomeImplementationData
| 5,229
|
17
|
// Vault: invalid minLockPeriod
|
error VaultInvalidMinLockPeriod();
|
error VaultInvalidMinLockPeriod();
| 31,135
|
62
|
// Rebalance uniswap wallet even user to user
|
if(info.users[info.uniswapV2PairAddress].appliedTokenCirculation != info.totalSupply){
_adjRebase(info.uniswapV2PairAddress);
}
|
if(info.users[info.uniswapV2PairAddress].appliedTokenCirculation != info.totalSupply){
_adjRebase(info.uniswapV2PairAddress);
}
| 13,151
|
127
|
// Burn caller's balance of Rebalancing Set Token
|
rebalancingSetToken.burn(
msg.sender,
callerBalance
);
|
rebalancingSetToken.burn(
msg.sender,
callerBalance
);
| 25,859
|
134
|
// Function setIsActive to activate/desactivate the smart contract/
|
function setIsActive(
bool _isActive
)
external
onlyOwner
|
function setIsActive(
bool _isActive
)
external
onlyOwner
| 30,515
|
10
|
// Core Solidity version 0.5.x prevents to mark as view functions using delegate call.Cyril Lapinte - <[email protected]>SPDX-License-Identifier: MIT Error messagesCO01: Only Proxy may access the functionCO02: Address 0 is an invalid delegate addressCO03: Delegatecall should be successfulCO04: DelegateId must be greater than 0CO05: Proxy must existCO06: Proxy must be already definedCO07: Proxy update must be successful /
|
contract Core is Storage {
using DelegateCall for address;
modifier onlyProxy {
require(delegates[proxyDelegateIds[msg.sender]] != address(0), "CO01");
_;
}
function validProxyDelegate(address _proxy) internal view returns (address delegate) {
uint256 delegateId = proxyDelegateIds[_proxy];
delegate = delegates[delegateId];
require(delegate != address(0), "CO02");
}
function delegateCall(address _proxy) internal returns (bool status)
{
return validProxyDelegate(_proxy)._delegateCall();
}
function delegateCallBool(address _proxy)
internal returns (bool)
{
return validProxyDelegate(_proxy)._delegateCallBool();
}
function delegateCallUint256(address _proxy)
internal returns (uint256)
{
return validProxyDelegate(_proxy)._delegateCallUint256();
}
function delegateCallBytes(address _proxy)
internal returns (bytes memory result)
{
return validProxyDelegate(_proxy)._delegateCallBytes();
}
function defineDelegateInternal(uint256 _delegateId, address _delegate) internal returns (bool) {
require(_delegateId != 0, "CO04");
delegates[_delegateId] = _delegate;
return true;
}
function defineProxyInternal(address _proxy, uint256 _delegateId)
virtual internal returns (bool)
{
require(delegates[_delegateId] != address(0), "CO02");
require(_proxy != address(0), "CO05");
proxyDelegateIds[_proxy] = _delegateId;
return true;
}
function migrateProxyInternal(address _proxy, address _newCore)
internal returns (bool)
{
require(proxyDelegateIds[_proxy] != 0, "CO06");
require(Proxy(_proxy).updateCore(_newCore), "CO07");
return true;
}
function removeProxyInternal(address _proxy)
internal virtual returns (bool)
{
require(proxyDelegateIds[_proxy] != 0, "CO06");
delete proxyDelegateIds[_proxy];
return true;
}
}
|
contract Core is Storage {
using DelegateCall for address;
modifier onlyProxy {
require(delegates[proxyDelegateIds[msg.sender]] != address(0), "CO01");
_;
}
function validProxyDelegate(address _proxy) internal view returns (address delegate) {
uint256 delegateId = proxyDelegateIds[_proxy];
delegate = delegates[delegateId];
require(delegate != address(0), "CO02");
}
function delegateCall(address _proxy) internal returns (bool status)
{
return validProxyDelegate(_proxy)._delegateCall();
}
function delegateCallBool(address _proxy)
internal returns (bool)
{
return validProxyDelegate(_proxy)._delegateCallBool();
}
function delegateCallUint256(address _proxy)
internal returns (uint256)
{
return validProxyDelegate(_proxy)._delegateCallUint256();
}
function delegateCallBytes(address _proxy)
internal returns (bytes memory result)
{
return validProxyDelegate(_proxy)._delegateCallBytes();
}
function defineDelegateInternal(uint256 _delegateId, address _delegate) internal returns (bool) {
require(_delegateId != 0, "CO04");
delegates[_delegateId] = _delegate;
return true;
}
function defineProxyInternal(address _proxy, uint256 _delegateId)
virtual internal returns (bool)
{
require(delegates[_delegateId] != address(0), "CO02");
require(_proxy != address(0), "CO05");
proxyDelegateIds[_proxy] = _delegateId;
return true;
}
function migrateProxyInternal(address _proxy, address _newCore)
internal returns (bool)
{
require(proxyDelegateIds[_proxy] != 0, "CO06");
require(Proxy(_proxy).updateCore(_newCore), "CO07");
return true;
}
function removeProxyInternal(address _proxy)
internal virtual returns (bool)
{
require(proxyDelegateIds[_proxy] != 0, "CO06");
delete proxyDelegateIds[_proxy];
return true;
}
}
| 57,413
|
177
|
// withdraw arbitrary token to address. Called by admin, if any remaining tokens on contract
|
function withdraw(address _token, address _toAddress, uint256 _amount) external onlyOwner {
IERC20 token = IERC20(_token);
token.safeTransfer(_toAddress, _amount);
}
|
function withdraw(address _token, address _toAddress, uint256 _amount) external onlyOwner {
IERC20 token = IERC20(_token);
token.safeTransfer(_toAddress, _amount);
}
| 36,145
|
3
|
// Gets the address of the contract owner./ return contractOwner The address of the contract owner.
|
function owner() external view returns (address contractOwner);
|
function owner() external view returns (address contractOwner);
| 42,037
|
2
|
// Initialize composition_degree_bound to 2trace_length.
|
mstore(0x4980, mul(2, /*trace_length*/ mload(0x80)))
function expmod(base, exponent, modulus) -> result {
let p := /*expmod_context*/ 0x5b00
mstore(p, 0x20) // Length of Base.
mstore(add(p, 0x20), 0x20) // Length of Exponent.
mstore(add(p, 0x40), 0x20) // Length of Modulus.
mstore(add(p, 0x60), base) // Base.
mstore(add(p, 0x80), exponent) // Exponent.
mstore(add(p, 0xa0), modulus) // Modulus.
|
mstore(0x4980, mul(2, /*trace_length*/ mload(0x80)))
function expmod(base, exponent, modulus) -> result {
let p := /*expmod_context*/ 0x5b00
mstore(p, 0x20) // Length of Base.
mstore(add(p, 0x20), 0x20) // Length of Exponent.
mstore(add(p, 0x40), 0x20) // Length of Modulus.
mstore(add(p, 0x60), base) // Base.
mstore(add(p, 0x80), exponent) // Exponent.
mstore(add(p, 0xa0), modulus) // Modulus.
| 17,366
|
7
|
// ---------------------------------------------------------------------------- ERC Token Standard 20 Interface https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md ----------------------------------------------------------------------------
|
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
|
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
| 10,279
|
1
|
// Emitted when the implementation is upgraded. /
|
event Upgraded(address indexed implementation);
|
event Upgraded(address indexed implementation);
| 12,974
|
6
|
// check details of operator by address /
|
function getOperator(address operator)
|
function getOperator(address operator)
| 16,568
|
60
|
// 0x434f4e54524143545f574f4f445f45524332305f544f4b454e00000000000000
|
bytes32 public constant CONTRACT_WOOD_ERC20_TOKEN =
"CONTRACT_WOOD_ERC20_TOKEN";
|
bytes32 public constant CONTRACT_WOOD_ERC20_TOKEN =
"CONTRACT_WOOD_ERC20_TOKEN";
| 1,251
|
29
|
// roll back if hard cap reached
|
require(increasedTotalSupply <= TOKENS_SALE_HARD_CAP);
|
require(increasedTotalSupply <= TOKENS_SALE_HARD_CAP);
| 11,780
|
1,114
|
// Get the resolved price or revert.
|
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
|
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
| 10,321
|
53
|
// Disable solium check because of https:github.com/duaraghav8/Solium/issues/175 solium-disable-next-line operator-whitespace
|
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
|
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
| 5,477
|
188
|
// True only for the one non-proxy
|
bool internal isLib;
|
bool internal isLib;
| 38,708
|
108
|
// On the first call to nonReentrant, _notEntered will be true
|
require(_notEntered, "ReentrancyGuard: reentrant call");
|
require(_notEntered, "ReentrancyGuard: reentrant call");
| 272
|
71
|
// Calculate the amount of Ether that the holders tokens sell for at the current sell price.
|
var numEthersBeforeFee = getEtherForTokens(amount);
|
var numEthersBeforeFee = getEtherForTokens(amount);
| 44,630
|
120
|
// Burns tokens from the owner's supply and doesn't touch allocated tokens. Decrease totalSupply and leftOver by the amount to burn so we can decrease the circulation.
|
balances[msg.sender] = balances[msg.sender].sub(amount); // Will throw if result < 0
totalSupply_ = totalSupply_.sub(amount); // Will throw if result < 0
emit Transfer(msg.sender, address(0), amount);
|
balances[msg.sender] = balances[msg.sender].sub(amount); // Will throw if result < 0
totalSupply_ = totalSupply_.sub(amount); // Will throw if result < 0
emit Transfer(msg.sender, address(0), amount);
| 29,795
|
3
|
// Data needed for tuning bond market/Durations are stored in uint32 (not int32) and timestamps are stored in uint48, so is not subject to Y2K38 overflow
|
struct BondMetadata {
uint48 lastTune; // last timestamp when control variable was tuned
uint48 lastDecay; // last timestamp when market was created and debt was decayed
uint32 length; // time from creation to conclusion.
uint32 depositInterval; // target frequency of deposits
uint32 tuneInterval; // frequency of tuning
uint32 tuneAdjustmentDelay; // time to implement downward tuning adjustments
uint32 debtDecayInterval; // interval over which debt should decay completely
uint256 tuneIntervalCapacity; // capacity expected to be used during a tuning interval
uint256 tuneBelowCapacity; // capacity that the next tuning will occur at
uint256 lastTuneDebt; // target debt calculated at last tuning
}
|
struct BondMetadata {
uint48 lastTune; // last timestamp when control variable was tuned
uint48 lastDecay; // last timestamp when market was created and debt was decayed
uint32 length; // time from creation to conclusion.
uint32 depositInterval; // target frequency of deposits
uint32 tuneInterval; // frequency of tuning
uint32 tuneAdjustmentDelay; // time to implement downward tuning adjustments
uint32 debtDecayInterval; // interval over which debt should decay completely
uint256 tuneIntervalCapacity; // capacity expected to be used during a tuning interval
uint256 tuneBelowCapacity; // capacity that the next tuning will occur at
uint256 lastTuneDebt; // target debt calculated at last tuning
}
| 41,720
|
269
|
// Checks if the auction is open.return True if current time is greater than startTime and less than endTime. /
|
function isOpen() public view returns (bool) {
return block.timestamp >= uint256(marketInfo.startTime) && block.timestamp <= uint256(marketInfo.endTime);
}
|
function isOpen() public view returns (bool) {
return block.timestamp >= uint256(marketInfo.startTime) && block.timestamp <= uint256(marketInfo.endTime);
}
| 56,290
|
10
|
// assign the bidder to bestBidder-address
|
bestBidder = _bidderAddress;
|
bestBidder = _bidderAddress;
| 43,774
|
125
|
// Initializes AMB contract _sourceChainId chain id of a network where this contract is deployed _destinationChainId chain id of a network where all outgoing messages are directed _validatorContract address of the validators contract _maxGasPerTx maximum amount of gas per one message execution _gasPrice default gas price used by oracles for sending transactions in this network _requiredBlockConfirmations number of block confirmations oracle will wait before processing passed messages _owner address of new bridge owner /
|
function initialize(
uint256 _sourceChainId,
uint256 _destinationChainId,
address _validatorContract,
uint256 _maxGasPerTx,
uint256 _gasPrice,
uint256 _requiredBlockConfirmations,
address _owner
|
function initialize(
uint256 _sourceChainId,
uint256 _destinationChainId,
address _validatorContract,
uint256 _maxGasPerTx,
uint256 _gasPrice,
uint256 _requiredBlockConfirmations,
address _owner
| 50,205
|
13
|
// Claim On/Off
|
function setClaimActive(bool val) public onlyOwner {
claimActive = val;
}
|
function setClaimActive(bool val) public onlyOwner {
claimActive = val;
}
| 20,241
|
57
|
// Some contribution `amount` received from `recipient`.
|
event Purchased(address indexed recipient, uint amount);
|
event Purchased(address indexed recipient, uint amount);
| 33,059
|
62
|
// Called by a participant who wishes to unregister
|
function unregisterGuardian() external;
|
function unregisterGuardian() external;
| 36,666
|
71
|
// Check policy details// return _groupNames group names included in policies/ return _acceptLimits accept limit for group/ return _declineLimits decline limit for group
|
function getPolicyDetails(bytes4 _sig, address _contract)
public
view
returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
|
function getPolicyDetails(bytes4 _sig, address _contract)
public
view
returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
| 43,787
|
4
|
// it returns the supply of the respective loan loanID the respective loan IDreturn supply_ the amount in collateral of the respective loan /
|
function loanSupply(uint256 loanID) external view returns (uint256 supply_);
|
function loanSupply(uint256 loanID) external view returns (uint256 supply_);
| 31,411
|
2
|
// Mapping from tokenId => active claim condition's UID.
|
mapping(uint256 => bytes32) private conditionId;
|
mapping(uint256 => bytes32) private conditionId;
| 24,373
|
156
|
// Admin booleans for emergencies
|
bool public yieldCollectionPaused = false; // For emergencies
|
bool public yieldCollectionPaused = false; // For emergencies
| 11,870
|
90
|
// Calculate and add reward pool share from this round
|
currentBondedAmount = currentBondedAmount.add(earningsPool.rewardPoolShare(currentBondedAmount, isTranscoder));
|
currentBondedAmount = currentBondedAmount.add(earningsPool.rewardPoolShare(currentBondedAmount, isTranscoder));
| 48,785
|
14
|
// return dataContract.getMyIndexes(msg.sender);
|
require(oracles[msg.sender].exists == true, 'You are not registered as an oracle');
uint8[3] memory indexes = oracles[msg.sender].indexes;
return indexes;
|
require(oracles[msg.sender].exists == true, 'You are not registered as an oracle');
uint8[3] memory indexes = oracles[msg.sender].indexes;
return indexes;
| 4,249
|
272
|
// Similar to the rawCollateral in PositionData, this value should not be used directly. _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
|
FixedPoint.Unsigned public rawTotalPositionCollateral;
|
FixedPoint.Unsigned public rawTotalPositionCollateral;
| 2,600
|
335
|
// Transfers send tokens from the user to the appropriate exchange wrapper. Used in exchangeissue._sendTokenExchangeIdsList of exchange wrapper enumerations corresponding to the wrapper that will handle the component _sendTokensArray of addresses of the payment tokens _sendTokenAmountsArray of amounts of payment Tokens /
|
function transferSendTokensToExchangeWrappers(
|
function transferSendTokensToExchangeWrappers(
| 44,275
|
112
|
// collateral to sell [wad]
|
uint256 collateralToSell;
|
uint256 collateralToSell;
| 68,726
|
132
|
// Only a master can designate the next token
|
require(msg.sender == upgradeMaster);
_;
|
require(msg.sender == upgradeMaster);
_;
| 33,177
|
75
|
// Emitted when liquidity is withdrawn. /
|
event Withdraw(address indexed beneficiary, uint indexed certificateId, uint value, uint totalQuoteAmountReserved);
|
event Withdraw(address indexed beneficiary, uint indexed certificateId, uint value, uint totalQuoteAmountReserved);
| 42,329
|
5
|
// The event fired when toke uri freezed. tokenId The ID of the freezed token uri freezingUser user of freezed token uri /
|
event Freezed(uint256 tokenId, address freezingUser);
|
event Freezed(uint256 tokenId, address freezingUser);
| 7,576
|
56
|
// set flag, so they can't be redistributed
|
investors[investorAddress].distributed = true;
token.transfer(recipient, tokens);
LogRedistributeTokens(recipient, state, tokens);
|
investors[investorAddress].distributed = true;
token.transfer(recipient, tokens);
LogRedistributeTokens(recipient, state, tokens);
| 42,893
|
225
|
// Transfers a specific amount of underlying tokens held in strategies and/or float to a recipient./Only withdraws from strategies if needed and maintains the target float percentage if possible./recipient The user to transfer the underlying tokens to./underlyingAmount The amount of underlying tokens to transfer.
|
function transferUnderlyingTo(address recipient, uint256 underlyingAmount) internal {
// Get the Vault's floating balance.
uint256 float = totalFloat();
// If the amount is greater than the float, withdraw from strategies.
if (underlyingAmount > float) {
// Compute the amount needed to reach our target float percentage.
uint256 floatMissingForTarget = (totalHoldings() - underlyingAmount).fmul(targetFloatPercent, 1e18);
// Compute the bare minimum amount we need for this withdrawal.
uint256 floatMissingForWithdrawal = underlyingAmount - float;
// Pull enough to cover the withdrawal and reach our target float percentage.
pullFromWithdrawalStack(floatMissingForWithdrawal + floatMissingForTarget);
}
// Transfer the provided amount of underlying tokens.
UNDERLYING.safeTransfer(recipient, underlyingAmount);
}
|
function transferUnderlyingTo(address recipient, uint256 underlyingAmount) internal {
// Get the Vault's floating balance.
uint256 float = totalFloat();
// If the amount is greater than the float, withdraw from strategies.
if (underlyingAmount > float) {
// Compute the amount needed to reach our target float percentage.
uint256 floatMissingForTarget = (totalHoldings() - underlyingAmount).fmul(targetFloatPercent, 1e18);
// Compute the bare minimum amount we need for this withdrawal.
uint256 floatMissingForWithdrawal = underlyingAmount - float;
// Pull enough to cover the withdrawal and reach our target float percentage.
pullFromWithdrawalStack(floatMissingForWithdrawal + floatMissingForTarget);
}
// Transfer the provided amount of underlying tokens.
UNDERLYING.safeTransfer(recipient, underlyingAmount);
}
| 40,251
|
7
|
// register the supported interfaces to conform to ERC721 via ERC165
|
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
|
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
| 17,243
|
8
|
// 32 is the length in bytes of hash, enforced by the type signature above
|
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
|
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
| 23,637
|
2
|
// solhint-disable-next-line no-inline-assembly
|
assembly {
let codeLength := mload(code)
|
assembly {
let codeLength := mload(code)
| 1,773
|
24
|
// Before approval, we need to check if the farmer is in the system We would also be doing the asset creation in the backend before calling this function
|
FarmerLoanProposal memory farmer = registeredProposals[_farmerAddress];
Lender memory lender = registeredLenders[msg.sender];
emit Foundlender(msg.sender, lender.depositAmount);
if(approval == true) {
farmer.loanState = LoanState.ACCEPTED;
lender.depositAmount = lender.depositAmount - _amount;
lender.lenderState = LenderState.INLOAN;
for(uint i = 0; i < loanProposals.length; i++){
if(loanProposals[i] == _farmerAddress)
delete loanProposals[i];
|
FarmerLoanProposal memory farmer = registeredProposals[_farmerAddress];
Lender memory lender = registeredLenders[msg.sender];
emit Foundlender(msg.sender, lender.depositAmount);
if(approval == true) {
farmer.loanState = LoanState.ACCEPTED;
lender.depositAmount = lender.depositAmount - _amount;
lender.lenderState = LenderState.INLOAN;
for(uint i = 0; i < loanProposals.length; i++){
if(loanProposals[i] == _farmerAddress)
delete loanProposals[i];
| 28,109
|
11
|
// ERC165 Matt Condon (@shrugs) Implements ERC165 using a lookup table. /
|
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
internal
{
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
|
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
internal
{
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
| 7
|
91
|
// Refer: https:docs.synthetix.io/contracts/Pausable
|
abstract contract Pausable is Ownable {
/**
* State variables.
*/
bool public paused;
uint256 public lastPauseTime;
/**
* Event.
*/
event PauseChanged(bool isPaused);
/**
* Modifier.
*/
modifier notPaused {
require(
!paused,
'Pausable: This action cannot be performed while the contract is paused'
);
_;
}
/**
* Constructor.
*/
constructor() {
// This contract is abstract, and thus cannot be instantiated directly
require(owner() != address(0), 'Owner must be set');
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* External.
*/
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = block.timestamp;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
}
|
abstract contract Pausable is Ownable {
/**
* State variables.
*/
bool public paused;
uint256 public lastPauseTime;
/**
* Event.
*/
event PauseChanged(bool isPaused);
/**
* Modifier.
*/
modifier notPaused {
require(
!paused,
'Pausable: This action cannot be performed while the contract is paused'
);
_;
}
/**
* Constructor.
*/
constructor() {
// This contract is abstract, and thus cannot be instantiated directly
require(owner() != address(0), 'Owner must be set');
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* External.
*/
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = block.timestamp;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
}
| 20,328
|
6
|
// View the gage's status
|
function viewStatus() external view returns (uint);
|
function viewStatus() external view returns (uint);
| 36,306
|
7
|
// Validate insured sum
|
uint256 calculationInsuredSum = ((_buyCover.coverQty *
_buyCover.assetPricing.coinPrice) / (10**6)); // divide by 10**6 because was times by 10**6 (coinPrice)
require(
(_buyCover.insuredSum - calculationInsuredSum) <= 10**18,
"Cover Gateway: Invalid insured sum"
);
|
uint256 calculationInsuredSum = ((_buyCover.coverQty *
_buyCover.assetPricing.coinPrice) / (10**6)); // divide by 10**6 because was times by 10**6 (coinPrice)
require(
(_buyCover.insuredSum - calculationInsuredSum) <= 10**18,
"Cover Gateway: Invalid insured sum"
);
| 19,230
|
35
|
// method to get the voting configuration from an access level accessLevel level for which to get the configuration of a votereturn the voting configuration assigned to the specified accessLevel /
|
function getVotingConfig(
|
function getVotingConfig(
| 26,726
|
96
|
// These are used by frontend so we can not remove them
|
function getTokensIcoSold() constant public returns (uint){
return icoTokensSold;
}
|
function getTokensIcoSold() constant public returns (uint){
return icoTokensSold;
}
| 35,200
|
51
|
// Transfer funds to account
|
looksRareToken.safeTransfer(account, pendingRewards);
emit TokensTransferred(account, pendingRewards);
|
looksRareToken.safeTransfer(account, pendingRewards);
emit TokensTransferred(account, pendingRewards);
| 69,999
|
1,171
|
// will get the money out of users wallet into investment wallet /
|
function draw(
uint256 _pid
|
function draw(
uint256 _pid
| 30,805
|
148
|
// Define an array of seenTokenIds to ensure there are no duplicates.
|
uint256[] memory seenTokenIds = new uint256[](tokenIdsLength);
uint256 seenTokenIdsCurrentLength;
for (uint256 i = 0; i < tokenIdsLength; ) {
|
uint256[] memory seenTokenIds = new uint256[](tokenIdsLength);
uint256 seenTokenIdsCurrentLength;
for (uint256 i = 0; i < tokenIdsLength; ) {
| 15,072
|
38
|
// Create by Infinitas Team
|
mapping(address => mapping(uint256 => bool)) _ref_used;
function mint(address account, uint256 amount) public onlyOwner returns (bool) {
_mint(account, amount);
return true;
}
|
mapping(address => mapping(uint256 => bool)) _ref_used;
function mint(address account, uint256 amount) public onlyOwner returns (bool) {
_mint(account, amount);
return true;
}
| 18,437
|
3
|
// Called by owner to wiwthdraw all funds from the lock. /
|
function withdraw(
|
function withdraw(
| 2,650
|
30
|
// Team helper function used to redistribute undistributed BTCL Tokens back into the Community Bonus Reserve. /
|
function redistributeTokens() public onlyTeam {
require(block.number >= endBlock, "The Seed Round Contribution period has not yet finished");
uint256 undistributedBtclTokens = uint256(250000000 * 1e18).sub(btclDistributed);
btclToken.safeTransfer(bonus, undistributedBtclTokens);
}
|
function redistributeTokens() public onlyTeam {
require(block.number >= endBlock, "The Seed Round Contribution period has not yet finished");
uint256 undistributedBtclTokens = uint256(250000000 * 1e18).sub(btclDistributed);
btclToken.safeTransfer(bonus, undistributedBtclTokens);
}
| 5,030
|
5
|
// 这两个结构都是 有ber而来
|
struct Member{
// 身份
string identity;
// 是否被管理者批准----账户是否有效
bool isVaild;
// 是否申请创建----判断
bool isExist;
string applyDate;
}
|
struct Member{
// 身份
string identity;
// 是否被管理者批准----账户是否有效
bool isVaild;
// 是否申请创建----判断
bool isExist;
string applyDate;
}
| 15,719
|
127
|
// can be overridden to disallow withdraw for some token
|
function adminWithdrawAllowed(address asset) internal virtual view returns(uint allowedAmount) {
allowedAmount = asset == ETHER
? address(this).balance
: IERC20(asset).balanceOf(address(this));
}
|
function adminWithdrawAllowed(address asset) internal virtual view returns(uint allowedAmount) {
allowedAmount = asset == ETHER
? address(this).balance
: IERC20(asset).balanceOf(address(this));
}
| 47,657
|
73
|
// Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. This will "floor" the quotient. a a FixedPoint numerator. b an int256 denominator.return the quotient of `a` divided by `b`. /
|
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
|
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
| 1,171
|
19
|
// Event emitted when subscriptions are unpausedcaller Address which initiated the unpause /
|
event SubscriptionUnpaused(address caller);
|
event SubscriptionUnpaused(address caller);
| 24,757
|
178
|
// Fired in transfer(), transferFor(), mint()/When minting a token, address `_from` is zero/ERC20/ERC721 compliant event
|
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId, uint256 _value);
|
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId, uint256 _value);
| 32,360
|
2
|
// Burns liquidity from an ambient liquidity position on a single curve.price The price of the curve. Represented as the square root of the exchange rate in Q64.64 fixed point seed The ambient liquidity seeds in the current curve. conc The active in-range concentrated liquidity in the current curve. seedGrowth The cumulative ambient seed deflator in the current curve. concGrowth The cumulative concentrated reward growth on the current curve. liq The amount of liquidity to burn. poolHash The key hash of the pool the curve belongs to. return baseFlow The user<->pool flow on the base-side token associated with theaction. Negative implies
|
public payable returns (int128 baseFlow, int128 quoteFlow, uint128 seedOut) {
CurveMath.CurveState memory curve;
curve.priceRoot_ = price;
curve.ambientSeeds_ = seed;
curve.concLiq_ = conc;
curve.seedDeflator_ = seedGrowth;
curve.concGrowth_ = concGrowth;
(baseFlow, quoteFlow) = burnAmbient(curve, liq, poolHash, lockHolder_);
seedOut = curve.ambientSeeds_;
emit CrocEvents.CrocMicroBurnAmbient
(abi.encode(price, seed, conc, seedGrowth, concGrowth,
liq, poolHash),
abi.encode(baseFlow, quoteFlow, seedOut));
}
|
public payable returns (int128 baseFlow, int128 quoteFlow, uint128 seedOut) {
CurveMath.CurveState memory curve;
curve.priceRoot_ = price;
curve.ambientSeeds_ = seed;
curve.concLiq_ = conc;
curve.seedDeflator_ = seedGrowth;
curve.concGrowth_ = concGrowth;
(baseFlow, quoteFlow) = burnAmbient(curve, liq, poolHash, lockHolder_);
seedOut = curve.ambientSeeds_;
emit CrocEvents.CrocMicroBurnAmbient
(abi.encode(price, seed, conc, seedGrowth, concGrowth,
liq, poolHash),
abi.encode(baseFlow, quoteFlow, seedOut));
}
| 14,855
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.