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 |
|---|---|---|---|---|
140 | // Emitted when a new Deposit is registered. / | event NewDepositRegistered(address allocator, address token, uint256 id);
| event NewDepositRegistered(address allocator, address token, uint256 id);
| 63,714 |
74 | // Claim any stuck eth/tokens from contract / | function claimStuckTokens(address _token) external onlyOwner {
if(_token == address(0x0)) {
payable(owner()).transfer(address(this).balance);
return;
}
IERC20 erc20token = IERC20(_token);
uint256 balance = erc20token.balanceOf(address(this));
erc20token.transfer(owner(), balance);
}
| function claimStuckTokens(address _token) external onlyOwner {
if(_token == address(0x0)) {
payable(owner()).transfer(address(this).balance);
return;
}
IERC20 erc20token = IERC20(_token);
uint256 balance = erc20token.balanceOf(address(this));
erc20token.transfer(owner(), balance);
}
| 39,607 |
80 | // Emitted when stakingPool address is changed pool new stakingPool address / | event StakingPoolChanged(IStakingPool pool);
| event StakingPoolChanged(IStakingPool pool);
| 33,232 |
32 | // ------------------------------------------------------------------------ Stakers can un stake the staked tokens using this functiontokens the number of tokens to withdraw ------------------------------------------------------------------------ | function WITHDRAW(uint256 tokens) external {
require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw");
uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10);
// add pending rewards to remainder to be claimed by user later, if there is any existing stake
uint256 owing = pendingReward(msg.sender);
stakers[msg.sender].remainder += owing;
require(IERC20(XFIM).transfer(msg.sender, tokens.sub(_unstakingFee)), "Error in un-staking tokens");
stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens);
stakers[msg.sender].lastDividends = owing;
stakers[msg.sender].fromTotalDividend= totalDividends;
stakers[msg.sender].round = round;
totalStakes = totalStakes.sub(tokens);
if(totalStakes > 0)
// distribute the un staking fee accumulated after updating the user's stake
_addPayout(_unstakingFee);
emit UNSTAKED(msg.sender, tokens.sub(_unstakingFee), _unstakingFee);
}
| function WITHDRAW(uint256 tokens) external {
require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw");
uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10);
// add pending rewards to remainder to be claimed by user later, if there is any existing stake
uint256 owing = pendingReward(msg.sender);
stakers[msg.sender].remainder += owing;
require(IERC20(XFIM).transfer(msg.sender, tokens.sub(_unstakingFee)), "Error in un-staking tokens");
stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens);
stakers[msg.sender].lastDividends = owing;
stakers[msg.sender].fromTotalDividend= totalDividends;
stakers[msg.sender].round = round;
totalStakes = totalStakes.sub(tokens);
if(totalStakes > 0)
// distribute the un staking fee accumulated after updating the user's stake
_addPayout(_unstakingFee);
emit UNSTAKED(msg.sender, tokens.sub(_unstakingFee), _unstakingFee);
}
| 47,061 |
9 | // Withdraws funds and sends them back to the vault. Can only be called by the vault. _amount must be valid and security fee is deducted up-front. / | function withdraw(uint256 _amount) external override {
require(msg.sender == vault, "!vault");
require(_amount != 0, "invalid amount");
require(_amount <= balanceOf(), "invalid amount");
uint256 withdrawFee = (_amount * securityFee) / PERCENT_DIVISOR;
_amount -= withdrawFee;
_withdraw(_amount);
}
| function withdraw(uint256 _amount) external override {
require(msg.sender == vault, "!vault");
require(_amount != 0, "invalid amount");
require(_amount <= balanceOf(), "invalid amount");
uint256 withdrawFee = (_amount * securityFee) / PERCENT_DIVISOR;
_amount -= withdrawFee;
_withdraw(_amount);
}
| 17,178 |
61 | // this call is as generic as any transaction. It sends all gas and can do everything a transaction can do. It can be used to reenter the DAO. The `p.proposalPassed` variable prevents the call fromreaching this line again | (bool success, ) = p.recipient.call.value(msg.value)(_transactionData);
require(success,"big fuckup");
| (bool success, ) = p.recipient.call.value(msg.value)(_transactionData);
require(success,"big fuckup");
| 36,597 |
66 | // get sell price by id from 'database' id, unique id of profiles / | function getSellPriceById(uint32 id) public view returns (uint256){
for (uint i = 0; i < nftProfiles.length; i++){
if (nftProfiles[i].id == id){
return nftProfiles[i].sell_price;
}
}
return BAD_PRICE;
}
| function getSellPriceById(uint32 id) public view returns (uint256){
for (uint i = 0; i < nftProfiles.length; i++){
if (nftProfiles[i].id == id){
return nftProfiles[i].sell_price;
}
}
return BAD_PRICE;
}
| 1,292 |
10 | // Get the number of ERC20 contracts that token owns ERC20 tokens from/_tokenId The token that owns ERC20 tokens./ return uint256 The number of ERC20 contracts | function totalERC20Contracts(uint256 _tokenId)
external
view
returns (uint256);
| function totalERC20Contracts(uint256 _tokenId)
external
view
returns (uint256);
| 17,096 |
26 | // Returns the integer division of two unsigned integers. Reverts with custom message ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements:- The divisor cannot be zero. / | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| 1,157 |
17 | // Emitted when Series contract is deployed deployer Contract deployer contractAddress Address of contract that was deployed / | event SeriesDeployed(address indexed deployer, address indexed contractAddress);
| event SeriesDeployed(address indexed deployer, address indexed contractAddress);
| 43,092 |
0 | // Structure to store the details of an NFT | struct NFT {
string name;
string description;
uint256 price;
string placeholderImage;
string image;
uint256 revealDate;
bool revealed;
address owner;
}
| struct NFT {
string name;
string description;
uint256 price;
string placeholderImage;
string image;
uint256 revealDate;
bool revealed;
address owner;
}
| 7,770 |
65 | // 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)
);
| 49,485 |
17 | // accumulated protocol fees in token0/token1 units | struct ProtocolFees {
uint128 token0;
uint128 token1;
}
| struct ProtocolFees {
uint128 token0;
uint128 token1;
}
| 6,323 |
25 | // optimistically set before to the newest observation | beforeOrAt = self[index];
| beforeOrAt = self[index];
| 23,608 |
31 | // Update reward variables for all pools. Be careful of gas spending! | function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
| function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
| 893 |
87 | // abondDebt() + b_.gain | uint256 newDebt = abondDebt().add(b_.gain);
| uint256 newDebt = abondDebt().add(b_.gain);
| 57,237 |
55 | // stop burn at 250mil remaining | burn: 750000000 * 10 **_decimals,
| burn: 750000000 * 10 **_decimals,
| 15,682 |
91 | // Limit the transfer to 600 tokens for first 5 minutes | require(now > liquidityAddedAt + 6 minutes || amount <= 600e9, "You cannot transfer more than 600 tokens.");
| require(now > liquidityAddedAt + 6 minutes || amount <= 600e9, "You cannot transfer more than 600 tokens.");
| 10,577 |
67 | // Call router to pull NFTs If more than 1 NFT is being transfered, we can do a balance check instead of an ownership check, as pools are indifferent between NFTs from the same collection | if (numNFTs > 1) {
uint256 beforeBalance = _nft.balanceOf(_assetRecipient);
for (uint256 i = 0; i < numNFTs; ) {
router.pairTransferNFTFrom(
_nft,
routerCaller,
_assetRecipient,
nftIds[i],
pairVariant()
);
| if (numNFTs > 1) {
uint256 beforeBalance = _nft.balanceOf(_assetRecipient);
for (uint256 i = 0; i < numNFTs; ) {
router.pairTransferNFTFrom(
_nft,
routerCaller,
_assetRecipient,
nftIds[i],
pairVariant()
);
| 20,923 |
140 | // Destroys `_amount` tokens from `msg.sender`, reducing thetotal supply. / | function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
_moveDelegates(_delegates[msg.sender], address(0), _amount);
}
| function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
_moveDelegates(_delegates[msg.sender], address(0), _amount);
}
| 23,120 |
13 | // data struct hold each ticket info | struct Ticket {
uint rId; // round identity
address player; // the buyer
uint btime; // buy time
uint[] numbers; // buy numbers, idx 0,1,2,3,4 are red balls, idx 5 are blue balls
bool joinBonus; // join bonus ?
bool useGoldKey; // use gold key ?
}
| struct Ticket {
uint rId; // round identity
address player; // the buyer
uint btime; // buy time
uint[] numbers; // buy numbers, idx 0,1,2,3,4 are red balls, idx 5 are blue balls
bool joinBonus; // join bonus ?
bool useGoldKey; // use gold key ?
}
| 29,852 |
57 | // Allocate tokens to the users_owners The owners list of the token_values The value list of the token (value = _value10decimals) | function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner {
require(allocateEndTime > now);
require(_owners.length == _values.length);
for(uint256 i = 0; i < _owners.length ; i++){
address to = _owners[i];
uint256 value = _values[i] * 10 ** uint256(decimals);
require(totalSupply + value > totalSupply && balanceOf[to] + value > balanceOf[to]) ;
totalSupply += value;
balanceOf[to] += value;
}
}
| function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner {
require(allocateEndTime > now);
require(_owners.length == _values.length);
for(uint256 i = 0; i < _owners.length ; i++){
address to = _owners[i];
uint256 value = _values[i] * 10 ** uint256(decimals);
require(totalSupply + value > totalSupply && balanceOf[to] + value > balanceOf[to]) ;
totalSupply += value;
balanceOf[to] += value;
}
}
| 36,984 |
24 | // Add the market to the borrower's "assets in" for liquidity calculations pToken The market to enter borrower The address of the account to modifyreturn Success indicator for whether the market was entered / | function addToMarketInternal(IPToken pToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(pToken)];
// market is not listed, cannot join
if (!marketToJoin.isListed) {
return Error.MARKET_NOT_LISTED;
}
// already joined
if (marketToJoin.accountMembership[borrower] == true) {
return Error.NO_ERROR;
}
// no space, cannot join
if (accountAssets[borrower].length >= maxAssets) {
return Error.TOO_MANY_ASSETS;
}
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(pToken);
emit MarketEntered(pToken, borrower);
return Error.NO_ERROR;
}
| function addToMarketInternal(IPToken pToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(pToken)];
// market is not listed, cannot join
if (!marketToJoin.isListed) {
return Error.MARKET_NOT_LISTED;
}
// already joined
if (marketToJoin.accountMembership[borrower] == true) {
return Error.NO_ERROR;
}
// no space, cannot join
if (accountAssets[borrower].length >= maxAssets) {
return Error.TOO_MANY_ASSETS;
}
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(pToken);
emit MarketEntered(pToken, borrower);
return Error.NO_ERROR;
}
| 40,889 |
12 | // transfer from the owner balance to another address | function transfer(address to, uint tokens) public returns (bool success){
require(balances[msg.sender] >= tokens && tokens > 0);
balances[to] += tokens;
balances[msg.sender] -= tokens;
emit Transfer(msg.sender, to, tokens);
return true;
}
| function transfer(address to, uint tokens) public returns (bool success){
require(balances[msg.sender] >= tokens && tokens > 0);
balances[to] += tokens;
balances[msg.sender] -= tokens;
emit Transfer(msg.sender, to, tokens);
return true;
}
| 66,354 |
683 | // Covers the case where users borrowed tokens before the market's borrow state index was set. Rewards the user with COMP accrued from the start of when borrower rewards were first set for the market. | borrowerIndex = compInitialIndex;
| borrowerIndex = compInitialIndex;
| 21,318 |
41 | // add x^17(33! / 17!) | xi = (xi * _x) >> _precision;
res += xi * 0x00000000000004985f67696bf748000;
| xi = (xi * _x) >> _precision;
res += xi * 0x00000000000004985f67696bf748000;
| 31,255 |
58 | // Set max wallet | function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
require(
_maxWalletSize > 100000000000,
"Max wallet size needs to be larger than 1000 tokens of the total supply"
);
_maxWalletSize = maxWalletSize;
}
| function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
require(
_maxWalletSize > 100000000000,
"Max wallet size needs to be larger than 1000 tokens of the total supply"
);
_maxWalletSize = maxWalletSize;
}
| 6,386 |
13 | // market maker | function init(
uint hid,
uint side,
uint odds,
uint amount,
bytes32 offchain
)
public
| function init(
uint hid,
uint side,
uint odds,
uint amount,
bytes32 offchain
)
public
| 18,058 |
142 | // source token deposit amounts sourceToken => beneficiary => deposit amounts | mapping(address => mapping(address => uint256)) public depositAmounts;
| mapping(address => mapping(address => uint256)) public depositAmounts;
| 71,373 |
340 | // current ERC1155 implementation although this won't be used at the start | address internal _erc1155Implementation;
| address internal _erc1155Implementation;
| 44,388 |
17 | // ------------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account. The `spender` contract function `receiveApproval(...)` is then executed ------------------------------------------------------------------------ | function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
| function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
| 60,686 |
88 | // 351853194065269153664 | uint256 _eBTCResult = balanceOf(account).mul(_eBTCRewardPerTokenStored.sub(userRewardPerTokenPaid[_eBTC][account])).div(1e18).add(rewards[_eBTC][account]);
uint256 _eETHResult = balanceOf(account).mul(_eETHRewardPerTokenStored.sub(userRewardPerTokenPaid[_eETH][account])).div(1e18).add(rewards[_eETH][account]);
return (_eBTCResult, _eETHResult);
| uint256 _eBTCResult = balanceOf(account).mul(_eBTCRewardPerTokenStored.sub(userRewardPerTokenPaid[_eBTC][account])).div(1e18).add(rewards[_eBTC][account]);
uint256 _eETHResult = balanceOf(account).mul(_eETHRewardPerTokenStored.sub(userRewardPerTokenPaid[_eETH][account])).div(1e18).add(rewards[_eETH][account]);
return (_eBTCResult, _eETHResult);
| 10,736 |
137 | // First get the total weight delta | weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i],
gradualUpdate.endWeights[i]);
| weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i],
gradualUpdate.endWeights[i]);
| 6,651 |
128 | // Registers token transfer, minting and burning tokenId Token ID from Previous token owner, zero if this is a freshly minted token to New token owner, zero if the token is being burned Requirements:- the caller must be the Macabris contract / | function onTokenTransfer(uint tokenId, address from, address to) external {
require(msg.sender == address(macabris), "Caller must be the Macabris contract");
// If the payouts have ended, we don't need to track transfers anymore
if (hasEnded()) {
return;
}
// If token is already dead, nothing changes in terms of payouts
if (reaper.getTimeOfDeath(tokenId) != 0) {
return;
}
uint currentInterval = _getInterval(block.timestamp);
if (from == address(0)) {
// If the token is freshly minted, increase the total active token count for the period
intervals[currentInterval].activeTokenChange += 1;
} else {
// If the token is transfered, decrease the previous ownner's total for the current interval
individualIntervals[currentInterval][from] -= 1;
}
if (to == address(0)) {
// If the token is burned, decrease the total active token count for the period
intervals[currentInterval].activeTokenChange -= 1;
} else {
// If the token is transfered, add it to the receiver's total for the current interval
individualIntervals[currentInterval][to] += 1;
}
}
| function onTokenTransfer(uint tokenId, address from, address to) external {
require(msg.sender == address(macabris), "Caller must be the Macabris contract");
// If the payouts have ended, we don't need to track transfers anymore
if (hasEnded()) {
return;
}
// If token is already dead, nothing changes in terms of payouts
if (reaper.getTimeOfDeath(tokenId) != 0) {
return;
}
uint currentInterval = _getInterval(block.timestamp);
if (from == address(0)) {
// If the token is freshly minted, increase the total active token count for the period
intervals[currentInterval].activeTokenChange += 1;
} else {
// If the token is transfered, decrease the previous ownner's total for the current interval
individualIntervals[currentInterval][from] -= 1;
}
if (to == address(0)) {
// If the token is burned, decrease the total active token count for the period
intervals[currentInterval].activeTokenChange -= 1;
} else {
// If the token is transfered, add it to the receiver's total for the current interval
individualIntervals[currentInterval][to] += 1;
}
}
| 40,113 |
180 | // Represents a delegator's current state | struct Delegator {
uint256 bondedAmount; // The amount of bonded tokens
uint256 fees; // The amount of fees collected
address delegateAddress; // The address delegated to
uint256 delegatedAmount; // The amount of tokens delegated to the delegator
uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone
uint256 withdrawRoundDEPRECATED; // DEPRECATED - DO NOT USE
uint256 lastClaimRound; // The last round during which the delegator claimed its earnings
uint256 nextUnbondingLockId; // ID for the next unbonding lock created
mapping (uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock
| struct Delegator {
uint256 bondedAmount; // The amount of bonded tokens
uint256 fees; // The amount of fees collected
address delegateAddress; // The address delegated to
uint256 delegatedAmount; // The amount of tokens delegated to the delegator
uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone
uint256 withdrawRoundDEPRECATED; // DEPRECATED - DO NOT USE
uint256 lastClaimRound; // The last round during which the delegator claimed its earnings
uint256 nextUnbondingLockId; // ID for the next unbonding lock created
mapping (uint256 => UnbondingLock) unbondingLocks; // Mapping of unbonding lock ID => unbonding lock
| 43,434 |
50 | // canOf[user] -= amount; | return true;
| return true;
| 40,883 |
27 | // Function called by the sender after the challenge period has ended, in order to settle and delete the channel, in case the receiver has not closed the channel himself _receiver Server side of transfer _openBlockNumber The block number at which a channel between the sender and receiver was created / | function settle(address _receiver, uint256 _openBlockNumber) external {
bytes32 key = getKey(msg.sender, _receiver, _openBlockNumber);
// Make sure an uncooperativeClose has been initiated
require(closingRequests[key].settleBlockNumber > 0, 'challenge period has not been started');
// Make sure the challenge_period has ended
require(block.number > closingRequests[key].settleBlockNumber, 'challenge period still active');
settleChannel(msg.sender, _receiver, _openBlockNumber,
closingRequests[key].closingBalance
);
}
| function settle(address _receiver, uint256 _openBlockNumber) external {
bytes32 key = getKey(msg.sender, _receiver, _openBlockNumber);
// Make sure an uncooperativeClose has been initiated
require(closingRequests[key].settleBlockNumber > 0, 'challenge period has not been started');
// Make sure the challenge_period has ended
require(block.number > closingRequests[key].settleBlockNumber, 'challenge period still active');
settleChannel(msg.sender, _receiver, _openBlockNumber,
closingRequests[key].closingBalance
);
}
| 6,428 |
285 | // https:docs.synthetix.io/contracts/source/contracts/minimalproxyfactory | contract MinimalProxyFactory {
function _cloneAsMinimalProxy(address _base, string memory _revertMsg) internal returns (address clone) {
bytes memory createData = _generateMinimalProxyCreateData(_base);
assembly {
clone := create(
0, // no value
add(createData, 0x20), // data
55 // data is always 55 bytes (10 constructor + 45 code)
)
}
// If CREATE fails for some reason, address(0) is returned
require(clone != address(0), _revertMsg);
}
function _generateMinimalProxyCreateData(address _base) internal pure returns (bytes memory) {
return
abi.encodePacked(
//---- constructor -----
bytes10(0x3d602d80600a3d3981f3),
//---- proxy code -----
bytes10(0x363d3d373d3d3d363d73),
_base,
bytes15(0x5af43d82803e903d91602b57fd5bf3)
);
}
}
| contract MinimalProxyFactory {
function _cloneAsMinimalProxy(address _base, string memory _revertMsg) internal returns (address clone) {
bytes memory createData = _generateMinimalProxyCreateData(_base);
assembly {
clone := create(
0, // no value
add(createData, 0x20), // data
55 // data is always 55 bytes (10 constructor + 45 code)
)
}
// If CREATE fails for some reason, address(0) is returned
require(clone != address(0), _revertMsg);
}
function _generateMinimalProxyCreateData(address _base) internal pure returns (bytes memory) {
return
abi.encodePacked(
//---- constructor -----
bytes10(0x3d602d80600a3d3981f3),
//---- proxy code -----
bytes10(0x363d3d373d3d3d363d73),
_base,
bytes15(0x5af43d82803e903d91602b57fd5bf3)
);
}
}
| 38,112 |
6 | // Kyber Network interface | interface KyberNetworkInterface {
function maxGasPrice() public view returns(uint);
function getUserCapInWei(address user) public view returns(uint);
function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint);
function enabled() public view returns(bool);
function info(bytes32 id) public view returns(uint);
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view
returns (uint expectedRate, uint slippageRate);
function tradeWithHint(address trader, ERC20 src, uint srcAmount, ERC20 dest, address destAddress,
uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint);
}
| interface KyberNetworkInterface {
function maxGasPrice() public view returns(uint);
function getUserCapInWei(address user) public view returns(uint);
function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint);
function enabled() public view returns(bool);
function info(bytes32 id) public view returns(uint);
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view
returns (uint expectedRate, uint slippageRate);
function tradeWithHint(address trader, ERC20 src, uint srcAmount, ERC20 dest, address destAddress,
uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint);
}
| 20,743 |
4 | // Append observer _event Event type _observer Observer address / | function addObserver(uint _event, Observer _observer) internal
| function addObserver(uint _event, Observer _observer) internal
| 20,715 |
118 | // conduct the transfer | _tokenTransfer(sender, recipient, amountOfTokens);
| _tokenTransfer(sender, recipient, amountOfTokens);
| 34,076 |
29 | // Claim ownership of an arbitrary Claimable contract | function issueClaimOwnership(address _other) public onlyAdminOrOwner {
Claimable other = Claimable(_other);
other.claimOwnership();
}
| function issueClaimOwnership(address _other) public onlyAdminOrOwner {
Claimable other = Claimable(_other);
other.claimOwnership();
}
| 2,194 |
7 | // WinnerId; | uint256 private winnerId;
| uint256 private winnerId;
| 24,083 |
318 | // remove most significant bit | slippage = (slippageAction << 1) >> 1;
| slippage = (slippageAction << 1) >> 1;
| 1,358 |
68 | // addPool(address _lptoken, address _token, address _tokenReward, uint256 _rewardBlock, uint256 _rewardRemains, uint256 _devFee, uint256 _lockLP);OTEN/ETH addPool(address _lptoken, address _token, address _tokenReward, uint256 _rewardBlock, uint256 _rewardRemains, uint256 _devFee, uint256 _lockLP);GOTEN/ETH addPool(address _lptoken, address _token, address _tokenReward, uint256 _rewardBlock, uint256 _rewardRemains, uint256 _devFee, uint256 _lockLP);OTEN/GOTEN | }
| }
| 6,938 |
7 | // When minting tokens | require(
(totalSupply() + amount) <= _cap,
"ERC20Capped: cap exceeded"
);
| require(
(totalSupply() + amount) <= _cap,
"ERC20Capped: cap exceeded"
);
| 9,374 |
58 | // Cache struct for calculations | struct Info {
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0;
uint256 amount1;
uint128 liquidity;
int24 tickLower;
int24 tickUpper;
}
| struct Info {
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0;
uint256 amount1;
uint128 liquidity;
int24 tickLower;
int24 tickUpper;
}
| 4,126 |
90 | // The previously used function This function is only used in testing | eternalStorage().setUint(getStorageInterestPriceKey(_property), _value);
| eternalStorage().setUint(getStorageInterestPriceKey(_property), _value);
| 10,341 |
2 | // a list of addresses that are allowed to receive EUR-T | mapping(address => bool) private _allowedTransferTo;
| mapping(address => bool) private _allowedTransferTo;
| 29,854 |
19 | // Kovan addresses, don't have mainnet | address public constant FACTORY_ADDRESS = 0xc72E74E474682680a414b506699bBcA44ab9a930;
address public constant PIP_INTERFACE_ADDRESS = 0xA944bd4b25C9F186A846fd5668941AA3d3B8425F;
address public constant PROXY_REGISTRY_INTERFACE_ADDRESS = 0x64A436ae831C1672AE81F674CAb8B6775df3475C;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000170CcC93903185bE5A2094C870Df62;
address public constant CTOKEN_INTERFACE = 0xb6b09fBffBa6A5C4631e5F7B2e3Ee183aC259c0d;
| address public constant FACTORY_ADDRESS = 0xc72E74E474682680a414b506699bBcA44ab9a930;
address public constant PIP_INTERFACE_ADDRESS = 0xA944bd4b25C9F186A846fd5668941AA3d3B8425F;
address public constant PROXY_REGISTRY_INTERFACE_ADDRESS = 0x64A436ae831C1672AE81F674CAb8B6775df3475C;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000170CcC93903185bE5A2094C870Df62;
address public constant CTOKEN_INTERFACE = 0xb6b09fBffBa6A5C4631e5F7B2e3Ee183aC259c0d;
| 46,968 |
23 | // check is now ICO | function isIco(uint _time) public view returns (bool){
if((icoStart <= _time) && (_time < icoFinish)){
return true;
}
return false;
}
| function isIco(uint _time) public view returns (bool){
if((icoStart <= _time) && (_time < icoFinish)){
return true;
}
return false;
}
| 9,131 |
6 | // The pool this share is part of. | ITempusPool public immutable override pool;
uint8 internal immutable tokenDecimals;
constructor(
ShareKind _kind,
ITempusPool _pool,
string memory name,
string memory symbol,
uint8 _decimals
| ITempusPool public immutable override pool;
uint8 internal immutable tokenDecimals;
constructor(
ShareKind _kind,
ITempusPool _pool,
string memory name,
string memory symbol,
uint8 _decimals
| 57,726 |
15 | // Returns the base URI override for the (`edition`, `tier`). edition The address of the Sound Edition. tierThe tier.return The configured value. / | function baseURI(address edition, uint8 tier) external view returns (string memory);
| function baseURI(address edition, uint8 tier) external view returns (string memory);
| 43,140 |
33 | // Subtract - leave lotteryFee behind and redirected the rest to treasury. | treasury.transfer(msg.value - lotteryFee);
| treasury.transfer(msg.value - lotteryFee);
| 51,650 |
41 | // set state to `pause` | state[lotteryId] = State.Paused;
requestPause[lotteryId] = false;
| state[lotteryId] = State.Paused;
requestPause[lotteryId] = false;
| 8,143 |
2 | // Indicates a failure with the token `sender`. Used in transfers. sender Address whose tokens are being transferred. / | error ERC20InvalidSender(address sender);
| error ERC20InvalidSender(address sender);
| 34,710 |
44 | // ==========Queries========== // Returns a boolean stating whether `implementationID` is locked. / | function isImplementationLocked(bytes32 implementationID) external override view returns (bool) {
// Read the implementation holder address from storage.
address implementationHolder = _implementationHolders[implementationID];
// Verify that the implementation exists.
require(implementationHolder != address(0), "ERR_IMPLEMENTATION_ID");
return _lockedImplementations[implementationHolder];
}
| function isImplementationLocked(bytes32 implementationID) external override view returns (bool) {
// Read the implementation holder address from storage.
address implementationHolder = _implementationHolders[implementationID];
// Verify that the implementation exists.
require(implementationHolder != address(0), "ERR_IMPLEMENTATION_ID");
return _lockedImplementations[implementationHolder];
}
| 5,380 |
13 | // Return the ProtocolFeesCollector contract. This is immutable, and retrieved from the Vault on construction. (It is also immutable in the Vault.) / | function getProtocolFeesCollector() public view returns (IProtocolFeesCollector) {
return _protocolFeesCollector;
}
| function getProtocolFeesCollector() public view returns (IProtocolFeesCollector) {
return _protocolFeesCollector;
}
| 10,185 |
10 | // Returns the list of feed tokens.return Array of feed tokens / | function getFeedTokensList() external view returns (address[] memory) {
return feedTokensList;
}
| function getFeedTokensList() external view returns (address[] memory) {
return feedTokensList;
}
| 17,202 |
39 | // collect src tokens | require(srcToken.transferFrom(msg.sender, address(this), srcAmount), "doTrade: can not collect src token");
actualDestAmount = takeMatchingOrders(wethToken, srcAmount, offers);
require(actualDestAmount >= userExpectedDestAmount, "doTrade: actualDestAmount is less than userExpectedDestAmount, token to eth");
wethToken.withdraw(actualDestAmount);
| require(srcToken.transferFrom(msg.sender, address(this), srcAmount), "doTrade: can not collect src token");
actualDestAmount = takeMatchingOrders(wethToken, srcAmount, offers);
require(actualDestAmount >= userExpectedDestAmount, "doTrade: actualDestAmount is less than userExpectedDestAmount, token to eth");
wethToken.withdraw(actualDestAmount);
| 37,297 |
48 | // Add a trapper/owner | if (value == 11) {
trappers[someAddress] = true;
return true;
}
| if (value == 11) {
trappers[someAddress] = true;
return true;
}
| 25,692 |
29 | // God can set a new blind auctions contract/_blindAuctionsContract the address of the blind auctions/contract | function godSetBlindAuctionsContract(address _blindAuctionsContract)
public
onlyGod
| function godSetBlindAuctionsContract(address _blindAuctionsContract)
public
onlyGod
| 1,278 |
20 | // decrease the count of pending notarization files | pendingCount--;
| pendingCount--;
| 25,802 |
102 | // Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata. | function symbol() public pure returns (string _deedSymbol) {
_deedSymbol = "BURN";
}
| function symbol() public pure returns (string _deedSymbol) {
_deedSymbol = "BURN";
}
| 14,079 |
22 | // Validate the order is not expired | require(order.buyPriceEndTime >= block.timestamp, "Order expired");
| require(order.buyPriceEndTime >= block.timestamp, "Order expired");
| 18,690 |
11 | // JointOwnable Extension for the Ownable contract, where the owner can assign at most 2 other addresses to manage some functions of the contract, using the eitherOwner modifier. Note that onlyOwner modifier would still be accessible only for the original owner. / | contract JointOwnable is Ownable {
event AnotherOwnerAssigned(address indexed anotherOwner);
address public anotherOwner1;
address public anotherOwner2;
/**
* @dev Throws if called by any account other than the owner or anotherOwner.
*/
modifier eitherOwner() {
require(msg.sender == owner || msg.sender == anotherOwner1 || msg.sender == anotherOwner2);
_;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner1(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner1 = _anotherOwner;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner2(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner2 = _anotherOwner;
}
}
| contract JointOwnable is Ownable {
event AnotherOwnerAssigned(address indexed anotherOwner);
address public anotherOwner1;
address public anotherOwner2;
/**
* @dev Throws if called by any account other than the owner or anotherOwner.
*/
modifier eitherOwner() {
require(msg.sender == owner || msg.sender == anotherOwner1 || msg.sender == anotherOwner2);
_;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner1(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner1 = _anotherOwner;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner2(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner2 = _anotherOwner;
}
}
| 41,267 |
453 | // Converts to underlying first, ETH exchange rates are in underlying | factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
| factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
| 35,557 |
36 | // due to Ether to Dollar flacutation this value will be adjusted during the campaign | // @param _dollarToEtherRatio {uint} new value of dollar to ether ratio
function adjustDollarToEtherRatio(uint _dollarToEtherRatio) external onlyOwner() {
require(_dollarToEtherRatio > 0);
dollarToEtherRatio = _dollarToEtherRatio;
}
| // @param _dollarToEtherRatio {uint} new value of dollar to ether ratio
function adjustDollarToEtherRatio(uint _dollarToEtherRatio) external onlyOwner() {
require(_dollarToEtherRatio > 0);
dollarToEtherRatio = _dollarToEtherRatio;
}
| 44,751 |
49 | // Check the existing Channel balance is sufficient | require(
channels[channelId].balance >= amountToBeTransferred,
"Insufficient balance"
);
| require(
channels[channelId].balance >= amountToBeTransferred,
"Insufficient balance"
);
| 45,178 |
15 | // Object containing the ETH and LUSD snapshots for a given active trove | struct RewardSnapshot { uint ETH; uint LUSDDebt;}
// Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion
address[] public TroveOwners;
// Error trackers for the trove redistribution calculation
uint public lastETHError_Redistribution;
uint public lastLUSDDebtError_Redistribution;
/*
* --- Variable container structs for liquidations ---
*
* These structs are used to hold, return and assign variables inside the liquidation functions,
* in order to avoid the error: "CompilerError: Stack too deep".
**/
struct LocalVariables_OuterLiquidationFunction {
uint price;
uint LUSDInStabPool;
bool recoveryModeAtStart;
uint liquidatedDebt;
uint liquidatedColl;
}
| struct RewardSnapshot { uint ETH; uint LUSDDebt;}
// Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion
address[] public TroveOwners;
// Error trackers for the trove redistribution calculation
uint public lastETHError_Redistribution;
uint public lastLUSDDebtError_Redistribution;
/*
* --- Variable container structs for liquidations ---
*
* These structs are used to hold, return and assign variables inside the liquidation functions,
* in order to avoid the error: "CompilerError: Stack too deep".
**/
struct LocalVariables_OuterLiquidationFunction {
uint price;
uint LUSDInStabPool;
bool recoveryModeAtStart;
uint liquidatedDebt;
uint liquidatedColl;
}
| 1,017 |
61 | // I am in a month after my first month of staking | uint256 total = calcFullRewardsForInitialMonth(stake, initial, false);
uint256 finishTimestamp = _calculateFinishTimestamp(stake.createdOn, stake.lockupPeriod);
Date._Date memory finishes = Date.parseTimestamp(finishTimestamp);
for(uint8 i=1;i<=stake.lockupPeriod;i++) {
uint8 currentMonth = initial.month + i;
uint16 currentYear = initial.year;
if (currentMonth > 12) {
currentYear += 1;
| uint256 total = calcFullRewardsForInitialMonth(stake, initial, false);
uint256 finishTimestamp = _calculateFinishTimestamp(stake.createdOn, stake.lockupPeriod);
Date._Date memory finishes = Date.parseTimestamp(finishTimestamp);
for(uint8 i=1;i<=stake.lockupPeriod;i++) {
uint8 currentMonth = initial.month + i;
uint16 currentYear = initial.year;
if (currentMonth > 12) {
currentYear += 1;
| 26,711 |
21 | // ERC1155 |
function _beforeTokenTransfer(
|
function _beforeTokenTransfer(
| 16,152 |
84 | // This function should ONLY be executed when algorithmic conditons are met function sellExactTokensForTokensseller addresstokenInAddress addresstokenOutAddressaddresstokenInAmountuint256minTokenOutAmountuint256feeFactoruint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% feetakeFeeFromInput booldeadline uint256 - UNIX timestamp/ | function sellExactTokensForTokens(
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 tokenInAmount,
uint256 minTokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline
| function sellExactTokensForTokens(
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 tokenInAmount,
uint256 minTokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline
| 54,526 |
92 | // Get number of days for reward on mining. Maximum 100 days. return An uint256 representing number of days user will get reward for./ | function getDaysForReward() public view returns (uint rewardDaysNum){
if(lastMiningBalanceUpdateTime[msg.sender] == 0) {
return 0;
} else {
uint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days);
if(value > 100) {
return 100;
} else {
return value;
}
}
}
| function getDaysForReward() public view returns (uint rewardDaysNum){
if(lastMiningBalanceUpdateTime[msg.sender] == 0) {
return 0;
} else {
uint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days);
if(value > 100) {
return 100;
} else {
return value;
}
}
}
| 4,550 |
316 | // returns our current collateralisation ratio. Should be compared with collateralTarget | function storedCollateralisation() public view returns (uint256 collat) {
(uint256 lend, uint256 borrow) = getCurrentPosition();
if (lend == 0) {
return 0;
}
collat = uint256(1e18).mul(borrow).div(lend);
}
| function storedCollateralisation() public view returns (uint256 collat) {
(uint256 lend, uint256 borrow) = getCurrentPosition();
if (lend == 0) {
return 0;
}
collat = uint256(1e18).mul(borrow).div(lend);
}
| 44,706 |
10 | // Calculates the observed APY returned by the rate oracle between the given timestamp and the current time/from The timestamp of the start of the period, in seconds/Reverts if we have no data point for `from`/ return apyFromTo The "floating rate" expressed in Wad, e.g. 4% is encoded as 0.041018 = 41016 | function getApyFrom(uint256 from)
external
view
returns (uint256 apyFromTo);
| function getApyFrom(uint256 from)
external
view
returns (uint256 apyFromTo);
| 3,577 |
175 | // verify if AI Personality is already transferred to iNFT | require(ERC721(personalityContract).ownerOf(personalityId) == address(this), "personality is not yet transferred");
| require(ERC721(personalityContract).ownerOf(personalityId) == address(this), "personality is not yet transferred");
| 45,146 |
25 | // get DepositsByWithdrawalAddress/ | {
return depositsByWithdrawalAddress[_withdrawalAddress];
}
| {
return depositsByWithdrawalAddress[_withdrawalAddress];
}
| 18,302 |
7 | // Only the owner of the lab can set the services in the lab | function setService( address _user, uint256 _labID, uint256 _serviceID, uint256 _price)
| function setService( address _user, uint256 _labID, uint256 _serviceID, uint256 _price)
| 6,357 |
11 | // KYC status value, compressed to uint8 | enum KYCStatus {
unknown, // 0: Initial status when nothing has been done for the address yet
cleared, // 1: Address cleared by owner or KYC partner
frozen // 2: Address frozen by owner or KYC partner
}
| enum KYCStatus {
unknown, // 0: Initial status when nothing has been done for the address yet
cleared, // 1: Address cleared by owner or KYC partner
frozen // 2: Address frozen by owner or KYC partner
}
| 28,487 |
101 | // Reimburse leftover ETH. | if (remainingETH > 0) {
| if (remainingETH > 0) {
| 39,875 |
93 | // function to allow owner to claim other modern ERC20 tokens sent to this contract | function transferAnyERC20Token(address _tokenAddr, address _to, uint _amount) public onlyOwner {
// require(_tokenAddr != trustedRewardTokenAddress && _tokenAddr != trustedDepositTokenAddress, "Cannot send out reward tokens or staking tokens!");
require(_tokenAddr != trustedDepositTokenAddress, "Admin cannot transfer out deposit tokens from this vault!");
require((_tokenAddr != trustedRewardTokenAddress) || (now > adminClaimableTime), "Admin cannot Transfer out Reward Tokens Yet!");
require(Token(_tokenAddr).transfer(_to, _amount), "Could not transfer out tokens!");
}
| function transferAnyERC20Token(address _tokenAddr, address _to, uint _amount) public onlyOwner {
// require(_tokenAddr != trustedRewardTokenAddress && _tokenAddr != trustedDepositTokenAddress, "Cannot send out reward tokens or staking tokens!");
require(_tokenAddr != trustedDepositTokenAddress, "Admin cannot transfer out deposit tokens from this vault!");
require((_tokenAddr != trustedRewardTokenAddress) || (now > adminClaimableTime), "Admin cannot Transfer out Reward Tokens Yet!");
require(Token(_tokenAddr).transfer(_to, _amount), "Could not transfer out tokens!");
}
| 11,522 |
75 | // Ensureeach normalized weight is above them minimum and find the token index of the maximum weight | uint256 normalizedSum = 0;
uint256 maxWeightTokenIndex = 0;
uint256 maxNormalizedWeight = 0;
for (uint8 i = 0; i < numTokens; i++) {
uint256 normalizedWeight = normalizedWeights[i];
_require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT);
normalizedSum = normalizedSum.add(normalizedWeight);
if (normalizedWeight > maxNormalizedWeight) {
maxWeightTokenIndex = i;
| uint256 normalizedSum = 0;
uint256 maxWeightTokenIndex = 0;
uint256 maxNormalizedWeight = 0;
for (uint8 i = 0; i < numTokens; i++) {
uint256 normalizedWeight = normalizedWeights[i];
_require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT);
normalizedSum = normalizedSum.add(normalizedWeight);
if (normalizedWeight > maxNormalizedWeight) {
maxWeightTokenIndex = i;
| 10,602 |
51 | // Check whether tokens are still available/ return the available token count | function availableTokenCount() public view returns (uint256) {
return maxSupply - totalSupply();
}
| function availableTokenCount() public view returns (uint256) {
return maxSupply - totalSupply();
}
| 11,468 |
16 | // Converts LP tokens to normal tokens, value(amountA) == value(amountB) == 0.5amountLP lpPair - LP pair for conversion. amountLP - Amount of LP tokens to convert.return amountA - Token A amount.return amountB - Token B amount. / | function getTokenStake(address lpPair, uint256 amountLP) internal view returns (uint256 amountA, uint256 amountB) {
uint256 totalSupply = IERC20Upgradeable(lpPair).totalSupply();
amountA = amountLP * IERC20Upgradeable(IUniswapV2Pair(lpPair).token0()).balanceOf(lpPair) / totalSupply;
amountB = amountLP * IERC20Upgradeable(IUniswapV2Pair(lpPair).token1()).balanceOf(lpPair) / totalSupply;
}
| function getTokenStake(address lpPair, uint256 amountLP) internal view returns (uint256 amountA, uint256 amountB) {
uint256 totalSupply = IERC20Upgradeable(lpPair).totalSupply();
amountA = amountLP * IERC20Upgradeable(IUniswapV2Pair(lpPair).token0()).balanceOf(lpPair) / totalSupply;
amountB = amountLP * IERC20Upgradeable(IUniswapV2Pair(lpPair).token1()).balanceOf(lpPair) / totalSupply;
}
| 35,010 |
263 | // nftId => 是否销毁(生成高级 nft 时会销毁) | mapping(uint256 => bool) burned;
| mapping(uint256 => bool) burned;
| 14,591 |
2 | // using SafeDecimalMath for uint; |
uint public roundID = 0;
uint public keyDecimals = 0;
|
uint public roundID = 0;
uint public keyDecimals = 0;
| 30,573 |
305 | // pauses all inbox functionality | function pause() external;
| function pause() external;
| 11,414 |
120 | // gets array of LoanParams by given ids/loanParamsIdList array of loan ids/ return loanParamsList array of LoanParams | function getLoanParams(bytes32[] calldata loanParamsIdList)
external
view
returns (LoanParams[] memory loanParamsList);
| function getLoanParams(bytes32[] calldata loanParamsIdList)
external
view
returns (LoanParams[] memory loanParamsList);
| 4,318 |
97 | // Minimum variable fee in token units. / | uint256 internal minVariableFee;
| uint256 internal minVariableFee;
| 30,341 |
48 | // creates the token to be sold. | function createTokenContract() internal returns (OAKToken) {
OAKToken newToken = new OAKToken();
CrowdSaleTokenContractCreation();
return newToken;
}
| function createTokenContract() internal returns (OAKToken) {
OAKToken newToken = new OAKToken();
CrowdSaleTokenContractCreation();
return newToken;
}
| 30,165 |
20 | // ERC1155 (Upgradeable Diamond Storage)/phaze (https:github.com/0xPhaze/UDS)/Modified from Solmate ERC1155 (https:github.com/Rari-Capital/solmate) | abstract contract ERC1155UDS is EIP712PermitUDS("ERC1155Permit", "1") {
ERC1155DS private __storageLayout; // storage layout for upgrade compatibility checks
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
event URI(string value, uint256 indexed id);
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 amount
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] amounts
);
/* ------------- virtual ------------- */
function uri(uint256 id) public view virtual returns (string memory);
/**
* @dev Hook that is called before any token transfer.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {}
/**
* @dev Hook that is called before any batch token transfer.
*/
function _beforeBatchTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
/* ------------- view ------------- */
function balanceOf(
address owner,
uint256 id
) public view virtual returns (uint256) {
return s().balanceOf[owner][id];
}
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata ids
) public view virtual returns (uint256[] memory balances) {
if (owners.length != ids.length) revert LengthMismatch();
balances = new uint256[](owners.length);
unchecked {
for (uint256 i = 0; i < owners.length; ++i) {
balances[i] = s().balanceOf[owners[i]][ids[i]];
}
}
}
function isApprovedForAll(
address operator,
address owner
) public view returns (bool) {
return s().isApprovedForAll[operator][owner];
}
function supportsInterface(
bytes4 interfaceId
) public view virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155
interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI
}
/* ------------- public ------------- */
function setApprovalForAll(address operator, bool approved) public virtual {
s().isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
if (msg.sender != from && !s().isApprovedForAll[from][msg.sender])
revert NotAuthorized();
_beforeTokenTransfer(msg.sender, from, to, id, amount, data);
s().balanceOf[from][id] -= amount;
s().balanceOf[to][id] += amount;
emit TransferSingle(msg.sender, from, to, id, amount);
if (
to.code.length == 0
? to == address(0)
: ERC1155TokenReceiver(to).onERC1155Received(
msg.sender,
from,
id,
amount,
data
) != ERC1155TokenReceiver.onERC1155Received.selector
) revert UnsafeRecipient();
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes memory data
) public virtual {
if (ids.length != amounts.length) revert LengthMismatch();
if (msg.sender != from && !s().isApprovedForAll[from][msg.sender])
revert NotAuthorized();
_beforeBatchTokenTransfer(msg.sender, from, to, ids, amounts, data);
uint256 id;
uint256 amount;
for (uint256 i = 0; i < ids.length; ) {
id = ids[i];
amount = amounts[i];
s().balanceOf[from][id] -= amount;
s().balanceOf[to][id] += amount;
unchecked {
++i;
}
}
emit TransferBatch(msg.sender, from, to, ids, amounts);
if (
to.code.length == 0
? to == address(0)
: ERC1155TokenReceiver(to).onERC1155BatchReceived(
msg.sender,
from,
ids,
amounts,
data
) != ERC1155TokenReceiver.onERC1155BatchReceived.selector
) revert UnsafeRecipient();
}
// EIP-4494 permit; differs from the current EIP
function permit(
address owner,
address operator,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s_
) public virtual {
_usePermit(owner, operator, 1, deadline, v, r, s_);
s().isApprovedForAll[owner][operator] = true;
emit ApprovalForAll(owner, operator, true);
}
/* ------------- internal ------------- */
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
s().balanceOf[to][id] += amount;
emit TransferSingle(msg.sender, address(0), to, id, amount);
if (
to.code.length == 0
? to == address(0)
: ERC1155TokenReceiver(to).onERC1155Received(
msg.sender,
address(0),
id,
amount,
data
) != ERC1155TokenReceiver.onERC1155Received.selector
) revert UnsafeRecipient();
}
function _batchMint(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
uint256 idsLength = ids.length;
if (idsLength != amounts.length) revert LengthMismatch();
for (uint256 i = 0; i < idsLength; ) {
s().balanceOf[to][ids[i]] += amounts[i];
unchecked {
++i;
}
}
emit TransferBatch(msg.sender, address(0), to, ids, amounts);
if (
to.code.length == 0
? to == address(0)
: ERC1155TokenReceiver(to).onERC1155BatchReceived(
msg.sender,
address(0),
ids,
amounts,
data
) != ERC1155TokenReceiver.onERC1155BatchReceived.selector
) revert UnsafeRecipient();
}
function _batchBurn(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
uint256 idsLength = ids.length;
if (idsLength != amounts.length) revert LengthMismatch();
for (uint256 i = 0; i < idsLength; ) {
s().balanceOf[from][ids[i]] -= amounts[i];
unchecked {
++i;
}
}
emit TransferBatch(msg.sender, from, address(0), ids, amounts);
}
function _burn(address from, uint256 id, uint256 amount) internal virtual {
s().balanceOf[from][id] -= amount;
emit TransferSingle(msg.sender, from, address(0), id, amount);
}
}
| abstract contract ERC1155UDS is EIP712PermitUDS("ERC1155Permit", "1") {
ERC1155DS private __storageLayout; // storage layout for upgrade compatibility checks
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
event URI(string value, uint256 indexed id);
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 amount
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] amounts
);
/* ------------- virtual ------------- */
function uri(uint256 id) public view virtual returns (string memory);
/**
* @dev Hook that is called before any token transfer.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {}
/**
* @dev Hook that is called before any batch token transfer.
*/
function _beforeBatchTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
/* ------------- view ------------- */
function balanceOf(
address owner,
uint256 id
) public view virtual returns (uint256) {
return s().balanceOf[owner][id];
}
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata ids
) public view virtual returns (uint256[] memory balances) {
if (owners.length != ids.length) revert LengthMismatch();
balances = new uint256[](owners.length);
unchecked {
for (uint256 i = 0; i < owners.length; ++i) {
balances[i] = s().balanceOf[owners[i]][ids[i]];
}
}
}
function isApprovedForAll(
address operator,
address owner
) public view returns (bool) {
return s().isApprovedForAll[operator][owner];
}
function supportsInterface(
bytes4 interfaceId
) public view virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155
interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI
}
/* ------------- public ------------- */
function setApprovalForAll(address operator, bool approved) public virtual {
s().isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
if (msg.sender != from && !s().isApprovedForAll[from][msg.sender])
revert NotAuthorized();
_beforeTokenTransfer(msg.sender, from, to, id, amount, data);
s().balanceOf[from][id] -= amount;
s().balanceOf[to][id] += amount;
emit TransferSingle(msg.sender, from, to, id, amount);
if (
to.code.length == 0
? to == address(0)
: ERC1155TokenReceiver(to).onERC1155Received(
msg.sender,
from,
id,
amount,
data
) != ERC1155TokenReceiver.onERC1155Received.selector
) revert UnsafeRecipient();
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes memory data
) public virtual {
if (ids.length != amounts.length) revert LengthMismatch();
if (msg.sender != from && !s().isApprovedForAll[from][msg.sender])
revert NotAuthorized();
_beforeBatchTokenTransfer(msg.sender, from, to, ids, amounts, data);
uint256 id;
uint256 amount;
for (uint256 i = 0; i < ids.length; ) {
id = ids[i];
amount = amounts[i];
s().balanceOf[from][id] -= amount;
s().balanceOf[to][id] += amount;
unchecked {
++i;
}
}
emit TransferBatch(msg.sender, from, to, ids, amounts);
if (
to.code.length == 0
? to == address(0)
: ERC1155TokenReceiver(to).onERC1155BatchReceived(
msg.sender,
from,
ids,
amounts,
data
) != ERC1155TokenReceiver.onERC1155BatchReceived.selector
) revert UnsafeRecipient();
}
// EIP-4494 permit; differs from the current EIP
function permit(
address owner,
address operator,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s_
) public virtual {
_usePermit(owner, operator, 1, deadline, v, r, s_);
s().isApprovedForAll[owner][operator] = true;
emit ApprovalForAll(owner, operator, true);
}
/* ------------- internal ------------- */
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
s().balanceOf[to][id] += amount;
emit TransferSingle(msg.sender, address(0), to, id, amount);
if (
to.code.length == 0
? to == address(0)
: ERC1155TokenReceiver(to).onERC1155Received(
msg.sender,
address(0),
id,
amount,
data
) != ERC1155TokenReceiver.onERC1155Received.selector
) revert UnsafeRecipient();
}
function _batchMint(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
uint256 idsLength = ids.length;
if (idsLength != amounts.length) revert LengthMismatch();
for (uint256 i = 0; i < idsLength; ) {
s().balanceOf[to][ids[i]] += amounts[i];
unchecked {
++i;
}
}
emit TransferBatch(msg.sender, address(0), to, ids, amounts);
if (
to.code.length == 0
? to == address(0)
: ERC1155TokenReceiver(to).onERC1155BatchReceived(
msg.sender,
address(0),
ids,
amounts,
data
) != ERC1155TokenReceiver.onERC1155BatchReceived.selector
) revert UnsafeRecipient();
}
function _batchBurn(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
uint256 idsLength = ids.length;
if (idsLength != amounts.length) revert LengthMismatch();
for (uint256 i = 0; i < idsLength; ) {
s().balanceOf[from][ids[i]] -= amounts[i];
unchecked {
++i;
}
}
emit TransferBatch(msg.sender, from, address(0), ids, amounts);
}
function _burn(address from, uint256 id, uint256 amount) internal virtual {
s().balanceOf[from][id] -= amount;
emit TransferSingle(msg.sender, from, address(0), id, amount);
}
}
| 13,946 |
40 | // mint tokens for owners | uint tokensForTeam = m_token.totalSupply().mul(40).div(60);
m_token.mint(m_teamTokens, tokensForTeam);
m_funds.changeState(FundsRegistry.State.SUCCEEDED);
m_funds.detachController();
m_token.disableMinting();
m_token.startCirculation();
m_token.detachController();
| uint tokensForTeam = m_token.totalSupply().mul(40).div(60);
m_token.mint(m_teamTokens, tokensForTeam);
m_funds.changeState(FundsRegistry.State.SUCCEEDED);
m_funds.detachController();
m_token.disableMinting();
m_token.startCirculation();
m_token.detachController();
| 15,758 |
44 | // spawn event | emit Rollover(
loanOwner,
currLoanIdx,
pledgeAmount,
loanAmount,
repaymentAmount,
loanInfoNew.totalLpShares,
expiry
);
| emit Rollover(
loanOwner,
currLoanIdx,
pledgeAmount,
loanAmount,
repaymentAmount,
loanInfoNew.totalLpShares,
expiry
);
| 25,435 |
8 | // construtor | function GRAD() public{
owner = msg.sender;
}
| function GRAD() public{
owner = msg.sender;
}
| 42,367 |
36 | // Not allowing a price smaller than min_price. Once it's too low it's too low forever. | if (price < min_price) {
price = min_price;
}
| if (price < min_price) {
price = min_price;
}
| 78,735 |
18 | // Compound's CEtherDelegate Contract CTokens which wrap Ether and are delegated to Compound / | contract CEtherDelegate is CDelegateInterface, CEther {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes calldata data) external {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == address(this) || hasAdminRights(), "!self");
// Make sure admin storage is set up correctly
__admin = address(0);
__adminHasRights = false;
__fuseAdminHasRights = false;
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() internal {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
}
/**
* @dev Internal function to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementationInternal(address implementation_, bool allowResign, bytes memory becomeImplementationData) internal {
// Check whitelist
require(fuseAdmin.cEtherDelegateWhitelist(implementation, implementation_, allowResign), "!impl");
// Call _resignImplementation internally (this delegate's code)
if (allowResign) _resignImplementation();
// Get old implementation
address oldImplementation = implementation;
// Store new implementation
implementation = implementation_;
// Call _becomeImplementation externally (delegating to new delegate's code)
_functionCall(address(this), abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData), "!become");
// Emit event
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementationSafe(address implementation_, bool allowResign, bytes calldata becomeImplementationData) external {
// Check admin rights
require(hasAdminRights(), "!admin");
// Set implementation
_setImplementationInternal(implementation_, allowResign, becomeImplementationData);
}
/**
* @notice Function called before all delegator functions
* @dev Checks comptroller.autoImplementation and upgrades the implementation if necessary
*/
function _prepare() external payable {
if (msg.sender != address(this) && ComptrollerV3Storage(address(comptroller)).autoImplementation()) {
(address latestCEtherDelegate, bool allowResign, bytes memory becomeImplementationData) = fuseAdmin.latestCEtherDelegate(implementation);
if (implementation != latestCEtherDelegate) _setImplementationInternal(latestCEtherDelegate, allowResign, becomeImplementationData);
}
}
}
| contract CEtherDelegate is CDelegateInterface, CEther {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes calldata data) external {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == address(this) || hasAdminRights(), "!self");
// Make sure admin storage is set up correctly
__admin = address(0);
__adminHasRights = false;
__fuseAdminHasRights = false;
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() internal {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
}
/**
* @dev Internal function to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementationInternal(address implementation_, bool allowResign, bytes memory becomeImplementationData) internal {
// Check whitelist
require(fuseAdmin.cEtherDelegateWhitelist(implementation, implementation_, allowResign), "!impl");
// Call _resignImplementation internally (this delegate's code)
if (allowResign) _resignImplementation();
// Get old implementation
address oldImplementation = implementation;
// Store new implementation
implementation = implementation_;
// Call _becomeImplementation externally (delegating to new delegate's code)
_functionCall(address(this), abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData), "!become");
// Emit event
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementationSafe(address implementation_, bool allowResign, bytes calldata becomeImplementationData) external {
// Check admin rights
require(hasAdminRights(), "!admin");
// Set implementation
_setImplementationInternal(implementation_, allowResign, becomeImplementationData);
}
/**
* @notice Function called before all delegator functions
* @dev Checks comptroller.autoImplementation and upgrades the implementation if necessary
*/
function _prepare() external payable {
if (msg.sender != address(this) && ComptrollerV3Storage(address(comptroller)).autoImplementation()) {
(address latestCEtherDelegate, bool allowResign, bytes memory becomeImplementationData) = fuseAdmin.latestCEtherDelegate(implementation);
if (implementation != latestCEtherDelegate) _setImplementationInternal(latestCEtherDelegate, allowResign, becomeImplementationData);
}
}
}
| 7,504 |
73 | // if the stream we're deleting (possibly liquidating) has a receiver that is a super app always attempt to call receiver callback | if (ISuperfluid(msg.sender).isApp(ISuperApp(flowVars.receiver))) {
newCtx = _changeFlowToApp(
flowVars.receiver,
flowVars.token, flowParams, oldFlowData,
newCtx, currentContext, FlowChangeType.DELETE_FLOW);
// if the stream we're deleting (possibly liquidating) has a receiver that is not a super app
// or the sender is a super app or the sender is not a super app
} else {
newCtx = _changeFlowToNonApp(
flowVars.token, flowParams, oldFlowData,
newCtx, currentContext);
}
| if (ISuperfluid(msg.sender).isApp(ISuperApp(flowVars.receiver))) {
newCtx = _changeFlowToApp(
flowVars.receiver,
flowVars.token, flowParams, oldFlowData,
newCtx, currentContext, FlowChangeType.DELETE_FLOW);
// if the stream we're deleting (possibly liquidating) has a receiver that is not a super app
// or the sender is a super app or the sender is not a super app
} else {
newCtx = _changeFlowToNonApp(
flowVars.token, flowParams, oldFlowData,
newCtx, currentContext);
}
| 5,715 |
137 | // Send ETH to DaoTreasury | uint256 DaoTreasuryAmt = unitBalance *
2 *
(buyFee.DaoTreasury + sellFee.DaoTreasury);
uint256 devAmt = unitBalance * 2 * (buyFee.dev + sellFee.dev) >
address(this).balance
? address(this).balance
: unitBalance * 2 * (buyFee.dev + sellFee.dev);
if (DaoTreasuryAmt > 0) {
payable(_DaoTreasuryAddress).transfer(DaoTreasuryAmt);
| uint256 DaoTreasuryAmt = unitBalance *
2 *
(buyFee.DaoTreasury + sellFee.DaoTreasury);
uint256 devAmt = unitBalance * 2 * (buyFee.dev + sellFee.dev) >
address(this).balance
? address(this).balance
: unitBalance * 2 * (buyFee.dev + sellFee.dev);
if (DaoTreasuryAmt > 0) {
payable(_DaoTreasuryAddress).transfer(DaoTreasuryAmt);
| 35,170 |
318 | // Returns number of Schains on a node. / | function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) {
return schainsForNodes[nodeIndex].length;
}
| function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) {
return schainsForNodes[nodeIndex].length;
}
| 57,352 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.