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 |
|---|---|---|---|---|
588 | // Amount of collateral claimed by users/Vault => TokenId => Account => Collateral claimed [wad] | mapping(address => mapping(uint256 => mapping(address => uint256))) public override claimed;
| mapping(address => mapping(uint256 => mapping(address => uint256))) public override claimed;
| 34,007 |
253 | // Dev rewards | incentivizeWithStake(address(0xdaeD3f8E267CF2e5480A379d75BfABad58ab2144), 3000000e18);
| incentivizeWithStake(address(0xdaeD3f8E267CF2e5480A379d75BfABad58ab2144), 3000000e18);
| 11,780 |
6 | // Constrctor function Initializes contract with initial supply tokens to the creator of the contract / | constructor() public {
name = "TutorialToken";
symbol = "TTT";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| constructor() public {
name = "TutorialToken";
symbol = "TTT";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 478 |
7 | // Event when amount deposited exchange | event Deposit(address token, address user, uint256 amount, uint256 balance);
| event Deposit(address token, address user, uint256 amount, uint256 balance);
| 30,177 |
1 | // is everything Okey? | require(campaign.deadline <block.timestamp,"The deadline should be in the future");
campaign.owner =_owner;
campaign.title =_title;
campaign.description =_description;
campaign.target =_target;
campaign.deadline =_deadline;
campaign.amountCollected =0;
campaign.image =_image;
| require(campaign.deadline <block.timestamp,"The deadline should be in the future");
campaign.owner =_owner;
campaign.title =_title;
campaign.description =_description;
campaign.target =_target;
campaign.deadline =_deadline;
campaign.amountCollected =0;
campaign.image =_image;
| 21,241 |
80 | // AddressStorage | function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
| function getAddressValue(bytes32 record) external view returns (address) {
return AddressStorage[record];
}
| 29,357 |
8 | // check if the Vendor Contract has enough amount of tokens for the transaction | uint256 vendorBalance = devToken.balanceOf(address(this));
require(
vendorBalance >= amountToBuy,
"Vendor contract has not enough tokens in its balance"
);
| uint256 vendorBalance = devToken.balanceOf(address(this));
require(
vendorBalance >= amountToBuy,
"Vendor contract has not enough tokens in its balance"
);
| 32,760 |
166 | // Keep track of the holders, reserve, and multiplier for this dividend. | _dividendHolderCounts.push(holders);
_dividendMultipliers.push(multiplier);
_dividendReserves.push(reserveIncrease);
| _dividendHolderCounts.push(holders);
_dividendMultipliers.push(multiplier);
_dividendReserves.push(reserveIncrease);
| 37,547 |
22 | // Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), Reverts when dividing by zero. Counterpart to Solidity's `%` operator. This function uses a `revert` opcode (which leaves remaining gas untouched) while Solidity uses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero./ | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
| function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
| 864 |
141 | // Compound support ETH as collateral not WETH. This hook will takecare of conversion from WETH to ETH and vice versa. This will be used in ETH strategy only, hence empty implementation /solhint-disable-next-line no-empty-blocks | function _afterRedeem() internal virtual {}
function _convertToCollateral(uint256 _cTokenAmount) internal view returns (uint256) {
return (_cTokenAmount * cToken.exchangeRateStored()) / 1e18;
}
| function _afterRedeem() internal virtual {}
function _convertToCollateral(uint256 _cTokenAmount) internal view returns (uint256) {
return (_cTokenAmount * cToken.exchangeRateStored()) / 1e18;
}
| 38,701 |
104 | // common errors | string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin'
string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small
| string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin'
string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small
| 21,353 |
153 | // This Earn strategy will deposit collateral token in a Vesper Grow Pool/ and converts the yield to another Drip Token solhint-disable no-empty-blocks | abstract contract EarnVesperStrategy is VesperStrategy, Earn {
using SafeERC20 for IERC20;
constructor(
address _pool,
address _swapManager,
address _receiptToken,
address _dripToken
) VesperStrategy(_pool, _swapManager, _receiptToken) Earn(_dripToken) {}
/// @notice Approve all required tokens
function _approveToken(uint256 _amount) internal virtual override(VesperStrategy, Strategy) {
collateralToken.safeApprove(pool, _amount);
collateralToken.safeApprove(address(vToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(VSP).safeApprove(address(swapManager.ROUTERS(i)), _amount);
collateralToken.safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
}
/**
* @notice Calculate earning and withdraw it from Vesper Grow.
* @param _totalDebt Total collateral debt of this strategy
* @return profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal virtual override(VesperStrategy, Strategy) returns (uint256) {
_claimRewardsAndConvertTo(address(dripToken));
uint256 _collateralBalance = _getCollateralBalance();
if (_collateralBalance > _totalDebt) {
_withdrawHere(_collateralBalance - _totalDebt);
}
_convertCollateralToDrip();
_forwardEarning();
return 0;
}
/// @notice Claim VSP rewards in underlying Grow Pool, if any
function _claimRewardsAndConvertTo(address _toToken) internal virtual override(VesperStrategy, Strategy) {
VesperStrategy._claimRewardsAndConvertTo(_toToken);
}
}
| abstract contract EarnVesperStrategy is VesperStrategy, Earn {
using SafeERC20 for IERC20;
constructor(
address _pool,
address _swapManager,
address _receiptToken,
address _dripToken
) VesperStrategy(_pool, _swapManager, _receiptToken) Earn(_dripToken) {}
/// @notice Approve all required tokens
function _approveToken(uint256 _amount) internal virtual override(VesperStrategy, Strategy) {
collateralToken.safeApprove(pool, _amount);
collateralToken.safeApprove(address(vToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(VSP).safeApprove(address(swapManager.ROUTERS(i)), _amount);
collateralToken.safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
}
/**
* @notice Calculate earning and withdraw it from Vesper Grow.
* @param _totalDebt Total collateral debt of this strategy
* @return profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal virtual override(VesperStrategy, Strategy) returns (uint256) {
_claimRewardsAndConvertTo(address(dripToken));
uint256 _collateralBalance = _getCollateralBalance();
if (_collateralBalance > _totalDebt) {
_withdrawHere(_collateralBalance - _totalDebt);
}
_convertCollateralToDrip();
_forwardEarning();
return 0;
}
/// @notice Claim VSP rewards in underlying Grow Pool, if any
function _claimRewardsAndConvertTo(address _toToken) internal virtual override(VesperStrategy, Strategy) {
VesperStrategy._claimRewardsAndConvertTo(_toToken);
}
}
| 22,932 |
305 | // require(msg.sender == primaryDevAddress , "Dev Only: caller is not the developer"); | _;
| _;
| 41,072 |
59 | // originalItem.token == newItem.token && originalItem.itemType == newItem.itemType | and(
eq(
mload(add(originalItem, Common_token_offset)),
mload(add(newItem, Common_token_offset))
),
eq(itemType, mload(newItem))
),
| and(
eq(
mload(add(originalItem, Common_token_offset)),
mload(add(newItem, Common_token_offset))
),
eq(itemType, mload(newItem))
),
| 20,425 |
16 | // 解锁日志记录 | emit LedgerRecordAdd(_date, _hash, _depth, _fileFormat, _stripLen, _balanceHash, _balanceDepth);
return true;
| emit LedgerRecordAdd(_date, _hash, _depth, _fileFormat, _stripLen, _balanceHash, _balanceDepth);
return true;
| 39,399 |
122 | // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds | return _tokenOwners.length();
| return _tokenOwners.length();
| 7,594 |
19 | // Represents the Mill formed on the board | struct Mill
| struct Mill
| 12,433 |
0 | // Interface for the Yield-bearing cToken by Compound | CTokenInterface public cToken;
| CTokenInterface public cToken;
| 24,492 |
138 | // Cache the recipient and amount | recipient = recipients[i];
amount = amounts[i];
| recipient = recipients[i];
amount = amounts[i];
| 41,697 |
210 | // Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64, even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is already assumed to fit in uint64. | Term storage previousTerm = terms[currentTermId++];
Term storage currentTerm = terms[currentTermId];
_onTermTransitioned(currentTermId);
| Term storage previousTerm = terms[currentTermId++];
Term storage currentTerm = terms[currentTermId];
_onTermTransitioned(currentTermId);
| 19,465 |
138 | // Returns the token stored in the pool. It will be in token defined decimals. | function tokensHere() public view virtual returns (uint256) {
return token.balanceOf(address(this));
}
| function tokensHere() public view virtual returns (uint256) {
return token.balanceOf(address(this));
}
| 1,814 |
12 | // return the amount of the token released. / | function getReleased(address token) external view returns (uint256) {
return released[token];
}
| function getReleased(address token) external view returns (uint256) {
return released[token];
}
| 15,496 |
74 | // Emit the cancel event | WithdrawSale(msg.sender, skinId);
| WithdrawSale(msg.sender, skinId);
| 52,764 |
396 | // Sanity check to make sure the token minter is right. | require(CurveTokenV3Interface(tokenAddresses[i]).minter() == swap[i], "incorrect pool");
| require(CurveTokenV3Interface(tokenAddresses[i]).minter() == swap[i], "incorrect pool");
| 69,112 |
45 | // Ensure that the loan date is greater than 6 months | require(block.timestamp >= loan.date + loanDuration, "Loan has not yet expired");
| require(block.timestamp >= loan.date + loanDuration, "Loan has not yet expired");
| 19,636 |
18 | // BASE TRAIT SWAPPING | uint256[9] memory base1 = getBaseAttributues(_token1);
uint256[9] memory base2 = getBaseAttributues(_token2);
uint256 tmp = base1[attributeId];
base1[attributeId] = base2[attributeId];
base2[attributeId] = tmp;
saveBaseAttributes(_token1, base1);
saveBaseAttributes(_token2, base2);
| uint256[9] memory base1 = getBaseAttributues(_token1);
uint256[9] memory base2 = getBaseAttributues(_token2);
uint256 tmp = base1[attributeId];
base1[attributeId] = base2[attributeId];
base2[attributeId] = tmp;
saveBaseAttributes(_token1, base1);
saveBaseAttributes(_token2, base2);
| 3,538 |
18 | // 存token | function depositToken(address token, uint256 amount) public {
require(token != address(0));
require(IToken(token).transferFrom(msg.sender, address(this), amount), 'transfer token failed');
tokens[token][msg.sender] = SafeMath.add(tokens[token][msg.sender], amount);
emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
| function depositToken(address token, uint256 amount) public {
require(token != address(0));
require(IToken(token).transferFrom(msg.sender, address(this), amount), 'transfer token failed');
tokens[token][msg.sender] = SafeMath.add(tokens[token][msg.sender], amount);
emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
| 52,724 |
6 | // Returns message's destination field | function destination(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(40, 4));
}
| function destination(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(40, 4));
}
| 20,604 |
32 | // Set the token URI resolver if provided. | if (_tokenUriResolver != IJBTokenUriResolver(address(0)))
_store.recordSetTokenUriResolver(_tokenUriResolver);
| if (_tokenUriResolver != IJBTokenUriResolver(address(0)))
_store.recordSetTokenUriResolver(_tokenUriResolver);
| 11,780 |
87 | // Allows to renounce upgrades | bool public upgradesAllowed = true;
| bool public upgradesAllowed = true;
| 77,167 |
7 | // The Public Key (stealth addresses) | mapping (uint256 => uint256[2]) publicKeys;
| mapping (uint256 => uint256[2]) publicKeys;
| 36,863 |
41 | // return the number of decimals of the token. / | function decimals() public view returns (uint8) {
return _decimals;
}
| function decimals() public view returns (uint8) {
return _decimals;
}
| 2,646 |
36 | // Exchange tokens | _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
uint256 amountReceived = (isFeeexempt[sender] || isFeeexempt[recipient]) ? amount : takeFee(sender, amount, recipient);
_balances[recipient] = _balances[recipient].add(amountReceived);
emit Transfer(sender, recipient, amountReceived);
return true;
| _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
uint256 amountReceived = (isFeeexempt[sender] || isFeeexempt[recipient]) ? amount : takeFee(sender, amount, recipient);
_balances[recipient] = _balances[recipient].add(amountReceived);
emit Transfer(sender, recipient, amountReceived);
return true;
| 20,036 |
4 | // i.e. maker ratio is -400, taker amt should be MakerOrder.ethPosted / (400/100) | amtRequired = (ethPosted / Settler.negate64(ratio)) * 100;
| amtRequired = (ethPosted / Settler.negate64(ratio)) * 100;
| 5,824 |
11 | // Dev fee. | uint256 public devfee = 1000;
| uint256 public devfee = 1000;
| 5,678 |
6 | // Returns True if an account passes a query, where query is the desired privileges. account The account to check the privileges of. query The desired privileges to check for. / | function check(address account, bytes32 query) external view returns (bool);
| function check(address account, bytes32 query) external view returns (bool);
| 40,122 |
18 | // Ballot Implements voting process along with vote delegation / | contract Ballot {
struct Voter {
uint weight; // weight is accumulated by delegation
bool voted; // if true, that person already voted
address delegate; // person delegated to
uint vote; // index of the voted proposal
}
struct Proposal {
address owner; // address that created the proposal
// If you can limit the length to a certain number of bytes,
// always use one of bytes1 to bytes32 because they are much cheaper
string name; // short name
uint voteCount; // number of accumulated votes
}
address public chairPerson;
uint public proposalCount;
Proposal[] public proposals;
mapping(address => Voter) public voters;
event proposalSubmited(
uint proposalIndex
);
event proposalVoted(
uint proposalIndex
);
/**
* @dev Modifier to validate if is chairPerson
*/
modifier isChairPerson() {
require(
msg.sender == chairPerson,
"Only chairPerson can give right to vote."
);
_;
}
/**
* @dev Modifier to validate if sender has vote right
*/
modifier hasVoteRight() {
require(voters[msg.sender].weight != 0, "Has no right to vote");
_;
}
/**
* @dev Set chairPerson and give him voting rights
*/
constructor() public {
chairPerson = msg.sender;
voters[chairPerson].weight = 1;
}
/**
* @dev Creates and saves new proposal
* @param _name name of proposal
*/
function _createProposal(string memory _name, address _owner) internal {
proposals.push(Proposal({
owner: _owner,
name: _name,
voteCount: 0
}));
emit proposalSubmited(proposalCount);
proposalCount++;
}
/**
* @dev Sends a new proposal to be saved
* @param _name Name of proposal
*/
function sendProposal(string memory _name) public hasVoteRight {
_createProposal(_name, msg.sender);
}
/**
* @dev Give 'voter' the right to vote on this ballot. May only be called by 'chairPerson'.
* @param _voter address of voter
*/
function giveRightToVote(address _voter) public isChairPerson {
require(
!voters[_voter].voted,
"The voter already voted."
);
require(voters[_voter].weight == 0, "Voter aready has right to vote");
voters[_voter].weight = 1;
}
/**
* @dev Delegate your vote to the voter 'to'.
* @param _to address to which vote is delegated
*/
function delegate(address _to) public hasVoteRight {
Voter storage sender = voters[msg.sender];
require(!sender.voted, "You already voted.");
require(_to != msg.sender, "Self-delegation is disallowed.");
sender.voted = true;
sender.delegate = _to;
Voter storage delegate_ = voters[_to];
if (delegate_.voted) {
// If the delegate already voted,
// directly add to the number of votes
proposals[delegate_.vote].voteCount += sender.weight;
emit proposalVoted(delegate_.vote);
} else {
// If the delegate did not vote yet,
// add to her weight.
delegate_.weight += sender.weight;
}
}
/**
* @dev Give your vote (including votes delegated to you) to proposal 'proposals[proposal].name'.
* @param _proposal index of proposal in the proposals array
*/
function vote(uint _proposal) public hasVoteRight {
Voter storage sender = voters[msg.sender];
require(!sender.voted, "Already voted.");
sender.voted = true;
sender.vote = _proposal;
// If 'proposal' is out of the range of the array,
// this will throw automatically and revert all
// changes.
proposals[_proposal].voteCount += sender.weight;
emit proposalVoted(_proposal);
}
/**
* @dev Computes the winning proposal taking all previous votes into account.
* @return winningProposal_ index of winning proposal in the proposals array
*/
function winningProposal() public view
returns (uint winningProposal_)
{
uint winningVoteCount = 0;
for (uint p = 0; p < proposals.length; p++) {
if (proposals[p].voteCount > winningVoteCount) {
winningVoteCount = proposals[p].voteCount;
winningProposal_ = p;
}
}
}
/**
* @dev Calls winningProposal() function to get the index of the winner contained in the proposals array and then
* @return winnerName_ the name of the winner
*/
function winnerName() public view
returns (string memory winnerName_)
{
winnerName_ = proposals[winningProposal()].name;
}
} | contract Ballot {
struct Voter {
uint weight; // weight is accumulated by delegation
bool voted; // if true, that person already voted
address delegate; // person delegated to
uint vote; // index of the voted proposal
}
struct Proposal {
address owner; // address that created the proposal
// If you can limit the length to a certain number of bytes,
// always use one of bytes1 to bytes32 because they are much cheaper
string name; // short name
uint voteCount; // number of accumulated votes
}
address public chairPerson;
uint public proposalCount;
Proposal[] public proposals;
mapping(address => Voter) public voters;
event proposalSubmited(
uint proposalIndex
);
event proposalVoted(
uint proposalIndex
);
/**
* @dev Modifier to validate if is chairPerson
*/
modifier isChairPerson() {
require(
msg.sender == chairPerson,
"Only chairPerson can give right to vote."
);
_;
}
/**
* @dev Modifier to validate if sender has vote right
*/
modifier hasVoteRight() {
require(voters[msg.sender].weight != 0, "Has no right to vote");
_;
}
/**
* @dev Set chairPerson and give him voting rights
*/
constructor() public {
chairPerson = msg.sender;
voters[chairPerson].weight = 1;
}
/**
* @dev Creates and saves new proposal
* @param _name name of proposal
*/
function _createProposal(string memory _name, address _owner) internal {
proposals.push(Proposal({
owner: _owner,
name: _name,
voteCount: 0
}));
emit proposalSubmited(proposalCount);
proposalCount++;
}
/**
* @dev Sends a new proposal to be saved
* @param _name Name of proposal
*/
function sendProposal(string memory _name) public hasVoteRight {
_createProposal(_name, msg.sender);
}
/**
* @dev Give 'voter' the right to vote on this ballot. May only be called by 'chairPerson'.
* @param _voter address of voter
*/
function giveRightToVote(address _voter) public isChairPerson {
require(
!voters[_voter].voted,
"The voter already voted."
);
require(voters[_voter].weight == 0, "Voter aready has right to vote");
voters[_voter].weight = 1;
}
/**
* @dev Delegate your vote to the voter 'to'.
* @param _to address to which vote is delegated
*/
function delegate(address _to) public hasVoteRight {
Voter storage sender = voters[msg.sender];
require(!sender.voted, "You already voted.");
require(_to != msg.sender, "Self-delegation is disallowed.");
sender.voted = true;
sender.delegate = _to;
Voter storage delegate_ = voters[_to];
if (delegate_.voted) {
// If the delegate already voted,
// directly add to the number of votes
proposals[delegate_.vote].voteCount += sender.weight;
emit proposalVoted(delegate_.vote);
} else {
// If the delegate did not vote yet,
// add to her weight.
delegate_.weight += sender.weight;
}
}
/**
* @dev Give your vote (including votes delegated to you) to proposal 'proposals[proposal].name'.
* @param _proposal index of proposal in the proposals array
*/
function vote(uint _proposal) public hasVoteRight {
Voter storage sender = voters[msg.sender];
require(!sender.voted, "Already voted.");
sender.voted = true;
sender.vote = _proposal;
// If 'proposal' is out of the range of the array,
// this will throw automatically and revert all
// changes.
proposals[_proposal].voteCount += sender.weight;
emit proposalVoted(_proposal);
}
/**
* @dev Computes the winning proposal taking all previous votes into account.
* @return winningProposal_ index of winning proposal in the proposals array
*/
function winningProposal() public view
returns (uint winningProposal_)
{
uint winningVoteCount = 0;
for (uint p = 0; p < proposals.length; p++) {
if (proposals[p].voteCount > winningVoteCount) {
winningVoteCount = proposals[p].voteCount;
winningProposal_ = p;
}
}
}
/**
* @dev Calls winningProposal() function to get the index of the winner contained in the proposals array and then
* @return winnerName_ the name of the winner
*/
function winnerName() public view
returns (string memory winnerName_)
{
winnerName_ = proposals[winningProposal()].name;
}
} | 26,727 |
121 | // Convert the RCN into MANA using the designated and save the received MANA | uint256 boughtMana = convertSafe(mortgage.tokenConverter, rcn, mana, loanAmount);
delete mortgage.tokenConverter;
| uint256 boughtMana = convertSafe(mortgage.tokenConverter, rcn, mana, loanAmount);
delete mortgage.tokenConverter;
| 50,080 |
84 | // Internal function to get the inverted rate, if any, and mark an inverted key as frozen if either limits are reached. currencyKey The price key to lookup rate The rate for the given price key / | function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) {
// if an inverse mapping exists, adjust the price accordingly
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint <= 0) {
return rate;
}
// set the rate to the current rate initially (if it's frozen, this is what will be returned)
uint newInverseRate = rates[currencyKey];
// get the new inverted rate if not frozen
if (!inverse.frozen) {
uint doubleEntryPoint = inverse.entryPoint.mul(2);
if (doubleEntryPoint <= rate) {
// avoid negative numbers for unsigned ints, so set this to 0
// which by the requirement that lowerLimit be > 0 will
// cause this to freeze the price to the lowerLimit
newInverseRate = 0;
} else {
newInverseRate = doubleEntryPoint.sub(rate);
}
// now if new rate hits our limits, set it to the limit and freeze
if (newInverseRate >= inverse.upperLimit) {
newInverseRate = inverse.upperLimit;
} else if (newInverseRate <= inverse.lowerLimit) {
newInverseRate = inverse.lowerLimit;
}
if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) {
inverse.frozen = true;
emit InversePriceFrozen(currencyKey);
}
}
return newInverseRate;
}
| function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) {
// if an inverse mapping exists, adjust the price accordingly
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint <= 0) {
return rate;
}
// set the rate to the current rate initially (if it's frozen, this is what will be returned)
uint newInverseRate = rates[currencyKey];
// get the new inverted rate if not frozen
if (!inverse.frozen) {
uint doubleEntryPoint = inverse.entryPoint.mul(2);
if (doubleEntryPoint <= rate) {
// avoid negative numbers for unsigned ints, so set this to 0
// which by the requirement that lowerLimit be > 0 will
// cause this to freeze the price to the lowerLimit
newInverseRate = 0;
} else {
newInverseRate = doubleEntryPoint.sub(rate);
}
// now if new rate hits our limits, set it to the limit and freeze
if (newInverseRate >= inverse.upperLimit) {
newInverseRate = inverse.upperLimit;
} else if (newInverseRate <= inverse.lowerLimit) {
newInverseRate = inverse.lowerLimit;
}
if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) {
inverse.frozen = true;
emit InversePriceFrozen(currencyKey);
}
}
return newInverseRate;
}
| 52,499 |
30 | // require(allowances[_id][_from][msg.sender] >= _value); | allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
| allowances[_id][_from][msg.sender] = allowances[_id][_from][msg.sender].sub(_value);
| 38,489 |
122 | // View function to see pending ERC20s for a user. | function pending(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accERC20PerShare = pool.accERC20PerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 lastBlock = block.number < endBlock ? block.number : endBlock;
uint256 nrOfBlocks = lastBlock.sub(pool.lastRewardBlock);
uint256 erc20Reward = nrOfBlocks.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accERC20PerShare = accERC20PerShare.add(erc20Reward.mul(1e36).div(lpSupply));
}
return user.amount.mul(accERC20PerShare).div(1e36).sub(user.rewardDebt);
}
| function pending(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accERC20PerShare = pool.accERC20PerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 lastBlock = block.number < endBlock ? block.number : endBlock;
uint256 nrOfBlocks = lastBlock.sub(pool.lastRewardBlock);
uint256 erc20Reward = nrOfBlocks.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accERC20PerShare = accERC20PerShare.add(erc20Reward.mul(1e36).div(lpSupply));
}
return user.amount.mul(accERC20PerShare).div(1e36).sub(user.rewardDebt);
}
| 3,720 |
9 | // The recipient of who gets the royalty. | address private royaltyRecipient;
| address private royaltyRecipient;
| 19,278 |
62 | // make sure that the message sender holds this key ID | require(IKeyVault(keyVault).keyBalanceOf(msg.sender, rootKeyId, false) > 0, 'KEY_NOT_HELD');
| require(IKeyVault(keyVault).keyBalanceOf(msg.sender, rootKeyId, false) > 0, 'KEY_NOT_HELD');
| 15,653 |
6 | // i : request index in array | Request storage curr_request = requests[i];
require( backers[msg.sender] ); // Should be a backer
require( ! curr_request.approvers[msg.sender] ); //Should not have voted on this request
curr_request.approvers[msg.sender] = true;
curr_request.yes_count++;
| Request storage curr_request = requests[i];
require( backers[msg.sender] ); // Should be a backer
require( ! curr_request.approvers[msg.sender] ); //Should not have voted on this request
curr_request.approvers[msg.sender] = true;
curr_request.yes_count++;
| 49,548 |
7 | // Methods /// | function setTokenId(
string memory tokenId_
| function setTokenId(
string memory tokenId_
| 31,408 |
25 | // Change amount of fee charged for every basket minted/ _newFeeNew fee amount/ return successOperation successful | function changeArrangerFee(uint _newFee) public onlyArranger returns (bool success) {
uint oldFee = arrangerFee;
arrangerFee = _newFee;
emit LogArrangerFeeChange(oldFee, arrangerFee);
return true;
}
| function changeArrangerFee(uint _newFee) public onlyArranger returns (bool success) {
uint oldFee = arrangerFee;
arrangerFee = _newFee;
emit LogArrangerFeeChange(oldFee, arrangerFee);
return true;
}
| 30,689 |
65 | // sets the manager of the contract | function setManager(address _manager) public onlyOwnerOrManager {
manager = _manager;
}
| function setManager(address _manager) public onlyOwnerOrManager {
manager = _manager;
}
| 35,453 |
278 | // 12. Process the payment to workout interest/principal split. | loan = _processPayment(loan, amountToLiquidate);
| loan = _processPayment(loan, amountToLiquidate);
| 30,014 |
2 | // list of probabilities for each trait type 0 - 6 are associated with head, breed, color, class, armor, offhand, mainhand | uint8[][7] public rarities;
| uint8[][7] public rarities;
| 56,660 |
0 | // This push is needed so we avoid index 0 causing bug of index-1 | stakeholders.push();
| stakeholders.push();
| 11,330 |
48 | // Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met._beneficiary Address performing the token purchase_weiAmount Value in wei involved in the purchase/ | function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
| function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
| 19,156 |
89 | // Approve `to` to operate on `tokenId` | * Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
| * Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
| 8,909 |
53 | // Business Logic to wrap already existing ERC721 Tokens to obtain a new NFT-Based EthItem.It raises the 'NewWrappedERC721Created' events. modelInitCallPayload The ABI-encoded input parameters to be passed to the model to phisically create the NFT.It changes according to the Model Version. ethItemAddress The address of the new EthItem ethItemInitResponse The ABI-encoded output response eventually received by the Model initialization procedure. / | function createWrappedERC721(address modelAddress, bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse);
| function createWrappedERC721(address modelAddress, bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse);
| 3,151 |
90 | // Set the age of contract's current value to block.timestamp. Note that this ensures an already signed, but now possibly invalid with regards to contract configurations, opPoke payload cannot be opPoke'd anymore. | _pokeData.age = uint32(block.timestamp);
| _pokeData.age = uint32(block.timestamp);
| 2,297 |
35 | // contributor => true if contribution has been claimed | mapping(address => bool) public claimed;
| mapping(address => bool) public claimed;
| 59,852 |
113 | // Set the new pair | uniswapV2Pair = newPair;
| uniswapV2Pair = newPair;
| 46,651 |
86 | // Binary search to estimate timestamp for block number/_block Block to find/max_epoch Don't go beyond this epoch/ return Approximate timestamp for block | function _find_block_epoch(uint _block, uint max_epoch) internal view returns (uint) {
// Binary search
uint _min = 0;
uint _max = max_epoch;
for (uint i = 0; i < 128; ++i) {
// Will be always enough for 128-bit numbers
if (_min >= _max) {
break;
}
uint _mid = (_min + _max + 1) / 2;
if (point_history[_mid].blk <= _block) {
_min = _mid;
} else {
_max = _mid - 1;
}
}
return _min;
}
| function _find_block_epoch(uint _block, uint max_epoch) internal view returns (uint) {
// Binary search
uint _min = 0;
uint _max = max_epoch;
for (uint i = 0; i < 128; ++i) {
// Will be always enough for 128-bit numbers
if (_min >= _max) {
break;
}
uint _mid = (_min + _max + 1) / 2;
if (point_history[_mid].blk <= _block) {
_min = _mid;
} else {
_max = _mid - 1;
}
}
return _min;
}
| 5,319 |
21 | // Load 8 byte from reversed public key at position 32 + i8 | assembly {
oneEigth := mload(add(reversed, add(32, mul(i, 8))))
}
| assembly {
oneEigth := mload(add(reversed, add(32, mul(i, 8))))
}
| 1,861 |
21 | // bonus | _bonusIcoTokenLocked = roundBonusLocked[1] * amountTokenIco / 100;
| _bonusIcoTokenLocked = roundBonusLocked[1] * amountTokenIco / 100;
| 4,376 |
66 | // The public sale hard cap of the fundraiser. |
uint constant TOKENS_HARD_CAP = 71250 * (10**3) * DECIMALS_FACTOR;
|
uint constant TOKENS_HARD_CAP = 71250 * (10**3) * DECIMALS_FACTOR;
| 48,323 |
76 | // check that from address holds the ticket | require(ticketOwners[_tokenId] == _from);
require((ticketsReceived[_to] + 1) <= 20);
| require(ticketOwners[_tokenId] == _from);
require((ticketsReceived[_to] + 1) <= 20);
| 14,617 |
6 | // NOTE: we will not update withdrawn, since a WithdrawExpired does not count towards normal withdrawals | states[channelId] = ChannelLibrary.State.Expired;
SafeERC20.transfer(channel.tokenAddr, msg.sender, toWithdraw);
emit LogChannelWithdrawExpired(channelId, toWithdraw);
| states[channelId] = ChannelLibrary.State.Expired;
SafeERC20.transfer(channel.tokenAddr, msg.sender, toWithdraw);
emit LogChannelWithdrawExpired(channelId, toWithdraw);
| 37,511 |
81 | // / | function initialize (address _contribution) onlyOwner {
require( _contribution != address(0) );
contribution = Contribution(_contribution);
atmToken = new ATMToken(tokenTotal);
//Start thawing process
setLockStartTime(now);
// alloc reserve token to fund account (50 billion)
lockToken(contribution.ethFundDeposit(), tokenToReserve);
lockToken(contribution.investorDeposit(), tokenToFounder);
//help founder&fund to claim first 1/6 ATMs
claimUserToken(contribution.investorDeposit());
claimFoundationToken();
LogRegister(_contribution, atmToken);
}
| function initialize (address _contribution) onlyOwner {
require( _contribution != address(0) );
contribution = Contribution(_contribution);
atmToken = new ATMToken(tokenTotal);
//Start thawing process
setLockStartTime(now);
// alloc reserve token to fund account (50 billion)
lockToken(contribution.ethFundDeposit(), tokenToReserve);
lockToken(contribution.investorDeposit(), tokenToFounder);
//help founder&fund to claim first 1/6 ATMs
claimUserToken(contribution.investorDeposit());
claimFoundationToken();
LogRegister(_contribution, atmToken);
}
| 46,456 |
114 | // now total rent payable is original amount minus calculated platform fee above | totalRentPayable = totalRentCost - totalPlatformFee;
| totalRentPayable = totalRentCost - totalPlatformFee;
| 22,928 |
7 | // Se transfiere los tokens ganados almacenados en el mapping s_rewardUnlocked | function claimReward() external nonReentrant{
require(s_rewardUnlocked[msg.sender] > 0, "Insufficient Unlocked Balance");
uint256 reward = s_rewardUnlocked[msg.sender];
s_rewardUnlocked[msg.sender] = 0;
bool success = rewardToken.transfer(msg.sender, reward);
require(success, "ClaimReward: Error tx");
}
| function claimReward() external nonReentrant{
require(s_rewardUnlocked[msg.sender] > 0, "Insufficient Unlocked Balance");
uint256 reward = s_rewardUnlocked[msg.sender];
s_rewardUnlocked[msg.sender] = 0;
bool success = rewardToken.transfer(msg.sender, reward);
require(success, "ClaimReward: Error tx");
}
| 23,192 |
91 | // deposit token to bond ALD./_type The type of deposited token./_token The address of token./_amount The amount of token. | function deposit(
ReserveType _type,
address _token,
uint256 _amount
) external returns (uint256);
| function deposit(
ReserveType _type,
address _token,
uint256 _amount
) external returns (uint256);
| 10,861 |
60 | // after the successful transfer - check if receiver supports ERC1363Receiver and execute a callback handler `onTransferReceived`, reverting whole transaction on any error | _notifyTransferred(_from, _to, _value, _data, false);
| _notifyTransferred(_from, _to, _value, _data, false);
| 18,861 |
161 | // Eyes N°6 => Color White/Yellow | function item_6() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.YELLOW);
}
| function item_6() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.YELLOW);
}
| 33,947 |
889 | // This module allows Pools to access historical pricing information. It uses a 1024 long circular buffer to store past data, where the data within each sample is the result ofaccumulating live data for no more than two minutes. Therefore, assuming the worst case scenario where new data isupdated in every single block, the oldest samples in the buffer (and therefore largest queryable period) willbe slightly over 34 hours old. Usage of this module requires the caller to keep track of two variables: the latest circular buffer index, and thetimestamp when the index last changed. Aditionally, access to the latest circular | abstract contract PoolPriceOracle is IPoolPriceOracle, IPriceOracle {
using Buffer for uint256;
using Samples for bytes32;
// Each sample in the buffer accumulates information for up to 2 minutes. This is simply to reduce the size of the
// buffer: small time deviations will not have any significant effect.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_SAMPLE_DURATION = 2 minutes;
// We use a mapping to simulate an array: the buffer won't grow or shrink, and since we will always use valid
// indexes using a mapping saves gas by skipping the bounds checks.
mapping(uint256 => bytes32) internal _samples;
// IPoolPriceOracle
function getSample(uint256 index)
external
view
override
returns (
int256 logPairPrice,
int256 accLogPairPrice,
int256 logBptPrice,
int256 accLogBptPrice,
int256 logInvariant,
int256 accLogInvariant,
uint256 timestamp
)
{
_require(index < Buffer.SIZE, Errors.ORACLE_INVALID_INDEX);
bytes32 sample = _getSample(index);
return sample.unpack();
}
function getTotalSamples() external pure override returns (uint256) {
return Buffer.SIZE;
}
/**
* @dev Manually dirty oracle sample storage slots with dummy data, to reduce the gas cost of the future swaps
* that will initialize them. This function is only useful before the oracle has been fully initialized.
*
* `endIndex` is non-inclusive.
*/
function dirtyUninitializedOracleSamples(uint256 startIndex, uint256 endIndex) external {
_require(startIndex < endIndex && endIndex <= Buffer.SIZE, Errors.OUT_OF_BOUNDS);
// Uninitialized samples are identified by a zero timestamp -- all other fields are ignored,
// so any non-zero value with a zero timestamp suffices.
bytes32 initSample = Samples.pack(1, 0, 0, 0, 0, 0, 0);
for (uint256 i = startIndex; i < endIndex; i++) {
if (_samples[i].timestamp() == 0) {
_samples[i] = initSample;
}
}
}
// IPriceOracle
function getLargestSafeQueryWindow() external pure override returns (uint256) {
return 34 hours;
}
function getLatest(Variable variable) external view override returns (uint256) {
return QueryProcessor.getInstantValue(_samples, variable, _getOracleIndex());
}
function getTimeWeightedAverage(OracleAverageQuery[] memory queries)
external
view
override
returns (uint256[] memory results)
{
results = new uint256[](queries.length);
uint256 latestIndex = _getOracleIndex();
for (uint256 i = 0; i < queries.length; ++i) {
results[i] = QueryProcessor.getTimeWeightedAverage(_samples, queries[i], latestIndex);
}
}
function getPastAccumulators(OracleAccumulatorQuery[] memory queries)
external
view
override
returns (int256[] memory results)
{
results = new int256[](queries.length);
uint256 latestIndex = _getOracleIndex();
OracleAccumulatorQuery memory query;
for (uint256 i = 0; i < queries.length; ++i) {
query = queries[i];
results[i] = _getPastAccumulator(query.variable, latestIndex, query.ago);
}
}
// Internal functions
/**
* @dev Processes new price and invariant data, updating the latest sample or creating a new one.
*
* Receives the new logarithms of values to store: `logPairPrice`, `logBptPrice` and `logInvariant`, as well the
* index of the latest sample and the timestamp of its creation.
*
* Returns the index of the latest sample. If different from `latestIndex`, the caller should also store the
* timestamp, and pass it on future calls to this function.
*/
function _processPriceData(
uint256 latestSampleCreationTimestamp,
uint256 latestIndex,
int256 logPairPrice,
int256 logBptPrice,
int256 logInvariant
) internal returns (uint256) {
// Read latest sample, and compute the next one by updating it with the newly received data.
bytes32 sample = _getSample(latestIndex).update(logPairPrice, logBptPrice, logInvariant, block.timestamp);
// We create a new sample if more than _MAX_SAMPLE_DURATION seconds have elapsed since the creation of the
// latest one. In other words, no sample accumulates data over a period larger than _MAX_SAMPLE_DURATION.
bool newSample = block.timestamp - latestSampleCreationTimestamp >= _MAX_SAMPLE_DURATION;
latestIndex = newSample ? latestIndex.next() : latestIndex;
// Store the updated or new sample.
_samples[latestIndex] = sample;
return latestIndex;
}
function _getPastAccumulator(
IPriceOracle.Variable variable,
uint256 latestIndex,
uint256 ago
) internal view returns (int256) {
return QueryProcessor.getPastAccumulator(_samples, variable, latestIndex, ago);
}
function _findNearestSample(
uint256 lookUpDate,
uint256 offset,
uint256 length
) internal view returns (bytes32 prev, bytes32 next) {
return QueryProcessor.findNearestSample(_samples, lookUpDate, offset, length);
}
/**
* @dev Returns the sample that corresponds to a given `index`.
*
* Using this function instead of accessing storage directly results in denser bytecode (since the storage slot is
* only computed here).
*/
function _getSample(uint256 index) internal view returns (bytes32) {
return _samples[index];
}
/**
* @dev Virtual function to be implemented by derived contracts. Must return the current index of the oracle
* circular buffer.
*/
function _getOracleIndex() internal view virtual returns (uint256);
}
| abstract contract PoolPriceOracle is IPoolPriceOracle, IPriceOracle {
using Buffer for uint256;
using Samples for bytes32;
// Each sample in the buffer accumulates information for up to 2 minutes. This is simply to reduce the size of the
// buffer: small time deviations will not have any significant effect.
// solhint-disable not-rely-on-time
uint256 private constant _MAX_SAMPLE_DURATION = 2 minutes;
// We use a mapping to simulate an array: the buffer won't grow or shrink, and since we will always use valid
// indexes using a mapping saves gas by skipping the bounds checks.
mapping(uint256 => bytes32) internal _samples;
// IPoolPriceOracle
function getSample(uint256 index)
external
view
override
returns (
int256 logPairPrice,
int256 accLogPairPrice,
int256 logBptPrice,
int256 accLogBptPrice,
int256 logInvariant,
int256 accLogInvariant,
uint256 timestamp
)
{
_require(index < Buffer.SIZE, Errors.ORACLE_INVALID_INDEX);
bytes32 sample = _getSample(index);
return sample.unpack();
}
function getTotalSamples() external pure override returns (uint256) {
return Buffer.SIZE;
}
/**
* @dev Manually dirty oracle sample storage slots with dummy data, to reduce the gas cost of the future swaps
* that will initialize them. This function is only useful before the oracle has been fully initialized.
*
* `endIndex` is non-inclusive.
*/
function dirtyUninitializedOracleSamples(uint256 startIndex, uint256 endIndex) external {
_require(startIndex < endIndex && endIndex <= Buffer.SIZE, Errors.OUT_OF_BOUNDS);
// Uninitialized samples are identified by a zero timestamp -- all other fields are ignored,
// so any non-zero value with a zero timestamp suffices.
bytes32 initSample = Samples.pack(1, 0, 0, 0, 0, 0, 0);
for (uint256 i = startIndex; i < endIndex; i++) {
if (_samples[i].timestamp() == 0) {
_samples[i] = initSample;
}
}
}
// IPriceOracle
function getLargestSafeQueryWindow() external pure override returns (uint256) {
return 34 hours;
}
function getLatest(Variable variable) external view override returns (uint256) {
return QueryProcessor.getInstantValue(_samples, variable, _getOracleIndex());
}
function getTimeWeightedAverage(OracleAverageQuery[] memory queries)
external
view
override
returns (uint256[] memory results)
{
results = new uint256[](queries.length);
uint256 latestIndex = _getOracleIndex();
for (uint256 i = 0; i < queries.length; ++i) {
results[i] = QueryProcessor.getTimeWeightedAverage(_samples, queries[i], latestIndex);
}
}
function getPastAccumulators(OracleAccumulatorQuery[] memory queries)
external
view
override
returns (int256[] memory results)
{
results = new int256[](queries.length);
uint256 latestIndex = _getOracleIndex();
OracleAccumulatorQuery memory query;
for (uint256 i = 0; i < queries.length; ++i) {
query = queries[i];
results[i] = _getPastAccumulator(query.variable, latestIndex, query.ago);
}
}
// Internal functions
/**
* @dev Processes new price and invariant data, updating the latest sample or creating a new one.
*
* Receives the new logarithms of values to store: `logPairPrice`, `logBptPrice` and `logInvariant`, as well the
* index of the latest sample and the timestamp of its creation.
*
* Returns the index of the latest sample. If different from `latestIndex`, the caller should also store the
* timestamp, and pass it on future calls to this function.
*/
function _processPriceData(
uint256 latestSampleCreationTimestamp,
uint256 latestIndex,
int256 logPairPrice,
int256 logBptPrice,
int256 logInvariant
) internal returns (uint256) {
// Read latest sample, and compute the next one by updating it with the newly received data.
bytes32 sample = _getSample(latestIndex).update(logPairPrice, logBptPrice, logInvariant, block.timestamp);
// We create a new sample if more than _MAX_SAMPLE_DURATION seconds have elapsed since the creation of the
// latest one. In other words, no sample accumulates data over a period larger than _MAX_SAMPLE_DURATION.
bool newSample = block.timestamp - latestSampleCreationTimestamp >= _MAX_SAMPLE_DURATION;
latestIndex = newSample ? latestIndex.next() : latestIndex;
// Store the updated or new sample.
_samples[latestIndex] = sample;
return latestIndex;
}
function _getPastAccumulator(
IPriceOracle.Variable variable,
uint256 latestIndex,
uint256 ago
) internal view returns (int256) {
return QueryProcessor.getPastAccumulator(_samples, variable, latestIndex, ago);
}
function _findNearestSample(
uint256 lookUpDate,
uint256 offset,
uint256 length
) internal view returns (bytes32 prev, bytes32 next) {
return QueryProcessor.findNearestSample(_samples, lookUpDate, offset, length);
}
/**
* @dev Returns the sample that corresponds to a given `index`.
*
* Using this function instead of accessing storage directly results in denser bytecode (since the storage slot is
* only computed here).
*/
function _getSample(uint256 index) internal view returns (bytes32) {
return _samples[index];
}
/**
* @dev Virtual function to be implemented by derived contracts. Must return the current index of the oracle
* circular buffer.
*/
function _getOracleIndex() internal view virtual returns (uint256);
}
| 56,693 |
25 | // Mints new liquidity tokens to `to` based on how much `token0` or `token1` has been deposited.The token transferred is the one that the Pair does not have a non-zero inactive liquidity balance for.Expects only one token to be deposited, so that it can be paired with the other token's inactive liquidity. The token deposits are deduced to be the delta between token balance before and after the transfers in order to account for unusual tokens. amountIn The amount of tokens that should be transferred in from the user to The account that receives the newly minted liquidity tokensreturn liquidityOut THe | function mintWithReservoir(uint256 amountIn, address to) external returns (uint256 liquidityOut);
| function mintWithReservoir(uint256 amountIn, address to) external returns (uint256 liquidityOut);
| 28,756 |
11 | // Utility function to calculate fee charges to a given amountamount Total transaction amount poolAmount Total pool amount / | function getCollectable(uint256 amount, uint256 poolAmount) external override view returns (uint256 totalFee) {
uint256 baseFee = amount.mul(_feeBaseValue).div(10**uint256(_feeDecimals));
uint256 dynamicFee = _getDynamicFees(amount, poolAmount);
return baseFee.add(dynamicFee);
}
| function getCollectable(uint256 amount, uint256 poolAmount) external override view returns (uint256 totalFee) {
uint256 baseFee = amount.mul(_feeBaseValue).div(10**uint256(_feeDecimals));
uint256 dynamicFee = _getDynamicFees(amount, poolAmount);
return baseFee.add(dynamicFee);
}
| 75,707 |
186 | // Whether any given car (tokenId) is special / | mapping(uint256 => bool) public isSpecial;
| mapping(uint256 => bool) public isSpecial;
| 56,239 |
300 | // Process strategy DHW, including reallocationOnly executed when reallocation is set for the DHW strat Strategy address slippages Array of slippage values processReallocationData Reallocation data (see ProcessReallocationData)return Received withdrawn reallocation / | function _doHardWorkReallocation(
address strat,
uint256[] memory slippages,
ProcessReallocationData memory processReallocationData
| function _doHardWorkReallocation(
address strat,
uint256[] memory slippages,
ProcessReallocationData memory processReallocationData
| 34,773 |
215 | // Not as good as minting a specific tokenId, but will behave the same at the start allowing you to explicitly mint some tokens at launch. | function _mintAtIndex(address to, uint index) internal virtual {
require(_msgSender() == tx.origin, "Contracts cannot mint");
require(to != address(0), "ERC721: mint to the zero address");
require(_numAvailableTokens >= 1, "ERC721r: minting more tokens than available");
uint tokenId = getAvailableTokenAtIndex(index, _numAvailableTokens);
--_numAvailableTokens;
_mintIdWithoutBalanceUpdate(to, tokenId);
_balances[to] += 1;
}
| function _mintAtIndex(address to, uint index) internal virtual {
require(_msgSender() == tx.origin, "Contracts cannot mint");
require(to != address(0), "ERC721: mint to the zero address");
require(_numAvailableTokens >= 1, "ERC721r: minting more tokens than available");
uint tokenId = getAvailableTokenAtIndex(index, _numAvailableTokens);
--_numAvailableTokens;
_mintIdWithoutBalanceUpdate(to, tokenId);
_balances[to] += 1;
}
| 6,849 |
49 | // Function to change the ACO pools penalties percentages on withdrawing open positions.Only can be called by a pool admin. withdrawOpenPositionPenalties Array of the penalties percentages on withdrawing open positions to be set. acoPools Array of ACO pools addresses. / | function setWithdrawOpenPositionPenaltyOnAcoPool(uint256[] calldata withdrawOpenPositionPenalties, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setWithdrawOpenPositionPenalty.selector, withdrawOpenPositionPenalties, acoPools);
}
| function setWithdrawOpenPositionPenaltyOnAcoPool(uint256[] calldata withdrawOpenPositionPenalties, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setWithdrawOpenPositionPenalty.selector, withdrawOpenPositionPenalties, acoPools);
}
| 35,689 |
61 | // Withdraw an NFT by committing a valid signature_beneficiary - Beneficiary's address_contract - NFT contract' address_tokenId - Token id_expires - Expiration of the signature_userId - User id_signature - Signature/ | function withdraw(
address _beneficiary,
address _contract,
uint256 _tokenId,
uint256 _expires,
bytes calldata _userId,
bytes calldata _signature
| function withdraw(
address _beneficiary,
address _contract,
uint256 _tokenId,
uint256 _expires,
bytes calldata _userId,
bytes calldata _signature
| 24,603 |
0 | // Implementation of the {IController} interface./ ========== CONSTANTS ========== //Maximum vault creator fee - 20% | uint256 public constant MAX_VAULT_CREATOR_FEE = 20_00;
| uint256 public constant MAX_VAULT_CREATOR_FEE = 20_00;
| 47,967 |
38 | // worth 5x Eth then the price for OMG would be 510e18 or Exp({mantissa: 5000000000000000000}).map: assetAddress -> Exp / | mapping(address => Exp) public _assetPrices;
constructor(address _poster) public {
anchorAdmin = msg.sender;
| mapping(address => Exp) public _assetPrices;
constructor(address _poster) public {
anchorAdmin = msg.sender;
| 36,507 |
19 | // LogicConstraints.alwaysRevert(_NAME.concatenate("token supply cap cannot mutate")); | require(
totalSupply().add(amount) <= cap(),
"supply cap exceeded"
);
| require(
totalSupply().add(amount) <= cap(),
"supply cap exceeded"
);
| 35,678 |
6 | // converts spefied amount of Liquidity tokens to Basic Token and returns to user (withdraw). The balance of the User (msg.sender) is decreased by specified amount ofLiquidity tokens. Resulted amount of tokens are transferred to msg.sender_amount - amount of liquidity tokens to exchange to Basic token. / | function withdraw(uint256 _amount) external virtual{
_withdraw(_amount, msg.sender);
}
| function withdraw(uint256 _amount) external virtual{
_withdraw(_amount, msg.sender);
}
| 13,909 |
362 | // Event emitted when assets are deposited | event Deposited(
address indexed operator,
address indexed to,
address indexed token,
uint256 amount,
address referrer
);
| event Deposited(
address indexed operator,
address indexed to,
address indexed token,
uint256 amount,
address referrer
);
| 36,079 |
49 | // get pointer to metadata | metadataIndex := calldataload(add(metadata, mul(sub(i, 0x01), 0x20)))
| metadataIndex := calldataload(add(metadata, mul(sub(i, 0x01), 0x20)))
| 43,050 |
52 | // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506);for Sushi testnet | uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
| uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
| 37,569 |
15 | // add new platform usernewUser to addname name of the useruserTypetype of the user, enterprise, validator or data subscriber/ | function addUser(address newUser, string memory name, UserType userType) public isController() {
require(!userMap[newUser][userType], "Members:addUser - This user already exist.");
user[newUser][userType] = name;
userMap[newUser][userType] = true;
if (userType == UserType.DataSubscriber)
dataSubscribers.push(newUser);
// dataSubscriberCount++;
else if (userType == UserType.Validator)
validators.push(newUser);
// validatorCount++;
else if (userType == UserType.Enterprise)
enterprises.push(newUser);
// enterpriseCount++;
// userAddersses.push(newUser);
emit UserAdded(newUser, name, userType);
}
| function addUser(address newUser, string memory name, UserType userType) public isController() {
require(!userMap[newUser][userType], "Members:addUser - This user already exist.");
user[newUser][userType] = name;
userMap[newUser][userType] = true;
if (userType == UserType.DataSubscriber)
dataSubscribers.push(newUser);
// dataSubscriberCount++;
else if (userType == UserType.Validator)
validators.push(newUser);
// validatorCount++;
else if (userType == UserType.Enterprise)
enterprises.push(newUser);
// enterpriseCount++;
// userAddersses.push(newUser);
emit UserAdded(newUser, name, userType);
}
| 13,688 |
47 | // 开始释放时间 | uint startTime;
| uint startTime;
| 26,284 |
10 | // solhint-disable private-vars-leading-underscore, var-name-mixedcase | uint256 private immutable UNIT_0;
uint256 private immutable UNIT_1;
uint256 private immutable TO_WAD_0;
uint256 private immutable TO_WAD_1;
uint256 private immutable TO_WAD_ORACLE_0;
uint256 private immutable TO_WAD_ORACLE_1;
address public immutable pool;
address public immutable priceFeed0;
address public immutable priceFeed1;
| uint256 private immutable UNIT_0;
uint256 private immutable UNIT_1;
uint256 private immutable TO_WAD_0;
uint256 private immutable TO_WAD_1;
uint256 private immutable TO_WAD_ORACLE_0;
uint256 private immutable TO_WAD_ORACLE_1;
address public immutable pool;
address public immutable priceFeed0;
address public immutable priceFeed1;
| 27,818 |
19 | // restore dev fee | devFee = baseDevFee;
emit Transfer(from, to, tTransferAmount);
| devFee = baseDevFee;
emit Transfer(from, to, tTransferAmount);
| 11,147 |
17 | // Add/remove any number of addresses whose funds get reflected/reflectCuts ReflectCut[] | function reflectCut(
SLib.ReflectCut_[] calldata reflectCuts
| function reflectCut(
SLib.ReflectCut_[] calldata reflectCuts
| 7,508 |
44 | // endIco closes down the ICO/ | function endIco() internal {
currentStage = Stages.icoEnd;
// Transfer any remaining tokens
if(remainingTokens > 0)
balances[owner] = balances[owner].add(remainingTokens);
// transfer any remaining ETH balance in the contract to the owner
owner.transfer(address(this).balance);
}
| function endIco() internal {
currentStage = Stages.icoEnd;
// Transfer any remaining tokens
if(remainingTokens > 0)
balances[owner] = balances[owner].add(remainingTokens);
// transfer any remaining ETH balance in the contract to the owner
owner.transfer(address(this).balance);
}
| 26,198 |
101 | // Given an bytes32 input, injects return/sub values if specified/_param The original input value/_mapType Indicated the type of the input in paramMapping/_subData Array of subscription data we can replace the input value with/_returnValues Array of subscription data we can replace the input value with | function _parseParamABytes32(
bytes32 _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
| function _parseParamABytes32(
bytes32 _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
| 2,655 |
112 | // File: contracts/common/HasOwners.sol |
pragma solidity 0.7.1;
|
pragma solidity 0.7.1;
| 25,516 |
33 | // refund the relayer any native asset sent to this contract | if (msg.value > 0) {
payable(msg.sender).transfer(msg.value);
}
| if (msg.value > 0) {
payable(msg.sender).transfer(msg.value);
}
| 8,996 |
69 | // Transfer the amount of token to the buyer | balances[owner] = balances[owner].sub(tokens);
balances[beneficiary] = balances[beneficiary].add(tokens);
Transfer(owner, beneficiary, tokens);
| balances[owner] = balances[owner].sub(tokens);
balances[beneficiary] = balances[beneficiary].add(tokens);
Transfer(owner, beneficiary, tokens);
| 39,221 |
22 | // get addresses array of token path | function getBancorPathForAssets(ERC20 _from, ERC20 _to) public view returns(address[] memory){
BancorNetworkInterface bancorNetwork = BancorNetworkInterface(
getBancorContractAddresByName("BancorNetwork")
);
address[] memory path = bancorNetwork.conversionPath(_from, _to);
return path;
}
| function getBancorPathForAssets(ERC20 _from, ERC20 _to) public view returns(address[] memory){
BancorNetworkInterface bancorNetwork = BancorNetworkInterface(
getBancorContractAddresByName("BancorNetwork")
);
address[] memory path = bancorNetwork.conversionPath(_from, _to);
return path;
}
| 16,502 |
174 | // Safely transfers the ownership of a given token ID to another addressIf the target address is a contract, it must implement `onERC721Received`,which is called upon a safe transfer, and return the magic value`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,the transfer is reverted.Requires the msg.sender to be the owner, approved, or operator _from current owner of the token _to address to receive the ownership of the given token ID _tokenId uint256 ID of the token to be transferred / | function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
_checkTransfer(_tokenId);
super.safeTransferFrom(_from, _to, _tokenId);
}
| function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
_checkTransfer(_tokenId);
super.safeTransferFrom(_from, _to, _tokenId);
}
| 32,599 |
9 | // L'administrateur de vote met fin à la session d'enregistrement des propositions. / | function EndEnregristrement () public onlyOwner{
require(Status==WorkflowStatus.ProposalsRegistrationStarted);
emit ProposalsRegistrationEnded();
Status = WorkflowStatus.ProposalsRegistrationEnded;
emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted,WorkflowStatus.ProposalsRegistrationEnded);
}
| function EndEnregristrement () public onlyOwner{
require(Status==WorkflowStatus.ProposalsRegistrationStarted);
emit ProposalsRegistrationEnded();
Status = WorkflowStatus.ProposalsRegistrationEnded;
emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted,WorkflowStatus.ProposalsRegistrationEnded);
}
| 48,316 |
45 | // Gets the approved address to take ownership of a given unicorn ID_unicornId uint256 ID of the unicorn to query the approval of return address currently approved to take ownership of the given unicorn ID/ | function approvedFor(uint256 _unicornId) public view returns (address) {
return unicornApprovals[_unicornId];
}
| function approvedFor(uint256 _unicornId) public view returns (address) {
return unicornApprovals[_unicornId];
}
| 28,114 |
18 | // Retrieve the transfer in question and perform the transfer. | _transfer(transfers[i]);
| _transfer(transfers[i]);
| 33,424 |
16 | // Constructor for Odin creationInitially assigns the totalSupply to the contract creator/ | function OdinToken() public {
// owner of this contract
owner = msg.sender;
symbol = "ODIN";
name = "ODIN Token";
decimals = 18;
_whitelistAll=false;
_totalSupply = 100000000000000000000000;
balances[owner].balance = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| function OdinToken() public {
// owner of this contract
owner = msg.sender;
symbol = "ODIN";
name = "ODIN Token";
decimals = 18;
_whitelistAll=false;
_totalSupply = 100000000000000000000000;
balances[owner].balance = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 16,103 |
45 | // Pair Details | mapping (uint256 => address) private pairs;
mapping (uint256 => address) private tokens;
uint256 private pairsLength;
address public WETH;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
| mapping (uint256 => address) private pairs;
mapping (uint256 => address) private tokens;
uint256 private pairsLength;
address public WETH;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
| 32,122 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.