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 |
|---|---|---|---|---|
480 | // NOTE: the remainder after division can be retrieved by the bounty provider |
if (award < bountyData.getBountyHunterDeposit(bountyId)) {
return bountyData.getBountyHunterDeposit(bountyId);
}
|
if (award < bountyData.getBountyHunterDeposit(bountyId)) {
return bountyData.getBountyHunterDeposit(bountyId);
}
| 41,337 |
26 | // Revert if used value > 100% of msg.value | if (msgValueUsed>100)
revert("Interpreter: Rule is spending more msg.value than received!");
| if (msgValueUsed>100)
revert("Interpreter: Rule is spending more msg.value than received!");
| 17,165 |
3 | // Accept transferOwnership. / | function acceptOwnership() public {
if (msg.sender == newOwner) {
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
| function acceptOwnership() public {
if (msg.sender == newOwner) {
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
| 24,371 |
135 | // asset => pToken (Platform Specific Token Address) | mapping(address => address) public assetToPToken;
| mapping(address => address) public assetToPToken;
| 83,521 |
12 | // Gets the amount of allocated MNT tokens that are not used in any vesting schedule yet.Creation of new vesting schedules will decrease this amount. / | function freeAllocation() external view returns (uint256);
| function freeAllocation() external view returns (uint256);
| 40,786 |
3 | // Map of users address and their state data (userAddress => userStateData) | mapping(address => UserState) internal _userState;
| mapping(address => UserState) internal _userState;
| 11,319 |
13 | // Allows a request to be cancelled if it has not been fulfilled Requires keeping track of the expiration value emitted from the oracle contract.Deletes the request from the `pendingRequests` mapping.Emits ChainlinkCancelled event. requestId The request ID payment The amount of LINK sent for the request callbackFunc The callback function specified for the request expiration The time of the expiration for the request / | function cancelChainlinkRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunc,
uint256 expiration
)
internal
| function cancelChainlinkRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunc,
uint256 expiration
)
internal
| 1,837 |
109 | // Check bid range | ActiveBidRange memory range = activeBidRange[_tokenId][_owner];
uint8 priceType = nafter.getPriceType(_tokenId, _owner);
require(priceType == 1 || priceType == 2, "bid is not valid for fixed sale");
if (priceType == 1)
require(range.startTime < block.timestamp && range.endTime > block.timestamp, "bid::can't place bid'");
| ActiveBidRange memory range = activeBidRange[_tokenId][_owner];
uint8 priceType = nafter.getPriceType(_tokenId, _owner);
require(priceType == 1 || priceType == 2, "bid is not valid for fixed sale");
if (priceType == 1)
require(range.startTime < block.timestamp && range.endTime > block.timestamp, "bid::can't place bid'");
| 55,175 |
29 | // Destroys tokens from an address, this process is irrecoverable._from The address to destroy the tokens from./ | function destroyFrom(address _from) onlyOwner returns (bool) {
uint256 balance = balanceOf(_from);
if (balance == 0) throw;
balances[_from] = 0;
totalSupply = totalSupply.sub(balance);
Destroy(_from);
}
| function destroyFrom(address _from) onlyOwner returns (bool) {
uint256 balance = balanceOf(_from);
if (balance == 0) throw;
balances[_from] = 0;
totalSupply = totalSupply.sub(balance);
Destroy(_from);
}
| 10,507 |
73 | // Update storage balance of previous bin | balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
| balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
| 2,626 |
10 | // Getter for the amount of releasable `token` tokens. `token` should be the address of anIERC20 contract. / | function releasable(address token) public view virtual returns (uint256) {
return vestedAmount(token, uint64(block.timestamp)) - released(token);
}
| function releasable(address token) public view virtual returns (uint256) {
return vestedAmount(token, uint64(block.timestamp)) - released(token);
}
| 9,920 |
64 | // if weiMinimumGoal will not be reached till endTime, buyers will be able to refund ETH | uint public weiMinimumGoal;
| uint public weiMinimumGoal;
| 8,252 |
32 | // gets billing parameters maximumGasPrice highest gas price for which transmitter will be compensated reasonableGasPrice transmitter will receive reward for gas prices under this value microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units / | function getBilling()
external
view
returns (
uint32 maximumGasPrice,
uint32 reasonableGasPrice,
uint32 microLinkPerEth,
uint32 linkGweiPerObservation,
uint32 linkGweiPerTransmission
)
| function getBilling()
external
view
returns (
uint32 maximumGasPrice,
uint32 reasonableGasPrice,
uint32 microLinkPerEth,
uint32 linkGweiPerObservation,
uint32 linkGweiPerTransmission
)
| 51,323 |
34 | // Sets the provenance hash and emits an event. The provenance hash is used for random reveals, whichis a hash of the ordered metadata to show it has not beenmodified after mint started. This function will revert after the first item has been minted.newProvenanceHash The new provenance hash to set. / | function setProvenanceHash(bytes32 newProvenanceHash) external {
// Ensure the sender is only the owner or contract itself.
_onlyOwnerOrSelf();
// Revert if any items have been minted.
if (_totalMinted() > 0) {
revert ProvenanceHashCannotBeSetAfterMintStarted();
}
// Keep track of the old provenance hash for emitting with the event.
bytes32 oldProvenanceHash = _provenanceHash;
// Set the new provenance hash.
_provenanceHash = newProvenanceHash;
// Emit an event with the update.
emit ProvenanceHashUpdated(oldProvenanceHash, newProvenanceHash);
}
| function setProvenanceHash(bytes32 newProvenanceHash) external {
// Ensure the sender is only the owner or contract itself.
_onlyOwnerOrSelf();
// Revert if any items have been minted.
if (_totalMinted() > 0) {
revert ProvenanceHashCannotBeSetAfterMintStarted();
}
// Keep track of the old provenance hash for emitting with the event.
bytes32 oldProvenanceHash = _provenanceHash;
// Set the new provenance hash.
_provenanceHash = newProvenanceHash;
// Emit an event with the update.
emit ProvenanceHashUpdated(oldProvenanceHash, newProvenanceHash);
}
| 20,316 |
0 | // Validation Result.Contains the result and error message. If the given string value is valid, `message` should be empty. / | struct Result {
bool isValid;
string message;
}
| struct Result {
bool isValid;
string message;
}
| 14,601 |
62 | // update position data in state | if (!credit.isOpen) {
revert PositionIsClosed();
}
| if (!credit.isOpen) {
revert PositionIsClosed();
}
| 3,810 |
52 | // We don't do interface check here as we might want to a normal wallet address to act as a release agent | releaseAgent = addr;
| releaseAgent = addr;
| 44,567 |
93 | // Moves `amount` tokens from the caller's account to `to`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. / | function transfer(address to, uint256 amount) external returns (bool);
| function transfer(address to, uint256 amount) external returns (bool);
| 40,114 |
512 | // sending the total msg.value if the transfer is ETH.the transferToReserve() function will take care of sending theexcess ETH back to the caller | core.transferToReserve.value(vars.isETH ? msg.value.sub(vars.originationFee) : 0)(
_reserve,
msg.sender,
vars.paybackAmountMinusFees
);
emit Repay(
_reserve,
_onBehalfOf,
msg.sender,
| core.transferToReserve.value(vars.isETH ? msg.value.sub(vars.originationFee) : 0)(
_reserve,
msg.sender,
vars.paybackAmountMinusFees
);
emit Repay(
_reserve,
_onBehalfOf,
msg.sender,
| 15,401 |
11 | // Gets the distribution end timestamp of the emissions / | function DISTRIBUTION_END() external view returns (uint256);
| function DISTRIBUTION_END() external view returns (uint256);
| 19,899 |
35 | // Creates and sends a retryable ticket to transfer GRT to L2 using the Arbitrum Inbox.The tokens are escrowed by the gateway until they are withdrawn back to L1.The ticket must be redeemed on L2 to receive tokens at the specified address.Note that the caller must previously allow the gateway to spend the specified amount of GRT. maxGas and gasPriceBid must be set using Arbitrum's NodeInterface.estimateRetryableTicket method.Also note that allowlisted senders (some protocol contracts) can include additional calldatafor a callhook to be executed on the L2 side when the tokens are received. In this case, the L2 transactioncan revert if the | function outboundTransfer(
address _l1Token,
address _to,
uint256 _amount,
uint256 _maxGas,
uint256 _gasPriceBid,
bytes calldata _data
| function outboundTransfer(
address _l1Token,
address _to,
uint256 _amount,
uint256 _maxGas,
uint256 _gasPriceBid,
bytes calldata _data
| 18,838 |
57 | // get the amount of collateral per 1 repaid otoken | uint256 debtPrice = _getDebtPrice(
depositedCollateral,
shortDetails.shortAmount,
cashValue,
shortDetails.shortUnderlyingPrice,
timestamp,
vaultDetails.collateralDecimals,
vaultDetails.isShortPut
);
| uint256 debtPrice = _getDebtPrice(
depositedCollateral,
shortDetails.shortAmount,
cashValue,
shortDetails.shortUnderlyingPrice,
timestamp,
vaultDetails.collateralDecimals,
vaultDetails.isShortPut
);
| 24,355 |
296 | // File: contracts/upgradeable_contracts/modules/gas_limit/SelectorTokenGasLimitManager.sol |
pragma solidity 0.7.5;
|
pragma solidity 0.7.5;
| 9,043 |
171 | // Delete token origin extension tracking | delete _tokensExtension[tokenId];
| delete _tokensExtension[tokenId];
| 1,701 |
9 | // Confirms and executes a pending rebasement proposal. Prohibits further proposals for 18 hours. / | function confirmRebasement() public isOwner
| function confirmRebasement() public isOwner
| 8,395 |
81 | // caller gives owner approval to operate token / | if (isAllowListRequiredMapping[id] == true) {
require(
isOnAllowlist(id, _msgSender()),
"You are not allowed to mint this token"
);
| if (isAllowListRequiredMapping[id] == true) {
require(
isOnAllowlist(id, _msgSender()),
"You are not allowed to mint this token"
);
| 1,789 |
1 | // Increment the limiter value of a wallet. _wallet The address of the wallet. _value The amount to be updated. / | function updateWallet(address _wallet, uint256 _value) external;
| function updateWallet(address _wallet, uint256 _value) external;
| 10,364 |
22 | // fire the event | emit FighterReady(_season);
| emit FighterReady(_season);
| 41,026 |
14 | // Sets winners according to the order of the array, lower index = better placement. | function setWinners(address[] calldata auctionWinners) external onlyOwner {
require(auctionWinners.length >= currentAuctionWinnerCount, "Not enough winners of auction");
require(!winnersSet, "Winners have already been set, clear winners before setting them again");
for(uint256 i = 0; i < currentAuctionWinnerCount; ) {
winners[auctionWinners[i]] = i + 1;
unchecked { ++i; }
}
winnersSet = true;
}
| function setWinners(address[] calldata auctionWinners) external onlyOwner {
require(auctionWinners.length >= currentAuctionWinnerCount, "Not enough winners of auction");
require(!winnersSet, "Winners have already been set, clear winners before setting them again");
for(uint256 i = 0; i < currentAuctionWinnerCount; ) {
winners[auctionWinners[i]] = i + 1;
unchecked { ++i; }
}
winnersSet = true;
}
| 35,259 |
64 | // Removes country restriction. Identities from those countries will again be authorised to manipulate Tokens linked to this Compliance._country Country to be unrestricted, should be expressed by following numeric ISO 3166-1 standard Only the owner of the Compliance smart contract can call this function emits an `RemovedRestrictedCountry` event / | function removeCountryRestriction(uint16 _country) public onlyOwner {
_restrictedCountries[_country] = false;
emit RemovedRestrictedCountry(_country);
}
| function removeCountryRestriction(uint16 _country) public onlyOwner {
_restrictedCountries[_country] = false;
emit RemovedRestrictedCountry(_country);
}
| 12,006 |
11 | // Splitter Contract that will collect mint fees; | address payable private _mintingBeneficiary;
| address payable private _mintingBeneficiary;
| 9,512 |
205 | // Reissue new Stake NFT id | newNftId = nextNftId;
_stakeById[newNftId] = stakeIndex;
| newNftId = nextNftId;
_stakeById[newNftId] = stakeIndex;
| 26,749 |
27 | // =====================================Setting to change for whoaaddress_ |
address internal whoaaddress_ = 0x314d0ED76d866826C809fb6a51d63642b2E9eC3e;
|
address internal whoaaddress_ = 0x314d0ED76d866826C809fb6a51d63642b2E9eC3e;
| 29,270 |
157 | // Returns the minimum of `x` and `y`. | function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
| function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
| 23,982 |
9 | // Get the numbers in the problem set | function getNumbers() public view returns(uint256[] numberSet) {
return numbers;
}
| function getNumbers() public view returns(uint256[] numberSet) {
return numbers;
}
| 40,590 |
118 | // / | function setHouseEdge(uint256 new_edge) external
| function setHouseEdge(uint256 new_edge) external
| 19,074 |
24 | // add fromToken and necessary amount of baseToken to endLP | endToken.approve(address(router), endAmount);
baseToken.approve(address(router), baseAmount);
| endToken.approve(address(router), endAmount);
baseToken.approve(address(router), baseAmount);
| 46,332 |
85 | // ========== STATE VARIABLES ========== // Stores balances and allowances. // Other ERC20 fields. // Constructor. _proxy The proxy associated with this contract. _name Token's ERC20 name. _symbol Token's ERC20 symbol. _totalSupply The total supply of the token. _tokenState The TokenState contract address. _owner The owner of this contract. / | constructor(
address _proxy,
TokenState _tokenState,
string _name,
string _symbol,
uint _totalSupply,
uint8 _decimals,
address _owner
| constructor(
address _proxy,
TokenState _tokenState,
string _name,
string _symbol,
uint _totalSupply,
uint8 _decimals,
address _owner
| 32,254 |
105 | // Updates the catnip fee divider._val Number to divide votes by./ | function setVoteDiv(uint256 _val) public _onlyOwner delegatedOnly _updateState(msg.sender) {
voteDiv = _val;
}
| function setVoteDiv(uint256 _val) public _onlyOwner delegatedOnly _updateState(msg.sender) {
voteDiv = _val;
}
| 32,140 |
325 | // Withdraw an amount of tokens from a proposal _proposalId Proposal id _amount Amount of withdrawn tokens _from Account to withdraw from / | function _withdrawFromProposal(uint256 _proposalId, uint256 _amount, address _from) internal {
Proposal storage proposal = proposals[_proposalId];
require(proposal.voterStake[_from] >= _amount, ERROR_WITHDRAW_MORE_THAN_STAKED);
require(_amount > 0, ERROR_AMOUNT_CAN_NOT_BE_ZERO);
uint256 previousStake = proposal.stakedTokens;
proposal.stakedTokens = proposal.stakedTokens.sub(_amount);
proposal.voterStake[_from] = proposal.voterStake[_from].sub(_amount);
totalVoterStake[_from] = totalVoterStake[_from].sub(_amount);
totalStaked = totalStaked.sub(_amount);
if (proposal.voterStake[_from] == 0) {
voterStakedProposals[_from].deleteItem(_proposalId);
}
if (proposal.proposalStatus == ProposalStatus.Active) {
_calculateAndSetConviction(proposal, previousStake);
}
emit StakeWithdrawn(_from, _proposalId, _amount, proposal.voterStake[_from], proposal.stakedTokens, proposal.convictionLast);
}
| function _withdrawFromProposal(uint256 _proposalId, uint256 _amount, address _from) internal {
Proposal storage proposal = proposals[_proposalId];
require(proposal.voterStake[_from] >= _amount, ERROR_WITHDRAW_MORE_THAN_STAKED);
require(_amount > 0, ERROR_AMOUNT_CAN_NOT_BE_ZERO);
uint256 previousStake = proposal.stakedTokens;
proposal.stakedTokens = proposal.stakedTokens.sub(_amount);
proposal.voterStake[_from] = proposal.voterStake[_from].sub(_amount);
totalVoterStake[_from] = totalVoterStake[_from].sub(_amount);
totalStaked = totalStaked.sub(_amount);
if (proposal.voterStake[_from] == 0) {
voterStakedProposals[_from].deleteItem(_proposalId);
}
if (proposal.proposalStatus == ProposalStatus.Active) {
_calculateAndSetConviction(proposal, previousStake);
}
emit StakeWithdrawn(_from, _proposalId, _amount, proposal.voterStake[_from], proposal.stakedTokens, proposal.convictionLast);
}
| 55,724 |
25 | // Owner can transfer out any accidentally sent ERC20 tokens | function transferERC20Token(address tokenAddress)
public
onlyOwner
returns (bool)
| function transferERC20Token(address tokenAddress)
public
onlyOwner
returns (bool)
| 29,504 |
21 | // window | "<path fill="
'"black"'
" d="
'"M193 225l0 -14c0,-3 3,-6 7,-6l0 0c4,0 7,3 7,6l0 14 -14 0zm-145 0l0 -14c0,-3 3,-6 7,-6l0 0c4,0 7,3 7,6l0 14 -14 0zm55 -21l0 -11c0,-2 3,-5 6,-5l0 0c4,0 7,3 7,5l0 11 -13 0zm36 0l0 -11c0,-2 3,-5 7,-5l0 0c3,0 6,3 6,5l0 11 -13 0z"'
"/>",
| "<path fill="
'"black"'
" d="
'"M193 225l0 -14c0,-3 3,-6 7,-6l0 0c4,0 7,3 7,6l0 14 -14 0zm-145 0l0 -14c0,-3 3,-6 7,-6l0 0c4,0 7,3 7,6l0 14 -14 0zm55 -21l0 -11c0,-2 3,-5 6,-5l0 0c4,0 7,3 7,5l0 11 -13 0zm36 0l0 -11c0,-2 3,-5 7,-5l0 0c3,0 6,3 6,5l0 11 -13 0z"'
"/>",
| 19,879 |
29 | // no ownership or approval checks cause we're forcing a change of ownership | require(from == ownerOf[id], "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
unchecked {
balanceOf[from]--;
balanceOf[to]++;
}
| require(from == ownerOf[id], "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
unchecked {
balanceOf[from]--;
balanceOf[to]++;
}
| 36,931 |
95 | // Reasons why a user's tokens have been locked / | mapping(address => bytes32[]) public lockReason;
| mapping(address => bytes32[]) public lockReason;
| 10,445 |
9 | // Cancels an auction that hasn't been won yet./Returns the NFT to original owner./This is a state-modifying function that can/be called while the contract is paused./_tokenId - ID of token on auction | function cancelAuction(uint256 _tokenId)
public
| function cancelAuction(uint256 _tokenId)
public
| 17,133 |
143 | // Get the current allowance from `owner` for `spender`owner The address of the account which owns the tokens to be spentspender The address of the account which may transfer tokens return The number of tokens allowed to be spent (-1 means infinite)/ | function allowance(address owner, address spender) external view returns (uint256 remaining);
| function allowance(address owner, address spender) external view returns (uint256 remaining);
| 533 |
233 | // return FL | dydxPaybackLoan(proxy, tokenAddr, amount);
| dydxPaybackLoan(proxy, tokenAddr, amount);
| 28,709 |
120 | // Deposits all balance to the vault. / | function depositAll() public virtual {
deposit(token.balanceOf(msg.sender));
}
| function depositAll() public virtual {
deposit(token.balanceOf(msg.sender));
}
| 4,330 |
128 | // ========== RESTRICTED FUNCTIONS ========== |
function notifyRewardAmount(
uint256 _reward
|
function notifyRewardAmount(
uint256 _reward
| 14,854 |
67 | // IContractId Implementation |
function contractId()
public
pure
returns (bytes32 id, uint256 version)
|
function contractId()
public
pure
returns (bytes32 id, uint256 version)
| 53,771 |
277 | // Initializes a reserve reserve The reserve object aTokenAddress The address of the overlying atoken contract interestRateStrategyAddress The address of the interest rate strategy contract / | ) external {
require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);
reserve.liquidityIndex = uint128(WadRayMath.ray());
reserve.variableBorrowIndex = uint128(WadRayMath.ray());
reserve.aTokenAddress = aTokenAddress;
reserve.stableDebtTokenAddress = stableDebtTokenAddress;
reserve.variableDebtTokenAddress = variableDebtTokenAddress;
reserve.interestRateStrategyAddress = interestRateStrategyAddress;
}
| ) external {
require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);
reserve.liquidityIndex = uint128(WadRayMath.ray());
reserve.variableBorrowIndex = uint128(WadRayMath.ray());
reserve.aTokenAddress = aTokenAddress;
reserve.stableDebtTokenAddress = stableDebtTokenAddress;
reserve.variableDebtTokenAddress = variableDebtTokenAddress;
reserve.interestRateStrategyAddress = interestRateStrategyAddress;
}
| 60,658 |
4 | // set fee (only owner) | function setFee(uint256 _fee) external onlyOwner {
fee = _fee;
}
| function setFee(uint256 _fee) external onlyOwner {
fee = _fee;
}
| 30,294 |
107 | // CryptoSaga Card ERC721 Token that repesents CryptoSaga's cards. Buy consuming a card, players of CryptoSaga can get a heroe. / | contract CryptoSagaCard is ERC721Token, Claimable, AccessMint {
string public constant name = "CryptoSaga Card";
string public constant symbol = "CARD";
// Rank of the token.
mapping(uint256 => uint8) public tokenIdToRank;
// The number of tokens ever minted.
uint256 public numberOfTokenId;
// The converter contract.
CryptoSagaCardSwap private swapContract;
// Event that should be fired when card is converted.
event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId);
// @dev Set the address of the contract that represents CryptoSaga Cards.
function setCryptoSagaCardSwapContract(address _contractAddress)
public
onlyOwner
{
swapContract = CryptoSagaCardSwap(_contractAddress);
}
function rankOf(uint256 _tokenId)
public view
returns (uint8)
{
return tokenIdToRank[_tokenId];
}
// @dev Mint a new card.
function mint(address _beneficiary, uint256 _amount, uint8 _rank)
onlyAccessMint
public
{
for (uint256 i = 0; i < _amount; i++) {
_mint(_beneficiary, numberOfTokenId);
tokenIdToRank[numberOfTokenId] = _rank;
numberOfTokenId ++;
}
}
// @dev Swap this card for reward.
// The card will be burnt.
function swap(uint256 _tokenId)
onlyOwnerOf(_tokenId)
public
returns (uint256)
{
require(address(swapContract) != address(0));
var _rank = tokenIdToRank[_tokenId];
var _rewardId = swapContract.swapCardForReward(this, _rank);
CardSwap(ownerOf(_tokenId), _tokenId, _rewardId);
_burn(_tokenId);
return _rewardId;
}
}
| contract CryptoSagaCard is ERC721Token, Claimable, AccessMint {
string public constant name = "CryptoSaga Card";
string public constant symbol = "CARD";
// Rank of the token.
mapping(uint256 => uint8) public tokenIdToRank;
// The number of tokens ever minted.
uint256 public numberOfTokenId;
// The converter contract.
CryptoSagaCardSwap private swapContract;
// Event that should be fired when card is converted.
event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId);
// @dev Set the address of the contract that represents CryptoSaga Cards.
function setCryptoSagaCardSwapContract(address _contractAddress)
public
onlyOwner
{
swapContract = CryptoSagaCardSwap(_contractAddress);
}
function rankOf(uint256 _tokenId)
public view
returns (uint8)
{
return tokenIdToRank[_tokenId];
}
// @dev Mint a new card.
function mint(address _beneficiary, uint256 _amount, uint8 _rank)
onlyAccessMint
public
{
for (uint256 i = 0; i < _amount; i++) {
_mint(_beneficiary, numberOfTokenId);
tokenIdToRank[numberOfTokenId] = _rank;
numberOfTokenId ++;
}
}
// @dev Swap this card for reward.
// The card will be burnt.
function swap(uint256 _tokenId)
onlyOwnerOf(_tokenId)
public
returns (uint256)
{
require(address(swapContract) != address(0));
var _rank = tokenIdToRank[_tokenId];
var _rewardId = swapContract.swapCardForReward(this, _rank);
CardSwap(ownerOf(_tokenId), _tokenId, _rewardId);
_burn(_tokenId);
return _rewardId;
}
}
| 17,273 |
71 | // v3 Aggregator interface / |
string constant private V3_NO_DATA_ERROR = "No data present";
|
string constant private V3_NO_DATA_ERROR = "No data present";
| 45,789 |
646 | // Returns all unlocked rewards given an address _beneficiary address of which we want to get all rewards / | function getUnlockedRewardsInfo(address _beneficiary) external view returns (Reward[]) {
Reward[] storage rewards = addressUnlockedRewards[_beneficiary];
return rewards;
}
| function getUnlockedRewardsInfo(address _beneficiary) external view returns (Reward[]) {
Reward[] storage rewards = addressUnlockedRewards[_beneficiary];
return rewards;
}
| 17,797 |
1,341 | // See {ERC721-_mint}. / | function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
| function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
| 16,694 |
41 | // Update the treasury address to receive the tax. _treasury New treasury address / | function updateTreasury(address _treasury) external onlyOwner {
require(address(0) != _treasury, "Zero address");
emit TreasuryUpdated(treasury, _treasury);
treasury = _treasury;
}
| function updateTreasury(address _treasury) external onlyOwner {
require(address(0) != _treasury, "Zero address");
emit TreasuryUpdated(treasury, _treasury);
treasury = _treasury;
}
| 8,764 |
240 | // Sets various variables for a Vault/Sender has to be allowed to call this method/vault Address of the Vault/param Name of the variable to set/data New value to set for the variable [address] | function setParam(
address vault,
bytes32 param,
address data
| function setParam(
address vault,
bytes32 param,
address data
| 33,917 |
11 | // optimized version from dss PR 78 | function rpow(uint256 x, uint256 n, uint256 b) internal pure returns (uint256 z) {
assembly {
switch n case 0 { z := b }
default {
switch x case 0 { z := 0 }
default {
switch mod(n, 2) case 0 { z := b } default { z := x }
let half := div(b, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if shr(128, x) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, b)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, b)
}
}
}
}
}
| function rpow(uint256 x, uint256 n, uint256 b) internal pure returns (uint256 z) {
assembly {
switch n case 0 { z := b }
default {
switch x case 0 { z := 0 }
default {
switch mod(n, 2) case 0 { z := b } default { z := x }
let half := div(b, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if shr(128, x) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, b)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, b)
}
}
}
}
}
| 20,544 |
0 | // We will mint all tokens in one go, and send them to a wallet | _mint(wallet_, supply_);
| _mint(wallet_, supply_);
| 16,723 |
39 | // ICO never happened. Allow refund.Modified by: TokenMagic / | function refund() public {
// Trying to ask refund too soon
require(now > freezeEndsAt && balances[msg.sender] > 0);
address investor = msg.sender;
uint amount = balances[investor];
delete balances[investor];
emit Refunded(investor, amount);
investor.transfer(amount);
}
| function refund() public {
// Trying to ask refund too soon
require(now > freezeEndsAt && balances[msg.sender] > 0);
address investor = msg.sender;
uint amount = balances[investor];
delete balances[investor];
emit Refunded(investor, amount);
investor.transfer(amount);
}
| 31,663 |
49 | // Returns the addition of two unsigned integers, reverting onoverflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow. / | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| 134 |
25 | // Allow owner to change nifty name, by 'niftyType'. / | function setNiftyName(uint256 niftyType, string memory niftyName) public onlyValidSender {
_setNiftyTypeName(niftyType, niftyName);
}
| function setNiftyName(uint256 niftyType, string memory niftyName) public onlyValidSender {
_setNiftyTypeName(niftyType, niftyName);
}
| 62,124 |
23 | // An open auction house, enabling collectors and curators to run their own auctions / | contract AuctionHouse is IAuctionHouse, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Counters for Counters.Counter;
// The minimum amount of time left in an auction after a new bid is created
uint256 public timeBuffer;
// The minimum percentage difference between the last bid amount and the current bid.
uint8 public minBidIncrementPercentage;
// The address of the zora protocol to use via this contract
address public zora;
// / The address of the WETH contract, so that any ETH transferred can be handled as an ERC-20
address public wethAddress;
// A mapping of all of the auctions currently running.
mapping(uint256 => IAuctionHouse.Auction) public auctions;
bytes4 constant interfaceId = 0x80ac58cd; // 721 interface id
Counters.Counter private _auctionIdTracker;
/**
* @notice Require that the specified auction exists
*/
modifier auctionExists(uint256 auctionId) {
require(_exists(auctionId), "Auction doesn't exist");
_;
}
/*
* Constructor
*/
constructor(address _zora, address _weth) public {
require(
IERC165(_zora).supportsInterface(interfaceId),
"Doesn't support NFT interface"
);
zora = _zora;
wethAddress = _weth;
timeBuffer = 15 * 60; // extend 15 minutes after every bid made in last 15 minutes
minBidIncrementPercentage = 10; // 10%
}
/**
* @notice Create an auction.
* @dev Store the auction details in the auctions mapping and emit an AuctionCreated event.
* If there is no curator, or if the curator is the auction creator, automatically approve the auction.
*/
function createAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentage,
address auctionCurrency
) public override nonReentrant returns (uint256) {
require(
IERC165(tokenContract).supportsInterface(interfaceId),
"tokenContract does not support ERC721 interface"
);
require(curatorFeePercentage < 100, "curatorFeePercentage must be less than 100");
address tokenOwner = IERC721(tokenContract).ownerOf(tokenId);
require(msg.sender == IERC721(tokenContract).getApproved(tokenId) || msg.sender == tokenOwner, "Caller must be approved or owner for token id");
uint256 auctionId = _auctionIdTracker.current();
auctions[auctionId] = Auction({
tokenId: tokenId,
tokenContract: tokenContract,
approved: false,
amount: 0,
duration: duration,
firstBidTime: 0,
reservePrice: reservePrice,
curatorFeePercentage: curatorFeePercentage,
tokenOwner: tokenOwner,
bidder: address(0),
curator: curator,
auctionCurrency: auctionCurrency
});
IERC721(tokenContract).transferFrom(tokenOwner, address(this), tokenId);
_auctionIdTracker.increment();
emit AuctionCreated(auctionId, tokenId, tokenContract, duration, reservePrice, tokenOwner, curator, curatorFeePercentage, auctionCurrency);
if(auctions[auctionId].curator == address(0) || curator == tokenOwner) {
_approveAuction(auctionId, true);
}
return auctionId;
}
/**
* @notice Approve an auction, opening up the auction for bids.
* @dev Only callable by the curator. Cannot be called if the auction has already started.
*/
function setAuctionApproval(uint256 auctionId, bool approved) external override auctionExists(auctionId) {
require(msg.sender == auctions[auctionId].curator, "Must be auction curator");
require(auctions[auctionId].firstBidTime == 0, "Auction has already started");
_approveAuction(auctionId, approved);
}
/**
* @notice Create a bid on a token, with a given amount.
* @dev If provided a valid bid, transfers the provided amount to this contract.
* If the auction is run in native ETH, the ETH is wrapped so it can be identically to other
* auction currencies in this contract.
*/
function createBid(uint256 auctionId, uint256 amount)
external
override
payable
auctionExists(auctionId)
nonReentrant
{
address payable lastBidder = auctions[auctionId].bidder;
require(auctions[auctionId].approved, "Auction must be approved by curator");
require(
auctions[auctionId].firstBidTime == 0 ||
block.timestamp <
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration),
"Auction expired"
);
require(
amount >= auctions[auctionId].reservePrice,
"Must send at least reservePrice"
);
require(
amount >= auctions[auctionId].amount.add(
auctions[auctionId].amount.mul(minBidIncrementPercentage).div(100)
),
"Must send more than last bid by minBidIncrementPercentage amount"
);
// For Zora Protocol, ensure that the bid is valid for the current bidShare configuration
if(auctions[auctionId].tokenContract == zora) {
require(
IMarket(IMediaExtended(zora).marketContract()).isValidBid(
auctions[auctionId].tokenId,
amount
),
"Bid invalid for share splitting"
);
}
// If this is the first valid bid, we should set the starting time now.
// If it's not, then we should refund the last bidder
if(auctions[auctionId].firstBidTime == 0) {
auctions[auctionId].firstBidTime = block.timestamp;
} else if(lastBidder != address(0)) {
_handleOutgoingBid(lastBidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
}
_handleIncomingBid(amount, auctions[auctionId].auctionCurrency);
auctions[auctionId].amount = amount;
auctions[auctionId].bidder = msg.sender;
bool extended = false;
// at this point we know that the timestamp is less than start + duration (since the auction would be over, otherwise)
// we want to know by how much the timestamp is less than start + duration
// if the difference is less than the timeBuffer, increase the duration by the timeBuffer
if (
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration).sub(
block.timestamp
) < timeBuffer
) {
auctions[auctionId].duration = auctions[auctionId].duration.add(timeBuffer);
extended = true;
}
emit AuctionBid(
auctionId,
auctions[auctionId].tokenId,
auctions[auctionId].tokenContract,
msg.sender,
amount,
lastBidder == address(0), // firstBid boolean
extended
);
}
/**
* @notice End an auction, finalizing the bid on Zora if applicable and paying out the respective parties.
* @dev If for some reason the auction cannot be finalized (invalid token recipient, for example),
* The auction is reset and the NFT is transferred back to the auction creator.
*/
function endAuction(uint256 auctionId) external override auctionExists(auctionId) nonReentrant {
require(
uint256(auctions[auctionId].firstBidTime) != 0,
"Auction hasn't begun"
);
require(
block.timestamp >=
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration),
"Auction hasn't completed"
);
address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency;
uint256 curatorFee = 0;
uint256 tokenOwnerProfit = auctions[auctionId].amount;
if(auctions[auctionId].tokenContract == zora) {
// If the auction is running on zora, settle it on the protocol
(bool success, uint256 remainingProfit) = _handleZoraAuctionSettlement(auctionId);
tokenOwnerProfit = remainingProfit;
if(success != true) {
_handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
_cancelAuction(auctionId);
return;
}
} else {
// Otherwise, transfer the token to the winner and pay out the participants below
try IERC721(auctions[auctionId].tokenContract).safeTransferFrom(address(this), auctions[auctionId].bidder, auctions[auctionId].tokenId) {} catch {
_handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
_cancelAuction(auctionId);
return;
}
}
if(auctions[auctionId].curator != address(0)) {
curatorFee = tokenOwnerProfit.mul(auctions[auctionId].curatorFeePercentage).div(100);
tokenOwnerProfit = tokenOwnerProfit.sub(curatorFee);
_handleOutgoingBid(auctions[auctionId].curator, curatorFee, auctions[auctionId].auctionCurrency);
}
_handleOutgoingBid(auctions[auctionId].tokenOwner, tokenOwnerProfit, auctions[auctionId].auctionCurrency);
emit AuctionEnded(
auctionId,
auctions[auctionId].tokenId,
auctions[auctionId].tokenContract,
auctions[auctionId].tokenOwner,
auctions[auctionId].curator,
auctions[auctionId].bidder,
tokenOwnerProfit,
curatorFee,
currency
);
delete auctions[auctionId];
}
| contract AuctionHouse is IAuctionHouse, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Counters for Counters.Counter;
// The minimum amount of time left in an auction after a new bid is created
uint256 public timeBuffer;
// The minimum percentage difference between the last bid amount and the current bid.
uint8 public minBidIncrementPercentage;
// The address of the zora protocol to use via this contract
address public zora;
// / The address of the WETH contract, so that any ETH transferred can be handled as an ERC-20
address public wethAddress;
// A mapping of all of the auctions currently running.
mapping(uint256 => IAuctionHouse.Auction) public auctions;
bytes4 constant interfaceId = 0x80ac58cd; // 721 interface id
Counters.Counter private _auctionIdTracker;
/**
* @notice Require that the specified auction exists
*/
modifier auctionExists(uint256 auctionId) {
require(_exists(auctionId), "Auction doesn't exist");
_;
}
/*
* Constructor
*/
constructor(address _zora, address _weth) public {
require(
IERC165(_zora).supportsInterface(interfaceId),
"Doesn't support NFT interface"
);
zora = _zora;
wethAddress = _weth;
timeBuffer = 15 * 60; // extend 15 minutes after every bid made in last 15 minutes
minBidIncrementPercentage = 10; // 10%
}
/**
* @notice Create an auction.
* @dev Store the auction details in the auctions mapping and emit an AuctionCreated event.
* If there is no curator, or if the curator is the auction creator, automatically approve the auction.
*/
function createAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentage,
address auctionCurrency
) public override nonReentrant returns (uint256) {
require(
IERC165(tokenContract).supportsInterface(interfaceId),
"tokenContract does not support ERC721 interface"
);
require(curatorFeePercentage < 100, "curatorFeePercentage must be less than 100");
address tokenOwner = IERC721(tokenContract).ownerOf(tokenId);
require(msg.sender == IERC721(tokenContract).getApproved(tokenId) || msg.sender == tokenOwner, "Caller must be approved or owner for token id");
uint256 auctionId = _auctionIdTracker.current();
auctions[auctionId] = Auction({
tokenId: tokenId,
tokenContract: tokenContract,
approved: false,
amount: 0,
duration: duration,
firstBidTime: 0,
reservePrice: reservePrice,
curatorFeePercentage: curatorFeePercentage,
tokenOwner: tokenOwner,
bidder: address(0),
curator: curator,
auctionCurrency: auctionCurrency
});
IERC721(tokenContract).transferFrom(tokenOwner, address(this), tokenId);
_auctionIdTracker.increment();
emit AuctionCreated(auctionId, tokenId, tokenContract, duration, reservePrice, tokenOwner, curator, curatorFeePercentage, auctionCurrency);
if(auctions[auctionId].curator == address(0) || curator == tokenOwner) {
_approveAuction(auctionId, true);
}
return auctionId;
}
/**
* @notice Approve an auction, opening up the auction for bids.
* @dev Only callable by the curator. Cannot be called if the auction has already started.
*/
function setAuctionApproval(uint256 auctionId, bool approved) external override auctionExists(auctionId) {
require(msg.sender == auctions[auctionId].curator, "Must be auction curator");
require(auctions[auctionId].firstBidTime == 0, "Auction has already started");
_approveAuction(auctionId, approved);
}
/**
* @notice Create a bid on a token, with a given amount.
* @dev If provided a valid bid, transfers the provided amount to this contract.
* If the auction is run in native ETH, the ETH is wrapped so it can be identically to other
* auction currencies in this contract.
*/
function createBid(uint256 auctionId, uint256 amount)
external
override
payable
auctionExists(auctionId)
nonReentrant
{
address payable lastBidder = auctions[auctionId].bidder;
require(auctions[auctionId].approved, "Auction must be approved by curator");
require(
auctions[auctionId].firstBidTime == 0 ||
block.timestamp <
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration),
"Auction expired"
);
require(
amount >= auctions[auctionId].reservePrice,
"Must send at least reservePrice"
);
require(
amount >= auctions[auctionId].amount.add(
auctions[auctionId].amount.mul(minBidIncrementPercentage).div(100)
),
"Must send more than last bid by minBidIncrementPercentage amount"
);
// For Zora Protocol, ensure that the bid is valid for the current bidShare configuration
if(auctions[auctionId].tokenContract == zora) {
require(
IMarket(IMediaExtended(zora).marketContract()).isValidBid(
auctions[auctionId].tokenId,
amount
),
"Bid invalid for share splitting"
);
}
// If this is the first valid bid, we should set the starting time now.
// If it's not, then we should refund the last bidder
if(auctions[auctionId].firstBidTime == 0) {
auctions[auctionId].firstBidTime = block.timestamp;
} else if(lastBidder != address(0)) {
_handleOutgoingBid(lastBidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
}
_handleIncomingBid(amount, auctions[auctionId].auctionCurrency);
auctions[auctionId].amount = amount;
auctions[auctionId].bidder = msg.sender;
bool extended = false;
// at this point we know that the timestamp is less than start + duration (since the auction would be over, otherwise)
// we want to know by how much the timestamp is less than start + duration
// if the difference is less than the timeBuffer, increase the duration by the timeBuffer
if (
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration).sub(
block.timestamp
) < timeBuffer
) {
auctions[auctionId].duration = auctions[auctionId].duration.add(timeBuffer);
extended = true;
}
emit AuctionBid(
auctionId,
auctions[auctionId].tokenId,
auctions[auctionId].tokenContract,
msg.sender,
amount,
lastBidder == address(0), // firstBid boolean
extended
);
}
/**
* @notice End an auction, finalizing the bid on Zora if applicable and paying out the respective parties.
* @dev If for some reason the auction cannot be finalized (invalid token recipient, for example),
* The auction is reset and the NFT is transferred back to the auction creator.
*/
function endAuction(uint256 auctionId) external override auctionExists(auctionId) nonReentrant {
require(
uint256(auctions[auctionId].firstBidTime) != 0,
"Auction hasn't begun"
);
require(
block.timestamp >=
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration),
"Auction hasn't completed"
);
address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency;
uint256 curatorFee = 0;
uint256 tokenOwnerProfit = auctions[auctionId].amount;
if(auctions[auctionId].tokenContract == zora) {
// If the auction is running on zora, settle it on the protocol
(bool success, uint256 remainingProfit) = _handleZoraAuctionSettlement(auctionId);
tokenOwnerProfit = remainingProfit;
if(success != true) {
_handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
_cancelAuction(auctionId);
return;
}
} else {
// Otherwise, transfer the token to the winner and pay out the participants below
try IERC721(auctions[auctionId].tokenContract).safeTransferFrom(address(this), auctions[auctionId].bidder, auctions[auctionId].tokenId) {} catch {
_handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
_cancelAuction(auctionId);
return;
}
}
if(auctions[auctionId].curator != address(0)) {
curatorFee = tokenOwnerProfit.mul(auctions[auctionId].curatorFeePercentage).div(100);
tokenOwnerProfit = tokenOwnerProfit.sub(curatorFee);
_handleOutgoingBid(auctions[auctionId].curator, curatorFee, auctions[auctionId].auctionCurrency);
}
_handleOutgoingBid(auctions[auctionId].tokenOwner, tokenOwnerProfit, auctions[auctionId].auctionCurrency);
emit AuctionEnded(
auctionId,
auctions[auctionId].tokenId,
auctions[auctionId].tokenContract,
auctions[auctionId].tokenOwner,
auctions[auctionId].curator,
auctions[auctionId].bidder,
tokenOwnerProfit,
curatorFee,
currency
);
delete auctions[auctionId];
}
| 25,788 |
21 | // if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request | if (_path[i - 1] != _path[i - 2])
ensureAllowance(_path[i - 2], converter, fromAmount);
| if (_path[i - 1] != _path[i - 2])
ensureAllowance(_path[i - 2], converter, fromAmount);
| 27,356 |
2 | // Sell a token for ETH directly against uniswap v3./encodedPath Uniswap-encoded path, where the last token is WETH./sellAmount amount of the first token in the path to sell./minBuyAmount Minimum amount of ETH to buy./recipient The recipient of the bought tokens. Can be zero for sender./ return buyAmount Amount of ETH bought. | function sellTokenForEthToUniswapV3(
bytes memory encodedPath,
uint256 sellAmount,
uint256 minBuyAmount,
address payable recipient
)
external
returns (uint256 buyAmount);
| function sellTokenForEthToUniswapV3(
bytes memory encodedPath,
uint256 sellAmount,
uint256 minBuyAmount,
address payable recipient
)
external
returns (uint256 buyAmount);
| 18,102 |
13 | // TestGatewayBase contract.Used for test only. / | contract TestGatewayBase is GatewayBase {
/* Constants */
/** Unlock period for change bounty in block height. */
uint256 public constant BOUNTY_CHANGE_UNLOCK_PERIOD = 2;
/* Constructor */
/**
* @notice This is used for testing.
*
* @param _stateRootProvider Contract address which implements
* StateRootInterface.
* @param _bounty The amount that facilitator will stakes to initiate the
* message transfers.
* @param _organization Address of a contract that manages workers.
*/
constructor(
StateRootInterface _stateRootProvider,
uint256 _bounty,
OrganizationInterface _organization
)
public
GatewayBase(
_stateRootProvider,
_bounty,
_organization
)
{}
/* external functions */
/**
* @notice It is used to set a message.
*
* @dev This is used for testing purpose.
*
* @param _intentHash Intent hash.
* @param _nonce Nonce of the message sender address.
* @param _gasPrice Gas price that message sender is ready to pay to
* transfer message.
* @param _gasLimit Gas limit that message sender is ready to pay.
* @param _sender Message sender address.
* @param _hashLock Hash Lock provided by the facilitator.
*
* @return messageHash_ Hash unique for every request.
*/
function setMessage(
bytes32 _intentHash,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit,
address _sender,
bytes32 _hashLock
)
external
returns (bytes32 messageHash_)
{
MessageBus.Message memory message = getMessage(
_intentHash,
_nonce,
_gasPrice,
_gasLimit,
_sender,
_hashLock
);
messageHash_ = MessageBus.messageDigest(
message.intentHash,
message.nonce,
message.gasPrice,
message.gasLimit,
message.sender,
message.hashLock
);
messages[messageHash_] = message;
}
/**
* @notice It sets the status of inbox.
*
* @dev This is used for testing purpose.
*
* @param _messageHash It sets the status of the message.
* @param _status It sets the state of the message.
*/
function setInboxStatus(
bytes32 _messageHash,
MessageBus.MessageStatus _status
)
external
{
messageBox.inbox[_messageHash] = _status;
}
/**
* @notice It sets the status of outbox.
*
* @dev This is used for testing purpose.
*
* @param _messageHash MessageHash for which status is the be set.
* @param _status Status of the message to be set.
*/
function setOutboxStatus(
bytes32 _messageHash,
MessageBus.MessageStatus _status
)
external
{
messageBox.outbox[_messageHash] = _status;
}
/**
* @notice It sets the message hash for active inbox process.
*
* @dev This is used for testing purpose.
*
* @param _account Account address.
* @param _messageHash MessageHash for which status is the be set.
*/
function setInboxProcess(
address _account,
bytes32 _messageHash
)
external
{
super.registerInboxProcess(_account, 1, _messageHash);
}
/**
* @notice It sets the message hash for active outbox process.
*
* @dev This is used for testing purpose.
*
* @param _account Account address.
* @param _messageHash MessageHash for which status is the be set.
*/
function setOutboxProcess(
address _account,
bytes32 _messageHash
)
external
{
super.registerOutboxProcess(_account, 1, _messageHash);
}
/**
* @notice Method allows organization to propose new bounty amount.
*
* @dev This is used for testing purpose.
*
* @param _proposedBounty proposed bounty amount.
*
* @return uint256 proposed bounty amount.
*/
function initiateBountyAmountChange(uint256 _proposedBounty)
external
onlyOrganization
returns(uint256)
{
return initiateBountyAmountChangeInternal(_proposedBounty, BOUNTY_CHANGE_UNLOCK_PERIOD);
}
}
| contract TestGatewayBase is GatewayBase {
/* Constants */
/** Unlock period for change bounty in block height. */
uint256 public constant BOUNTY_CHANGE_UNLOCK_PERIOD = 2;
/* Constructor */
/**
* @notice This is used for testing.
*
* @param _stateRootProvider Contract address which implements
* StateRootInterface.
* @param _bounty The amount that facilitator will stakes to initiate the
* message transfers.
* @param _organization Address of a contract that manages workers.
*/
constructor(
StateRootInterface _stateRootProvider,
uint256 _bounty,
OrganizationInterface _organization
)
public
GatewayBase(
_stateRootProvider,
_bounty,
_organization
)
{}
/* external functions */
/**
* @notice It is used to set a message.
*
* @dev This is used for testing purpose.
*
* @param _intentHash Intent hash.
* @param _nonce Nonce of the message sender address.
* @param _gasPrice Gas price that message sender is ready to pay to
* transfer message.
* @param _gasLimit Gas limit that message sender is ready to pay.
* @param _sender Message sender address.
* @param _hashLock Hash Lock provided by the facilitator.
*
* @return messageHash_ Hash unique for every request.
*/
function setMessage(
bytes32 _intentHash,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit,
address _sender,
bytes32 _hashLock
)
external
returns (bytes32 messageHash_)
{
MessageBus.Message memory message = getMessage(
_intentHash,
_nonce,
_gasPrice,
_gasLimit,
_sender,
_hashLock
);
messageHash_ = MessageBus.messageDigest(
message.intentHash,
message.nonce,
message.gasPrice,
message.gasLimit,
message.sender,
message.hashLock
);
messages[messageHash_] = message;
}
/**
* @notice It sets the status of inbox.
*
* @dev This is used for testing purpose.
*
* @param _messageHash It sets the status of the message.
* @param _status It sets the state of the message.
*/
function setInboxStatus(
bytes32 _messageHash,
MessageBus.MessageStatus _status
)
external
{
messageBox.inbox[_messageHash] = _status;
}
/**
* @notice It sets the status of outbox.
*
* @dev This is used for testing purpose.
*
* @param _messageHash MessageHash for which status is the be set.
* @param _status Status of the message to be set.
*/
function setOutboxStatus(
bytes32 _messageHash,
MessageBus.MessageStatus _status
)
external
{
messageBox.outbox[_messageHash] = _status;
}
/**
* @notice It sets the message hash for active inbox process.
*
* @dev This is used for testing purpose.
*
* @param _account Account address.
* @param _messageHash MessageHash for which status is the be set.
*/
function setInboxProcess(
address _account,
bytes32 _messageHash
)
external
{
super.registerInboxProcess(_account, 1, _messageHash);
}
/**
* @notice It sets the message hash for active outbox process.
*
* @dev This is used for testing purpose.
*
* @param _account Account address.
* @param _messageHash MessageHash for which status is the be set.
*/
function setOutboxProcess(
address _account,
bytes32 _messageHash
)
external
{
super.registerOutboxProcess(_account, 1, _messageHash);
}
/**
* @notice Method allows organization to propose new bounty amount.
*
* @dev This is used for testing purpose.
*
* @param _proposedBounty proposed bounty amount.
*
* @return uint256 proposed bounty amount.
*/
function initiateBountyAmountChange(uint256 _proposedBounty)
external
onlyOrganization
returns(uint256)
{
return initiateBountyAmountChangeInternal(_proposedBounty, BOUNTY_CHANGE_UNLOCK_PERIOD);
}
}
| 31,595 |
209 | // Sets the implementation address of the proxy./This is only meant to be called when upgrading self/The initial setImplementation for a proxy is set during/the proxy's initialization, not with this call/_newImplementation Address of the new implementation. | function setImplementation(address _newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(_newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, _newImplementation)
}
}
| function setImplementation(address _newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(_newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, _newImplementation)
}
}
| 47,726 |
55 | // require(newAmount > totalSupply() / 100000, "SwapTokensAtAmount must be greater than 0.001% of total supply"); | swapTokensAtAmount = newAmount;
emit SwapTokensAtAmountUpdated(newAmount);
| swapTokensAtAmount = newAmount;
emit SwapTokensAtAmountUpdated(newAmount);
| 28,641 |
30 | // Sets user's burn creditsSets total burn credits / | modifier burnWrapper(uint256 numberOfBatches, bool burningXen) {
| modifier burnWrapper(uint256 numberOfBatches, bool burningXen) {
| 30,214 |
33 | // returns total supply in current blockchain _blockNumber get total supply at specific blockreturn the totaly supply / | function totalSupplyLocal(uint256 _blockNumber)
public
view
returns (uint256)
| function totalSupplyLocal(uint256 _blockNumber)
public
view
returns (uint256)
| 5,022 |
88 | // Modifier that throws if called by any account other than the owneror the supplied role, or if the caller is not the owner and the role inquestion is paused. role The role to require unless the caller is the owner. Permittedroles are bot commander (0), and canceller (1), and pauser (2). / | modifier onlyOwnerOr(Role role) {
if (!isOwner()) {
require(_isRole(role), "Caller does not have a required role.");
require(!_isPaused(role), "Role in question is currently paused.");
}
_;
}
| modifier onlyOwnerOr(Role role) {
if (!isOwner()) {
require(_isRole(role), "Caller does not have a required role.");
require(!_isPaused(role), "Role in question is currently paused.");
}
_;
}
| 33,856 |
176 | // register the supported interfaces to conform to ERC721 via ERC165 | _registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
| _registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
| 2,590 |
13 | // я хочу понять, почему кошка сильнее собаки | pattern ИнфКакОбъектВосх
{
inf=ИнфКакОбъектВосх:export{ПЕРЕХОДНОСТЬ ПАДЕЖ ВИД МОДАЛЬНЫЙ node:root_node }
| pattern ИнфКакОбъектВосх
{
inf=ИнфКакОбъектВосх:export{ПЕРЕХОДНОСТЬ ПАДЕЖ ВИД МОДАЛЬНЫЙ node:root_node }
| 21,110 |
54 | // Make an investment based on pricing strategy This is a wrapper for buyTokens(), but the amount of tokens receiver willhave depends on the pricing strategy used.receiver The Ethereum address who receives the tokens customerId (optional) UUID v4 to track the successful payments on the server side' return tokensBought How mony tokens were bought / | function investInternal(address receiver, uint128 customerId) stopInEmergency internal returns(uint tokensBought) {
return buyTokens(receiver, customerId, pricingStrategy.calculatePrice(msg.value, weiRaised - presaleWeiRaised, tokensSold, msg.sender, token.decimals()));
}
| function investInternal(address receiver, uint128 customerId) stopInEmergency internal returns(uint tokensBought) {
return buyTokens(receiver, customerId, pricingStrategy.calculatePrice(msg.value, weiRaised - presaleWeiRaised, tokensSold, msg.sender, token.decimals()));
}
| 1,798 |
85 | // limits | uint256 private maxBuyAmount;
uint256 private maxSellAmount;
uint256 private maxWalletAmount;
uint256 private thresholdSwapAmount;
| uint256 private maxBuyAmount;
uint256 private maxSellAmount;
uint256 private maxWalletAmount;
uint256 private thresholdSwapAmount;
| 16,295 |
37 | // check referrer | address referrer = bytesToAddress(msg.data);
if (investors[referrer].deposit > 0 && referrer != msg.sender) {
user.referrer = referrer;
}
| address referrer = bytesToAddress(msg.data);
if (investors[referrer].deposit > 0 && referrer != msg.sender) {
user.referrer = referrer;
}
| 12,424 |
148 | // Returns the amount of ERC-20 $AWOO held by the specified address/account The holder account to check | function totalBalanceOf(address account) external view returns(uint256) {
return _virtualBalance[account] + balanceOf(account);
}
| function totalBalanceOf(address account) external view returns(uint256) {
return _virtualBalance[account] + balanceOf(account);
}
| 437 |
118 | // e.g. 8e36 / 10e18 = 8e17 | return z.div(y);
| return z.div(y);
| 25,944 |
64 | // 获取存款余额 | function balanceOf(address _tokenAddress, address _who)
public
view
returns (uint256 balance)
| function balanceOf(address _tokenAddress, address _who)
public
view
returns (uint256 balance)
| 19,698 |
1 | // Toggles bot protection, blocking suspicious transactions during liquidity events. / | function bpToggleOnOff() external onlyOwner {
bpEnabled = !bpEnabled;
}
| function bpToggleOnOff() external onlyOwner {
bpEnabled = !bpEnabled;
}
| 39,351 |
42 | // The ERC20 standard implementation. / | contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
| contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
| 35,036 |
27 | // Decrease the amount of tokens that an owner allowed to a spender.approve should be called when allowed_[_spender] == 0. To decrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.sol spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by. / | function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
| function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
| 522 |
47 | // check que length == TOTAL_UNIQUE_STICKERS Check that pool balance > 0 | require(winnersRemaining() > 0, "No more winners");
uint256 shirtNumberIndex;
| require(winnersRemaining() > 0, "No more winners");
uint256 shirtNumberIndex;
| 12,448 |
27 | // Function to get total active stakeHolders return returns the number/ | function getActiveStakeHoldersCount() public view isStakeHolder returns(uint32) {
return activeStakeHoldersCount;
}
| function getActiveStakeHoldersCount() public view isStakeHolder returns(uint32) {
return activeStakeHoldersCount;
}
| 23,553 |
51 | // Adds collateral addresses supported. Needed to make sure dollarBalances is correct | function addCollateral(address collat_addr) public onlyByOwnGov {
require(collat_addr != address(0), "Zero address detected");
require(collat_addr != address(FRAX), "FRAX is not collateral");
require(allowed_collaterals[collat_addr] == false, "Address already exists");
allowed_collaterals[collat_addr] = true;
collateral_addresses.push(collat_addr);
}
| function addCollateral(address collat_addr) public onlyByOwnGov {
require(collat_addr != address(0), "Zero address detected");
require(collat_addr != address(FRAX), "FRAX is not collateral");
require(allowed_collaterals[collat_addr] == false, "Address already exists");
allowed_collaterals[collat_addr] = true;
collateral_addresses.push(collat_addr);
}
| 74,984 |
111 | // Returns the amount of collateral locked in borrowing operations./collateral Valid collateral type./user Address of the user vault. | function locked(bytes32 collateral, address user)
public view
validCollateral(collateral)
returns (uint256)
| function locked(bytes32 collateral, address user)
public view
validCollateral(collateral)
returns (uint256)
| 78,335 |
11 | // Mapping from uid of a direct listing => offeror address => offer made to the direct listing by the respective offeror. | mapping(uint256 => mapping(address => Offer)) public offers;
| mapping(uint256 => mapping(address => Offer)) public offers;
| 23,899 |
101 | // JiaoziToken with Governance. | contract JiaoziToken is ERC20("JIAOZI.farm", "JIAOZI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
} | contract JiaoziToken is ERC20("JIAOZI.farm", "JIAOZI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
} | 36,462 |
0 | // Supply, limits and fees | uint256 private constant REWARDS_TRACKER_IDENTIFIER = 2;
uint256 private constant TOTAL_SUPPLY = 100000000000000 * (10**9);
uint256 public maxTxAmount = TOTAL_SUPPLY.mul(20).div(1000); // 2%
uint256 public maxWalletSize = TOTAL_SUPPLY.mul(20).div(1000); // 2%
uint256 private platformFee = 100; // 1%
uint256 private _previousPlatformFee = platformFee;
uint256 public devFee = 300; // 3%
| uint256 private constant REWARDS_TRACKER_IDENTIFIER = 2;
uint256 private constant TOTAL_SUPPLY = 100000000000000 * (10**9);
uint256 public maxTxAmount = TOTAL_SUPPLY.mul(20).div(1000); // 2%
uint256 public maxWalletSize = TOTAL_SUPPLY.mul(20).div(1000); // 2%
uint256 private platformFee = 100; // 1%
uint256 private _previousPlatformFee = platformFee;
uint256 public devFee = 300; // 3%
| 24,196 |
0 | // internal function to transfer of native token to a given recipient tothe recipient of the transfer. amountthe amount to transfer. / | function _performNativeTransfer(address to, uint256 amount) internal {
| function _performNativeTransfer(address to, uint256 amount) internal {
| 16,335 |
200 | // removes protected liquidity from a pool also burns governance tokens from the caller if the caller removes network tokens_idid in the caller's list of protected liquidity_portion portion of liquidity to remove, in PPM/ | function removeLiquidity(uint256 _id, uint32 _portion) external protected {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PERCENT");
ProtectedLiquidity memory liquidity = protectedLiquidity(_id);
Fraction memory addRate = Fraction({ n: liquidity.reserveRateN, d: liquidity.reserveRateD });
// verify input & permissions
require(liquidity.provider == msg.sender, "ERR_ACCESS_DENIED");
// verify that the pool is whitelisted
require(store.isPoolWhitelisted(liquidity.poolToken), "ERR_POOL_NOT_WHITELISTED");
if (_portion == PPM_RESOLUTION) {
// remove the pool tokens from the provider
store.removeProtectedLiquidity(_id);
}
else {
// remove portion of the pool tokens from the provider
uint256 fullPoolAmount = liquidity.poolAmount;
uint256 fullReserveAmount = liquidity.reserveAmount;
liquidity.poolAmount = liquidity.poolAmount.mul(_portion).div(PPM_RESOLUTION);
liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion).div(PPM_RESOLUTION);
store.updateProtectedLiquidityAmounts(_id, fullPoolAmount - liquidity.poolAmount, fullReserveAmount - liquidity.reserveAmount);
}
// add the pool tokens to the system
store.incSystemBalance(liquidity.poolToken, liquidity.poolAmount);
// if removing network token liquidity, burn the governance tokens from the caller
if (liquidity.reserveToken == networkToken) {
govToken.destroy(msg.sender, liquidity.reserveAmount);
}
// get the current rate between the reserves (recent average)
ILiquidityPoolV1Converter converter = ILiquidityPoolV1Converter(payable(liquidity.poolToken.owner()));
Fraction memory currentRate;
(currentRate.n, currentRate.d) = converter.recentAverageRate(liquidity.reserveToken);
// get the target token amount
uint256 targetAmount = removeLiquidityTargetAmount(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
addRate,
currentRate,
liquidity.timestamp,
time());
// remove network token liquidity
if (liquidity.reserveToken == networkToken) {
// mint network tokens for the caller and lock them
networkToken.issue(address(store), targetAmount);
lockTokens(msg.sender, targetAmount);
return;
}
// remove base token liquidity
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).mul(2).div(poolRate.n);
// limit the amount of pool tokens by the amount the system holds
uint256 systemBalance = store.systemBalance(liquidity.poolToken);
poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount;
// withdraw the pool tokens from the store
store.decSystemBalance(liquidity.poolToken, poolAmount);
store.withdrawTokens(liquidity.poolToken, address(this), poolAmount);
// remove liquidity
removeLiquidity(converter, poolAmount, liquidity.reserveToken, networkToken);
// transfer the base tokens to the caller
uint256 baseBalance;
if (liquidity.reserveToken == ETH_RESERVE_ADDRESS) {
baseBalance = address(this).balance;
msg.sender.transfer(baseBalance);
}
else {
baseBalance = liquidity.reserveToken.balanceOf(address(this));
safeTransfer(liquidity.reserveToken, msg.sender, baseBalance);
}
// compensate the caller with network tokens if still needed
if (baseBalance < targetAmount) {
uint256 delta = targetAmount - baseBalance;
// calculate the delta in network tokens
delta = delta.mul(currentRate.n).div(currentRate.d);
// the delta might be very small due to precision loss
// in which case no compensation will take place (gas optimization)
if (delta >= _minNetworkCompensation()) {
// check if there's enough network token balance, otherwise mint more
uint256 networkBalance = networkToken.balanceOf(address(this));
if (networkBalance < delta) {
networkToken.issue(address(this), delta - networkBalance);
}
// lock network tokens for the caller
safeTransfer(networkToken, address(store), delta);
lockTokens(msg.sender, delta);
}
}
// if the contract still holds network token, burn them
uint256 networkBalance = networkToken.balanceOf(address(this));
if (networkBalance > 0) {
networkToken.destroy(address(this), networkBalance);
}
}
| function removeLiquidity(uint256 _id, uint32 _portion) external protected {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PERCENT");
ProtectedLiquidity memory liquidity = protectedLiquidity(_id);
Fraction memory addRate = Fraction({ n: liquidity.reserveRateN, d: liquidity.reserveRateD });
// verify input & permissions
require(liquidity.provider == msg.sender, "ERR_ACCESS_DENIED");
// verify that the pool is whitelisted
require(store.isPoolWhitelisted(liquidity.poolToken), "ERR_POOL_NOT_WHITELISTED");
if (_portion == PPM_RESOLUTION) {
// remove the pool tokens from the provider
store.removeProtectedLiquidity(_id);
}
else {
// remove portion of the pool tokens from the provider
uint256 fullPoolAmount = liquidity.poolAmount;
uint256 fullReserveAmount = liquidity.reserveAmount;
liquidity.poolAmount = liquidity.poolAmount.mul(_portion).div(PPM_RESOLUTION);
liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion).div(PPM_RESOLUTION);
store.updateProtectedLiquidityAmounts(_id, fullPoolAmount - liquidity.poolAmount, fullReserveAmount - liquidity.reserveAmount);
}
// add the pool tokens to the system
store.incSystemBalance(liquidity.poolToken, liquidity.poolAmount);
// if removing network token liquidity, burn the governance tokens from the caller
if (liquidity.reserveToken == networkToken) {
govToken.destroy(msg.sender, liquidity.reserveAmount);
}
// get the current rate between the reserves (recent average)
ILiquidityPoolV1Converter converter = ILiquidityPoolV1Converter(payable(liquidity.poolToken.owner()));
Fraction memory currentRate;
(currentRate.n, currentRate.d) = converter.recentAverageRate(liquidity.reserveToken);
// get the target token amount
uint256 targetAmount = removeLiquidityTargetAmount(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
addRate,
currentRate,
liquidity.timestamp,
time());
// remove network token liquidity
if (liquidity.reserveToken == networkToken) {
// mint network tokens for the caller and lock them
networkToken.issue(address(store), targetAmount);
lockTokens(msg.sender, targetAmount);
return;
}
// remove base token liquidity
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).mul(2).div(poolRate.n);
// limit the amount of pool tokens by the amount the system holds
uint256 systemBalance = store.systemBalance(liquidity.poolToken);
poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount;
// withdraw the pool tokens from the store
store.decSystemBalance(liquidity.poolToken, poolAmount);
store.withdrawTokens(liquidity.poolToken, address(this), poolAmount);
// remove liquidity
removeLiquidity(converter, poolAmount, liquidity.reserveToken, networkToken);
// transfer the base tokens to the caller
uint256 baseBalance;
if (liquidity.reserveToken == ETH_RESERVE_ADDRESS) {
baseBalance = address(this).balance;
msg.sender.transfer(baseBalance);
}
else {
baseBalance = liquidity.reserveToken.balanceOf(address(this));
safeTransfer(liquidity.reserveToken, msg.sender, baseBalance);
}
// compensate the caller with network tokens if still needed
if (baseBalance < targetAmount) {
uint256 delta = targetAmount - baseBalance;
// calculate the delta in network tokens
delta = delta.mul(currentRate.n).div(currentRate.d);
// the delta might be very small due to precision loss
// in which case no compensation will take place (gas optimization)
if (delta >= _minNetworkCompensation()) {
// check if there's enough network token balance, otherwise mint more
uint256 networkBalance = networkToken.balanceOf(address(this));
if (networkBalance < delta) {
networkToken.issue(address(this), delta - networkBalance);
}
// lock network tokens for the caller
safeTransfer(networkToken, address(store), delta);
lockTokens(msg.sender, delta);
}
}
// if the contract still holds network token, burn them
uint256 networkBalance = networkToken.balanceOf(address(this));
if (networkBalance > 0) {
networkToken.destroy(address(this), networkBalance);
}
}
| 41,449 |
11 | // if draw is not init, then use draw at 0 | draw = drawRingBuffer[0];
| draw = drawRingBuffer[0];
| 34,126 |
212 | // Reverse time to 00:00 UTC and then add 13 hours | startTimestamp = startTimestamp / 1 days * 1 days + 13 hours;
| startTimestamp = startTimestamp / 1 days * 1 days + 13 hours;
| 24,398 |
27 | // Lets the contract receives native tokens from `nativeTokenWrapper` withdraw. | receive() external payable {}
/// @dev Returns the type of the contract.
function contractType() external pure returns (bytes32) {
return MODULE_TYPE;
}
| receive() external payable {}
/// @dev Returns the type of the contract.
function contractType() external pure returns (bytes32) {
return MODULE_TYPE;
}
| 4,066 |
66 | // Inverts the stored [`from`, `to`] route and stores this as a new route. | function generateInvertedRoute(IERC20 from, IERC20 to) private {
delete routes[to][from];
uint256 length = routes[from][to].length;
uint256 index;
RouteStep memory step;
for (uint256 i = 0; i < length; i++) {
index = length - 1 - i;
step = routes[from][to][index];
routes[to][from].push(
RouteStep({
from: step.to,
pair: step.pair,
to: step.from,
amountsOutNominator: step.amountsOutNominator,
amountsOutDenominator: step.amountsOutDenominator
})
);
}
}
| function generateInvertedRoute(IERC20 from, IERC20 to) private {
delete routes[to][from];
uint256 length = routes[from][to].length;
uint256 index;
RouteStep memory step;
for (uint256 i = 0; i < length; i++) {
index = length - 1 - i;
step = routes[from][to][index];
routes[to][from].push(
RouteStep({
from: step.to,
pair: step.pair,
to: step.from,
amountsOutNominator: step.amountsOutNominator,
amountsOutDenominator: step.amountsOutDenominator
})
);
}
}
| 18,418 |
229 | // SetToken must be in a pending state and module must be in pending state / | function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
}
| function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
}
| 22,200 |
15 | // Keep track of cumulative ETH funds for which the tokens have been claimed | uint public funds_claimed;
| uint public funds_claimed;
| 39,471 |
2 | // Post call gas limit (Prevents overspending of gas) | uint256 public maxPostCallGasUsage = 350000;
| uint256 public maxPostCallGasUsage = 350000;
| 11,320 |
27 | // Converts user's components into Set Tokens held directly in Vault instead of user's account_setAddress of the Set _quantity Number of tokens to redeem / | function issueInVault(
| function issueInVault(
| 8,647 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.