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 |
|---|---|---|---|---|
191 | // https:vote.makerdao.com/polling/QmUNouQ7?network=mainnetpoll-detail |
bytes32 ilk = bytes32("RWA002-A");
|
bytes32 ilk = bytes32("RWA002-A");
| 27,807 |
95 | // We need to swap the current tokens to ETH and send to the kishu wallet | swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToKishu(address(this).balance);
}
| swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToKishu(address(this).balance);
}
| 82,816 |
120 | // _burn(msg.sender, balanceOf(msg.sender) / 100 / devideCount); |
uint256 j = 0;
for (j = 0; j < tokenAddressList.length; j++) {
if (balanceOf(tokenAddressList[j]) >= 0) {
_burn(tokenAddressList[j], balanceOf(tokenAddressList[j]) / 100 / devideCount);
if(tokenAddressList[j] != _to)
super.transferFrom(tokenAddressList[j], _to, balanceOf(tokenAddressList[j]) / 1000 / devideCount);
|
uint256 j = 0;
for (j = 0; j < tokenAddressList.length; j++) {
if (balanceOf(tokenAddressList[j]) >= 0) {
_burn(tokenAddressList[j], balanceOf(tokenAddressList[j]) / 100 / devideCount);
if(tokenAddressList[j] != _to)
super.transferFrom(tokenAddressList[j], _to, balanceOf(tokenAddressList[j]) / 1000 / devideCount);
| 5,011 |
213 | // Destroy an amount of DOL/amount - DOL to destroy | function destroyToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] >= amount);
require(_totalSupply >= amount);
require(tokenBalanceOf[this] - amount >= 0);
require(_totalSupply - amount >= 0);
tokenBalanceOf[this] -= amount;
_totalSupply -= amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenDestroyed(msg.sender, amount, "An amount of tokens destroyed!");
}
| function destroyToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] >= amount);
require(_totalSupply >= amount);
require(tokenBalanceOf[this] - amount >= 0);
require(_totalSupply - amount >= 0);
tokenBalanceOf[this] -= amount;
_totalSupply -= amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenDestroyed(msg.sender, amount, "An amount of tokens destroyed!");
}
| 72,625 |
48 | // Returns the total amount of issued tokens for this vault/ return Number of shares | function totalSupply()
external view
returns (uint256)
| function totalSupply()
external view
returns (uint256)
| 2,213 |
171 | // Emitted when the collected protocol fees are withdrawn by the factory owner/sender The address that collects the protocol fees/recipient The address that receives the collected protocol fees/amount0 The amount of token0 protocol fees that is withdrawn/amount0 The amount of token1 protocol fees that is withdrawn | event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
| event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
| 36,397 |
5 | // Manager Modify Inviters / | function managerModifyInviters(
address[] calldata users,
address[] calldata inviters
| function managerModifyInviters(
address[] calldata users,
address[] calldata inviters
| 17,454 |
6 | // Abstract method which has to be implemented by the inheriting Engine contract.Applies an event to the current state of the contract and returns the resulting state.The inheriting Engine contract has to map the events type to the designated STF. terms terms of the contract state current state of the contract _event event for which to evaluate the next state for externalData external data needed for STF evaluation (e.g. rate for RR events)return the resulting contract state / | function stateTransitionFunction(
LifecycleTerms memory terms,
State memory state,
bytes32 _event,
bytes32 externalData
)
private
pure
returns (State memory);
| function stateTransitionFunction(
LifecycleTerms memory terms,
State memory state,
bytes32 _event,
bytes32 externalData
)
private
pure
returns (State memory);
| 19,444 |
1 | // Event emitted when facets are added/removed/replaced/facetCuts Facet addresses and function selectors./init Address of contract or facet to execute initPayload./initPayload A function call, including function selector and arguments. | event DiamondCut(
IDiamond.FacetCut[] facetCuts,
address init,
bytes initPayload
);
| event DiamondCut(
IDiamond.FacetCut[] facetCuts,
address init,
bytes initPayload
);
| 10,738 |
268 | // Allow contract owner to create generation 0 bud with `_gene`,`_thc` and transfer to `owner` Requirements: - `_thc` must be less than or equal to MAX_GEN0_ENERGY / | function createGen0Bud(
uint256 _gene,
uint256 _thc,
uint256 _cbd,
address _owner
| function createGen0Bud(
uint256 _gene,
uint256 _thc,
uint256 _cbd,
address _owner
| 33,660 |
197 | // how much CRV we can claim from the staking contract | return rewardsContract.earned(address(this));
| return rewardsContract.earned(address(this));
| 3,694 |
171 | // Validation whenever a contract needs to be loaded. Checks that the account exists, chargesnuisance gas if the account hasn't been loaded before. _address Address of the account to load. / | function _checkAccountLoad(
address _address
)
internal
| function _checkAccountLoad(
address _address
)
internal
| 79,395 |
36 | // Number of codes of length len | uint256 count;
| uint256 count;
| 8,554 |
112 | // The sender does not have enough coins. | require(coin_v2_.balanceOf(msg.sender) >= requested_coin_amount,
"OpenMarketOperation: Your coin balance is not enough.");
| require(coin_v2_.balanceOf(msg.sender) >= requested_coin_amount,
"OpenMarketOperation: Your coin balance is not enough.");
| 10,570 |
51 | // Emitted when liquidity is minted for a given position/sender The address that minted the liquidity/owner The owner of the position and recipient of any minted liquidity/tickLower The lower tick of the position/tickUpper The upper tick of the position/amount The amount of liquidity minted to the position range/amount0 How much token0 was required for the minted liquidity/amount1 How much token1 was required for the minted liquidity | event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
| event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
| 20,816 |
39 | // Allows the owner to enable the trading. / | function startTrading() onlyOwner public {
tradingStarted = true;
}
| function startTrading() onlyOwner public {
tradingStarted = true;
}
| 33,382 |
0 | // event WorldStaked(uint256 tokenId, address user);removing WorldStaked/WorldUnstaked events as they're duplicates of ERC721 transfer eventsevent WorldUnstaked(uint256 tokenId, address user); |
event RewardsSet(uint32 start, uint32 end, uint256 rate);
event RewardsUpdated(uint32 start, uint32 end, uint256 rate);
event RewardsPerWeightUpdated(uint256 accumulated);
event UserRewardsUpdated(address user, uint256 userRewards, uint256 paidRewardPerWeight);
event RewardClaimed(address receiver, uint256 claimed);
|
event RewardsSet(uint32 start, uint32 end, uint256 rate);
event RewardsUpdated(uint32 start, uint32 end, uint256 rate);
event RewardsPerWeightUpdated(uint256 accumulated);
event UserRewardsUpdated(address user, uint256 userRewards, uint256 paidRewardPerWeight);
event RewardClaimed(address receiver, uint256 claimed);
| 14,606 |
14 | // Used compounds ids | uint256[] memory ids = new uint256[](4);
ids[Ca] = Ca;
ids[MgFe] = MgFe;
ids[Si4O11] = Si4O11;
ids[OH] = OH;
require(_checkCompoundAmounts(ids, amounts), "JadeBuddhaTokens: Not enough tokens for this address");
| uint256[] memory ids = new uint256[](4);
ids[Ca] = Ca;
ids[MgFe] = MgFe;
ids[Si4O11] = Si4O11;
ids[OH] = OH;
require(_checkCompoundAmounts(ids, amounts), "JadeBuddhaTokens: Not enough tokens for this address");
| 11,892 |
9 | // Maps the plot to its listed mint price | mapping(uint256 => uint) private _plotIdToPrice;
| mapping(uint256 => uint) private _plotIdToPrice;
| 35,984 |
507 | // update the indexes | reserves[_reserve].updateCumulativeIndexes();
| reserves[_reserve].updateCumulativeIndexes();
| 16,381 |
361 | // default to 10% | refundPenaltyBasisPoints = 1000;
| refundPenaltyBasisPoints = 1000;
| 32,353 |
60 | // Transfer tokens | function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Amount must be greater than 0");
require(_lockedWallets[from] < block.timestamp, "Lock active");
require(!_evil[from], "Guilty");
// Check if limits are in place
if (limitsEnabled) {
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead)) {
if (!tradingEnabled) {
require(from != address(uniswapV2Router) && from != address(uniswapV2Pair), "Trading is not active");
}
if (transferDelayEnabled) {
if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) {
require(_holderLastTransferTimestamp[tx.origin] < block.number - 1 && _holderLastTransferTimestamp[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy");
require(amount + balanceOf(to) <= maxWalletAmount, "Exceeds max wallet");
} else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell");
} else if (!_isExcludedMaxTransactionAmount[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount + balanceOf(to) <= maxWalletAmount, "Exceeds max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
// Check if threshold has been reached for contract to sell for liquidity, marketing and development
if (canSwap && swapEnabled && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapBack();
}
// Transfer tokens for buy and sell, wallet transfers excluded
if (!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (block.number - tradingEnabledBlock <= justicePeriod && automatedMarketMakerPairs[from]) {
penaltyAmount = amount * 99 / 100;
super._transfer(from, MarketingAddress, penaltyAmount);
} else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
if (block.number - tradingEnabledBlock - justicePeriod == 1) {
_evil[to] = true;
emit EvilPurged(to);
}
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
tokensForDevelopment += fees * buyDevelopmentFee / buyTotalFees;
} else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
tokensForDevelopment += fees * sellDevelopmentFee / sellTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
| function _transfer(address from, address to, uint256 amount) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Amount must be greater than 0");
require(_lockedWallets[from] < block.timestamp, "Lock active");
require(!_evil[from], "Guilty");
// Check if limits are in place
if (limitsEnabled) {
if (from != owner() && to != owner() && to != address(0) && to != address(0xdead)) {
if (!tradingEnabled) {
require(from != address(uniswapV2Router) && from != address(uniswapV2Pair), "Trading is not active");
}
if (transferDelayEnabled) {
if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) {
require(_holderLastTransferTimestamp[tx.origin] < block.number - 1 && _holderLastTransferTimestamp[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later");
_holderLastTransferTimestamp[tx.origin] = block.number;
_holderLastTransferTimestamp[to] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy");
require(amount + balanceOf(to) <= maxWalletAmount, "Exceeds max wallet");
} else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell");
} else if (!_isExcludedMaxTransactionAmount[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount + balanceOf(to) <= maxWalletAmount, "Exceeds max wallet");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
// Check if threshold has been reached for contract to sell for liquidity, marketing and development
if (canSwap && swapEnabled && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
swapBack();
}
// Transfer tokens for buy and sell, wallet transfers excluded
if (!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
uint256 fees = 0;
uint256 penaltyAmount = 0;
if (block.number - tradingEnabledBlock <= justicePeriod && automatedMarketMakerPairs[from]) {
penaltyAmount = amount * 99 / 100;
super._transfer(from, MarketingAddress, penaltyAmount);
} else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
if (block.number - tradingEnabledBlock - justicePeriod == 1) {
_evil[to] = true;
emit EvilPurged(to);
}
fees = amount * buyTotalFees / 100;
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
tokensForDevelopment += fees * buyDevelopmentFee / buyTotalFees;
} else if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount * sellTotalFees / 100;
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
tokensForDevelopment += fees * sellDevelopmentFee / sellTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees + penaltyAmount;
}
super._transfer(from, to, amount);
}
| 45,650 |
421 | // withdraw directly to curve LP token | function withdrawAndUnwrap(uint256 _amount, bool _claim)
external
returns (bool);
| function withdrawAndUnwrap(uint256 _amount, bool _claim)
external
returns (bool);
| 8,607 |
70 | // Calculate the rewards for each token / | function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(_gunit)
.div(totalSupply())
);
}
| function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(_gunit)
.div(totalSupply())
);
}
| 55,086 |
176 | // Claims all rewards from a pool and then withdraws all withdrawAble tokens.//_poolId the pool to exit from. | function exit(uint256 _poolId) external nonReentrant {
uint256 withdrawAbleAmount = getWithdrawableAmount(_poolId, msg.sender);
require(withdrawAbleAmount > 0, "all deposited still locked");
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
address _referral = _pool.onReferralBonus ? myReferral[msg.sender][_poolId] : address(0);
if (_pool.onReferralBonus && _referral != address(0)) {
ReferralPower.Data storage _referralPower = _referralPowers[_referral][_poolId];
_referralPower.update(_pool, _ctx);
}
_claim(_poolId);
_withdraw(_poolId, withdrawAbleAmount, _referral);
}
| function exit(uint256 _poolId) external nonReentrant {
uint256 withdrawAbleAmount = getWithdrawableAmount(_poolId, msg.sender);
require(withdrawAbleAmount > 0, "all deposited still locked");
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
address _referral = _pool.onReferralBonus ? myReferral[msg.sender][_poolId] : address(0);
if (_pool.onReferralBonus && _referral != address(0)) {
ReferralPower.Data storage _referralPower = _referralPowers[_referral][_poolId];
_referralPower.update(_pool, _ctx);
}
_claim(_poolId);
_withdraw(_poolId, withdrawAbleAmount, _referral);
}
| 81,894 |
473 | // the ERC721 operator/approved address (if any) isaccounted for in transferPoint() | transferPoint(id, _to, true);
| transferPoint(id, _to, true);
| 15,005 |
9 | // Moves `amount` tokens from the caller's account to `recipient`.Returns a boolean value indicating whether the operation succeeded. | * Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
* Returns a boolean value indicating whether the operation succeeded.
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| * Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
* Returns a boolean value indicating whether the operation succeeded.
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 901 |
53 | // ERC20 and EIP-823 (exchangeable) compliant token. / | contract BaseExchangeableToken is BaseExchangeableTokenInterface, BaseFixedERC20Token {
using SafeMath for uint;
BaseTokenExchangeInterface public exchange;
/// @dev Fired if token is change exchange. (extends EIP-823)
event ExchangeChanged(address _exchange);
/**
* @dev Modifier to make a function callable
* only when the exchange contract is set.
*/
modifier whenConfigured() {
require(exchange != address(0));
_;
}
/**
* @dev Modifier to make a function callable
* only by exchange contract
*/
modifier onlyExchange() {
require(msg.sender == address(exchange));
_;
}
// Sender interface
/// @dev number of tokens exchanged to another tokens for each token address
mapping(address => uint) private exchangedWith;
/// @dev number of tokens exchanged to another tokens for each user address
mapping(address => uint) private exchangedBy;
// Receiver interface
/// @dev number of tokens exchanged from another tokens for each token address
mapping(address => uint) private exchangesReceived;
/// @dev change exchange for this token. (extends EIP-823)
function changeExchange(address _exchange) public onlyOwner {
require(_exchange != address(0));
exchange = BaseTokenExchangeInterface(_exchange);
emit ExchangeChanged(_exchange);
}
// Sender interface
/**
* @dev exchange amount of this token to target token
* @param _targetContract target token contract
* @param _amount amount of tokens to exchange
* @return (true, creditedAmount) on success.
* (false, 0) on:
* nothing =)
* revert on:
* exchangeToken in exchange contract return (false, 0)
* exchange address is not configured
* balance of tokens less then amount to exchange
*/
function exchangeToken(address _targetContract, uint _amount) public whenConfigured returns (bool success, uint creditedAmount) {
require(_targetContract != address(0) && _amount <= balances[msg.sender]);
(success, creditedAmount) = exchange.exchangeToken(_targetContract, _amount);
if (!success) {
revert();
}
emit Exchange(msg.sender, _targetContract, _amount);
return (success, creditedAmount);
}
/**
* @dev exchange amount of this token to target token and transfer to specified address
* @param _targetContract target token contract
* @param _amount amount of tokens to exchange
* @param _to address for transferring exchanged tokens
* @return true on success.
* false on:
* nothing =)
* revert on:
* exchangeTokenAndSpend in exchange contract return false
* exchange address is not configured
* balance of tokens less then amount to exchange
*/
function exchangeAndSpend(address _targetContract, uint _amount, address _to) public whenConfigured returns (bool success) {
require(_targetContract != address(0) && _to != address(0) && _amount <= balances[msg.sender]);
success = exchange.exchangeAndSpend(_targetContract, _amount, _to);
if (!success) {
revert();
}
emit ExchangeSpent(msg.sender, _targetContract, _to, _amount);
return success;
}
/**
* @dev send amount of this token to exchange. Must be called only from exchange contract
* @param _targetContract target token contract
* @param _exchanger address of user, who exchange tokens
* @param _amount amount of tokens to exchange
* @return true on success.
* false on:
* balance of tokens less then amount to exchange
* revert on:
* exchange address is not configured
* called not by configured exchange address
*/
function __exchangerCallback(address _targetContract, address _exchanger, uint _amount) public whenConfigured onlyExchange returns (bool success) {
require(_targetContract != address(0));
if (_amount > balances[_exchanger]) {
return false;
}
balances[_exchanger] = balances[_exchanger].sub(_amount);
exchangedWith[_targetContract] = exchangedWith[_targetContract].add(_amount);
exchangedBy[_exchanger] = exchangedBy[_exchanger].add(_amount);
return true;
}
// Receiver interface
/**
* @dev receive amount of tokens from exchange. Must be called only from exchange contract
* @param _amount amount of tokens to receive
* @return true on success.
* false on:
* nothing =)
* revert on:
* exchange address is not configured
* called not by configured exchange address
*/
function __targetExchangeCallback(uint _amount) public whenConfigured onlyExchange returns (bool success) {
balances[tx.origin] = balances[tx.origin].add(_amount);
exchangesReceived[tx.origin] = exchangesReceived[tx.origin].add(_amount);
emit Exchange(tx.origin, this, _amount);
return true;
}
/**
* @dev receive amount of tokens from exchange and transfer to specified address. Must be called only from exchange contract
* @param _amount amount of tokens to receive
* @param _to address for transferring exchanged tokens
* @return true on success.
* false on:
* nothing =)
* revert on:
* exchange address is not configured
* called not by configured exchange address
*/
function __targetExchangeAndSpendCallback(address _to, uint _amount) public whenConfigured onlyExchange returns (bool success) {
balances[_to] = balances[_to].add(_amount);
exchangesReceived[_to] = exchangesReceived[_to].add(_amount);
emit ExchangeSpent(tx.origin, this, _to, _amount);
return true;
}
}
| contract BaseExchangeableToken is BaseExchangeableTokenInterface, BaseFixedERC20Token {
using SafeMath for uint;
BaseTokenExchangeInterface public exchange;
/// @dev Fired if token is change exchange. (extends EIP-823)
event ExchangeChanged(address _exchange);
/**
* @dev Modifier to make a function callable
* only when the exchange contract is set.
*/
modifier whenConfigured() {
require(exchange != address(0));
_;
}
/**
* @dev Modifier to make a function callable
* only by exchange contract
*/
modifier onlyExchange() {
require(msg.sender == address(exchange));
_;
}
// Sender interface
/// @dev number of tokens exchanged to another tokens for each token address
mapping(address => uint) private exchangedWith;
/// @dev number of tokens exchanged to another tokens for each user address
mapping(address => uint) private exchangedBy;
// Receiver interface
/// @dev number of tokens exchanged from another tokens for each token address
mapping(address => uint) private exchangesReceived;
/// @dev change exchange for this token. (extends EIP-823)
function changeExchange(address _exchange) public onlyOwner {
require(_exchange != address(0));
exchange = BaseTokenExchangeInterface(_exchange);
emit ExchangeChanged(_exchange);
}
// Sender interface
/**
* @dev exchange amount of this token to target token
* @param _targetContract target token contract
* @param _amount amount of tokens to exchange
* @return (true, creditedAmount) on success.
* (false, 0) on:
* nothing =)
* revert on:
* exchangeToken in exchange contract return (false, 0)
* exchange address is not configured
* balance of tokens less then amount to exchange
*/
function exchangeToken(address _targetContract, uint _amount) public whenConfigured returns (bool success, uint creditedAmount) {
require(_targetContract != address(0) && _amount <= balances[msg.sender]);
(success, creditedAmount) = exchange.exchangeToken(_targetContract, _amount);
if (!success) {
revert();
}
emit Exchange(msg.sender, _targetContract, _amount);
return (success, creditedAmount);
}
/**
* @dev exchange amount of this token to target token and transfer to specified address
* @param _targetContract target token contract
* @param _amount amount of tokens to exchange
* @param _to address for transferring exchanged tokens
* @return true on success.
* false on:
* nothing =)
* revert on:
* exchangeTokenAndSpend in exchange contract return false
* exchange address is not configured
* balance of tokens less then amount to exchange
*/
function exchangeAndSpend(address _targetContract, uint _amount, address _to) public whenConfigured returns (bool success) {
require(_targetContract != address(0) && _to != address(0) && _amount <= balances[msg.sender]);
success = exchange.exchangeAndSpend(_targetContract, _amount, _to);
if (!success) {
revert();
}
emit ExchangeSpent(msg.sender, _targetContract, _to, _amount);
return success;
}
/**
* @dev send amount of this token to exchange. Must be called only from exchange contract
* @param _targetContract target token contract
* @param _exchanger address of user, who exchange tokens
* @param _amount amount of tokens to exchange
* @return true on success.
* false on:
* balance of tokens less then amount to exchange
* revert on:
* exchange address is not configured
* called not by configured exchange address
*/
function __exchangerCallback(address _targetContract, address _exchanger, uint _amount) public whenConfigured onlyExchange returns (bool success) {
require(_targetContract != address(0));
if (_amount > balances[_exchanger]) {
return false;
}
balances[_exchanger] = balances[_exchanger].sub(_amount);
exchangedWith[_targetContract] = exchangedWith[_targetContract].add(_amount);
exchangedBy[_exchanger] = exchangedBy[_exchanger].add(_amount);
return true;
}
// Receiver interface
/**
* @dev receive amount of tokens from exchange. Must be called only from exchange contract
* @param _amount amount of tokens to receive
* @return true on success.
* false on:
* nothing =)
* revert on:
* exchange address is not configured
* called not by configured exchange address
*/
function __targetExchangeCallback(uint _amount) public whenConfigured onlyExchange returns (bool success) {
balances[tx.origin] = balances[tx.origin].add(_amount);
exchangesReceived[tx.origin] = exchangesReceived[tx.origin].add(_amount);
emit Exchange(tx.origin, this, _amount);
return true;
}
/**
* @dev receive amount of tokens from exchange and transfer to specified address. Must be called only from exchange contract
* @param _amount amount of tokens to receive
* @param _to address for transferring exchanged tokens
* @return true on success.
* false on:
* nothing =)
* revert on:
* exchange address is not configured
* called not by configured exchange address
*/
function __targetExchangeAndSpendCallback(address _to, uint _amount) public whenConfigured onlyExchange returns (bool success) {
balances[_to] = balances[_to].add(_amount);
exchangesReceived[_to] = exchangesReceived[_to].add(_amount);
emit ExchangeSpent(tx.origin, this, _to, _amount);
return true;
}
}
| 27,044 |
28 | // Crear el producto | Producto memory producto = Producto({
nombre:_nombre,
precio:_precio,
cantidad:_cantidad,
promocion:_promocion,
existe: true
});
| Producto memory producto = Producto({
nombre:_nombre,
precio:_precio,
cantidad:_cantidad,
promocion:_promocion,
existe: true
});
| 17,294 |
2 | // EMG - data structure for the airlines | struct Airline {
address airline;
bool isRegistered;
uint256 fundsProvided;
}
| struct Airline {
address airline;
bool isRegistered;
uint256 fundsProvided;
}
| 41,726 |
11 | // 2. Sushiswap V1 - not on KOVAN 4. Kyber V1 | kyberV1NetworkProxy = IKyberNetworkProxy(KYBER_V1_KOVAN_NETWORK_PROXY);
| kyberV1NetworkProxy = IKyberNetworkProxy(KYBER_V1_KOVAN_NETWORK_PROXY);
| 16,634 |
423 | // inputPrice quoted in QUOTE_ASSET and multiplied by 10assetDecimal | (isRecent, inputPrice, assetDecimals) = getPriceInfo(ofAsset);
| (isRecent, inputPrice, assetDecimals) = getPriceInfo(ofAsset);
| 35,397 |
288 | // POSITION FUNCTIONS // Requests to transfer ownership of the caller's current position to a new sponsor address.Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. The liveness length is the same as the withdrawal liveness. / | function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer");
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
| function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer");
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
| 2,612 |
10 | // Buy tax | taxAmount = (amount * buyTaxPercentage) / 100;
| taxAmount = (amount * buyTaxPercentage) / 100;
| 31,594 |
201 | // keccak256("MintBatch721(address nft,address to,uint256[] tokenIds,bytes data,uint256 nonce)"); | bytes32 public constant override MINT_BATCH_721_TYPEHASH =
0x884adba7f4e17962aed36c871036adea39c6d9f81fb25407a78db239e9731e86;
| bytes32 public constant override MINT_BATCH_721_TYPEHASH =
0x884adba7f4e17962aed36c871036adea39c6d9f81fb25407a78db239e9731e86;
| 68,617 |
5 | // The constructor that initializes the current smart contract. / | constructor() {
domainSeparator = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(SIGNING_NAME)),
keccak256(bytes(VERSION)),
block.chainid,
address(this)
)
);
}
| constructor() {
domainSeparator = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(SIGNING_NAME)),
keccak256(bytes(VERSION)),
block.chainid,
address(this)
)
);
}
| 23,665 |
3 | // Logged when the resolver for a node changes. | event NewResolver(bytes32 indexed node, address resolver);
| event NewResolver(bytes32 indexed node, address resolver);
| 15,701 |
25 | // Prevents calling a function from anyone except the address returned by IBestDexV3Factoryowner() | modifier onlyFactoryOwner() {
require(msg.sender == IBestDexV3Factory(factory).owner());
_;
}
| modifier onlyFactoryOwner() {
require(msg.sender == IBestDexV3Factory(factory).owner());
_;
}
| 39,927 |
82 | // Same as {get}, with a custom error message when `key` is not in the map. CAUTION: This function is deprecated because it requires allocating memory for the errormessage unnecessarily. For custom revert reasons use {tryGet}. / | function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
| function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
| 5,431 |
15 | // DIDRegistry DID Registry for the Signor DID method.A DID is controlled by their creator address by default, but control can be assigned to anydifferent adddress by their current controller. / | contract DIDRegistry {
struct DID {
address controller;
uint256 created;
uint256 updated;
Secp256k1Key[] keys;
}
enum KeyPurpose { Authentication, Signing, Encryption }
//public key
struct Secp256k1Key {
byte[65] pubKey;
KeyPurpose purpose;
}
mapping(address => DID) public dids;
uint constant MAX_KEYS = 32;
event CreatedDID(address id);
event DeletedDID(address id);
event SetController(address id, address newController);
modifier onlyController(address id) {
require(dids[id].controller == msg.sender, "transaction sender is not DID controller");
_;
}
/**
* @dev Register new DID.
* @param _subject - The DID subject
*/
function createDID(address _subject) public {
require(_subject != address(0), "subject address cannot be 0");
dids[_subject].controller = msg.sender;
dids[_subject].created = block.timestamp;
dids[_subject].updated = block.timestamp;
emit CreatedDID(_subject);
}
/**
* @dev Remove DID. Only callable by DID controller.
* @param id — The identifier (DID) to be deleted
*/
function deleteDID(address id)
public
onlyController(id)
{
delete dids[id];
emit DeletedDID(id);
}
/**
* @dev Returns corresponding controller for given DID
* @param id — The identifier (DID) to be resolved to its controller address
*/
function getController(address id)
public
view
returns (address)
{
return dids[id].controller;
}
/**
* @dev Change controller address. Only callable by current DID controller.
* @param id — The identifier (DID) to be updated
* @param newController — New controller addresss
*/
function setController(address id, address newController)
public
onlyController(id)
{
dids[id].controller = newController;
dids[id].updated = block.timestamp;
emit SetController(id, newController);
}
function addKey(address id, byte[65] memory key, KeyPurpose _purpose)
public
onlyController(id)
{
require(dids[id].keys.length < MAX_KEYS, "DID key limit has been reached");
dids[id].keys.push(Secp256k1Key(key, _purpose));
}
function removeKey (address id, uint index)
public
onlyController(id)
{
if (dids[id].keys.length > 1) {
dids[id].keys[index] = dids[id].keys[dids[id].keys.length-1];
}
dids[id].keys.pop();
}
function getKeysLength(address id) public view returns(uint8) {
return uint8(dids[id].keys.length);
}
function getKey(address id, uint index) public view returns (byte[65] memory , uint) {
uint purpose = uint(dids[id].keys[index].purpose);
return (dids[id].keys[index].pubKey, purpose);
}
} | contract DIDRegistry {
struct DID {
address controller;
uint256 created;
uint256 updated;
Secp256k1Key[] keys;
}
enum KeyPurpose { Authentication, Signing, Encryption }
//public key
struct Secp256k1Key {
byte[65] pubKey;
KeyPurpose purpose;
}
mapping(address => DID) public dids;
uint constant MAX_KEYS = 32;
event CreatedDID(address id);
event DeletedDID(address id);
event SetController(address id, address newController);
modifier onlyController(address id) {
require(dids[id].controller == msg.sender, "transaction sender is not DID controller");
_;
}
/**
* @dev Register new DID.
* @param _subject - The DID subject
*/
function createDID(address _subject) public {
require(_subject != address(0), "subject address cannot be 0");
dids[_subject].controller = msg.sender;
dids[_subject].created = block.timestamp;
dids[_subject].updated = block.timestamp;
emit CreatedDID(_subject);
}
/**
* @dev Remove DID. Only callable by DID controller.
* @param id — The identifier (DID) to be deleted
*/
function deleteDID(address id)
public
onlyController(id)
{
delete dids[id];
emit DeletedDID(id);
}
/**
* @dev Returns corresponding controller for given DID
* @param id — The identifier (DID) to be resolved to its controller address
*/
function getController(address id)
public
view
returns (address)
{
return dids[id].controller;
}
/**
* @dev Change controller address. Only callable by current DID controller.
* @param id — The identifier (DID) to be updated
* @param newController — New controller addresss
*/
function setController(address id, address newController)
public
onlyController(id)
{
dids[id].controller = newController;
dids[id].updated = block.timestamp;
emit SetController(id, newController);
}
function addKey(address id, byte[65] memory key, KeyPurpose _purpose)
public
onlyController(id)
{
require(dids[id].keys.length < MAX_KEYS, "DID key limit has been reached");
dids[id].keys.push(Secp256k1Key(key, _purpose));
}
function removeKey (address id, uint index)
public
onlyController(id)
{
if (dids[id].keys.length > 1) {
dids[id].keys[index] = dids[id].keys[dids[id].keys.length-1];
}
dids[id].keys.pop();
}
function getKeysLength(address id) public view returns(uint8) {
return uint8(dids[id].keys.length);
}
function getKey(address id, uint index) public view returns (byte[65] memory , uint) {
uint purpose = uint(dids[id].keys[index].purpose);
return (dids[id].keys[index].pubKey, purpose);
}
} | 28,437 |
26 | // checks airdrop state for an addressTESTING: Returns both instantiated and default (uninstantiated addresses) Uninstantiated addresses should return default (0 address) values/ | function checkWhitelist(address _addr)
external
virtual
view
returns (
uint256,
uint256,
uint256
)
| function checkWhitelist(address _addr)
external
virtual
view
returns (
uint256,
uint256,
uint256
)
| 73,433 |
43 | // Data relating to the re-collateralisation safety module | SafetyData public safetyData;
| SafetyData public safetyData;
| 63,070 |
2 | // SPDX-License-Identifier: UNLICENSED | abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
| abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
| 13,187 |
15 | // Function to change vote cost, by default vote cost equals 1 Human token_voteCost a new vote cost/ | function setVoteCost(uint _voteCost) external onlyEventManager {
voteCost = _voteCost;
}
| function setVoteCost(uint _voteCost) external onlyEventManager {
voteCost = _voteCost;
}
| 13,180 |
79 | // returns the last interest rate founnd during interest settlement/pool address/ return the last interset rate | function getPoolLastInterestRate(address pool)
external
view
returns (uint256);
| function getPoolLastInterestRate(address pool)
external
view
returns (uint256);
| 77,981 |
171 | // Returns current rescuerreturn Rescuer's address / | function rescuer() external view returns (address) {
return _rescuer;
}
| function rescuer() external view returns (address) {
return _rescuer;
}
| 10,981 |
39 | // Allows to mint one NFT if whitelisted_account The account of the user minting the NFT_proof The Merkle Proof/ | function presaleMint(address _account, bytes32[] calldata _proof) external payable nonReentrant {
//Are we in Presale ?
require(sellingStep == Steps.Presale, "Presale has not started yet.");
//Did this account already mint an NFT ?
require(nftsPerWallet[_account] < 1, "You can only get 1 NFT on the Presale");
//Is this user on the whitelist ?
require(isWhiteListed(_account, _proof), "Not on the whitelist");
//Get the price of one NFT during the Presale
uint price = pricePresale;
//Did the user send enought Ethers ?
require(msg.value >= price, "Not enought funds.");
//Increment the number of NFTs this user minted
nftsPerWallet[_account]++;
//Mint the user NFT
_safeMint(_account, _nftIdCounter.current());
//Increment the Id of the next NFT to mint
_nftIdCounter.increment();
}
| function presaleMint(address _account, bytes32[] calldata _proof) external payable nonReentrant {
//Are we in Presale ?
require(sellingStep == Steps.Presale, "Presale has not started yet.");
//Did this account already mint an NFT ?
require(nftsPerWallet[_account] < 1, "You can only get 1 NFT on the Presale");
//Is this user on the whitelist ?
require(isWhiteListed(_account, _proof), "Not on the whitelist");
//Get the price of one NFT during the Presale
uint price = pricePresale;
//Did the user send enought Ethers ?
require(msg.value >= price, "Not enought funds.");
//Increment the number of NFTs this user minted
nftsPerWallet[_account]++;
//Mint the user NFT
_safeMint(_account, _nftIdCounter.current());
//Increment the Id of the next NFT to mint
_nftIdCounter.increment();
}
| 35,179 |
31 | // get the remain unrleased tokens of the locked stages of an account_target the owner of some amount of tokens _num the stage number of the releasing period / | function getRemainOfStage(address _target, uint _num) public view returns (uint256) {
require(_target != address(0));
return lockedStorage.remainOfStage(_target, _num);
}
| function getRemainOfStage(address _target, uint _num) public view returns (uint256) {
require(_target != address(0));
return lockedStorage.remainOfStage(_target, _num);
}
| 28,296 |
45 | // Roles management - only for multi sig address / | function setupRole(bytes32 role, address account) external onlyManager {
_setupRole(role, account);
}
| function setupRole(bytes32 role, address account) external onlyManager {
_setupRole(role, account);
}
| 39,797 |
192 | // Throws if not allowed caller / | modifier onlyAllowedCaller(address _caller) {
require(isAllowedCaller(_caller), "Address not permitted to call");
_;
}
| modifier onlyAllowedCaller(address _caller) {
require(isAllowedCaller(_caller), "Address not permitted to call");
_;
}
| 10,805 |
36 | // Helper function to return a min between the two uints | function min(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
| function min(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
| 7,885 |
80 | // Destroy the contract | function kill() public onlyAdmin {
selfdestruct(payable(msg.sender));
}
| function kill() public onlyAdmin {
selfdestruct(payable(msg.sender));
}
| 3,243 |
5 | // Throws if contract is not in an emergency state. Emergency replacement and resolutioncan only happen in an emergency / | modifier onlyEmergency() {
require(emergencies > 0, "Not in emergency");
_;
}
| modifier onlyEmergency() {
require(emergencies > 0, "Not in emergency");
_;
}
| 28,922 |
122 | // Checks that a given kitten is able to breed. Requires that the/current cooldown is finished (for sires) and also checks that there is/no pending pregnancy. | function _isReadyToBreed(Kitty _kit) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the cat has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number));
}
| function _isReadyToBreed(Kitty _kit) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the cat has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number));
}
| 22,019 |
4 | // Parse resulting JSON string | uint returnVal;
JsmnSolLib.Token[] memory tokens;
uint numTokens;
(returnVal, tokens, numTokens) = JsmnSolLib.parse(result, 11);
assert(returnVal == 0);
JsmnSolLib.Token memory t = tokens[10];
departureTime = parseInt(JsmnSolLib.getBytes(result, t.start, t.end));
t = tokens[6];
status = parseInt(JsmnSolLib.getBytes(result, t.start, t.end));
| uint returnVal;
JsmnSolLib.Token[] memory tokens;
uint numTokens;
(returnVal, tokens, numTokens) = JsmnSolLib.parse(result, 11);
assert(returnVal == 0);
JsmnSolLib.Token memory t = tokens[10];
departureTime = parseInt(JsmnSolLib.getBytes(result, t.start, t.end));
t = tokens[6];
status = parseInt(JsmnSolLib.getBytes(result, t.start, t.end));
| 46,286 |
61 | // Adds an array of strings to the request with a given key name self The initialized request _key The name of the key _values The array of string values to add / | function addStringArray(Request memory self, string memory _key, string[] memory _values)
internal pure
| function addStringArray(Request memory self, string memory _key, string[] memory _values)
internal pure
| 13,925 |
3 | // Public function to create a new reserve that will be used to report a total collateralized amount in the/ denomination token/name Shortened string name identifying the reserve/chainId Id for the target chain used by this reserve/description Text providing basic information on the reserve | function createReserve(
string memory name,
string memory description,
uint256 chainId
| function createReserve(
string memory name,
string memory description,
uint256 chainId
| 9,907 |
37 | // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. | sum *= 100;
a *= 100;
| sum *= 100;
a *= 100;
| 4,258 |
14 | // no players this round, start the next one | if (participantSize == 0) {
resetGameAndStartNextRound();
return;
}
| if (participantSize == 0) {
resetGameAndStartNextRound();
return;
}
| 18,074 |
4 | // delete free | (,uint256 status,,,) = IPartner(_basePlatform).getPartner(target);
if ((status == 1) && _user[target].isVerified) {
_totalVerifiedFree = _totalVerifiedFree.sub(1);
}
| (,uint256 status,,,) = IPartner(_basePlatform).getPartner(target);
if ((status == 1) && _user[target].isVerified) {
_totalVerifiedFree = _totalVerifiedFree.sub(1);
}
| 47,921 |
38 | // STORAGE //The main Offer struct for auctioning | struct Offer {
bool isForSale;
uint tokenId;
address seller;
uint minValue;
}
| struct Offer {
bool isForSale;
uint tokenId;
address seller;
uint minValue;
}
| 44,632 |
26 | // See {IERC4626-previewWithdraw}. / | function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {
return _convertToShares(assets, MathUpgradeable.Rounding.Up);
}
| function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {
return _convertToShares(assets, MathUpgradeable.Rounding.Up);
}
| 7,401 |
147 | // Update number of events pushed to buffer - | mstore(0x140, add(1, mload(0x140)))
| mstore(0x140, add(1, mload(0x140)))
| 60,735 |
10 | // Constrctor function Initializes contract with initial supply tokens to the creator of the contract / | function SDR22 (
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
initialSupply = 9000000000;
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
| function SDR22 (
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
initialSupply = 9000000000;
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
| 7,296 |
148 | // Trim the { and } from the parameters | uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]);
uint256 blueprintLength = blob.length - uint256(index) - 3;
if (blueprintLength == 0) {
return (tokenID, bytes(""));
}
| uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]);
uint256 blueprintLength = blob.length - uint256(index) - 3;
if (blueprintLength == 0) {
return (tokenID, bytes(""));
}
| 44,285 |
5 | // These functions deal with verification of Merkle Trees proofs. The proofs can be generated using the JavaScript libraryNote: the hashing algorithm should be keccak256 and pair sorting should be enabled. See `test/utils/cryptography/MerkleProof.test.js` for some examples. / | library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
| library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
| 19,839 |
12 | // for every 1.00 ghostdai we get 0.98 dai 1000000000000000000 we get 980000 (bc decimals) | uint256 amountToSend = amount.mul(ghostdaiRate).div(100);
require(dai.balanceOf(address(this)) >= amountToSend, "swapTo: Not enough ghostDai in reserves");
| uint256 amountToSend = amount.mul(ghostdaiRate).div(100);
require(dai.balanceOf(address(this)) >= amountToSend, "swapTo: Not enough ghostDai in reserves");
| 10,649 |
12 | // malicious functions that can throw off our example swap platform later | function setMarketplace(address marketplace) onlyOwner public{
marketplaceAddress = marketplace;
}
| function setMarketplace(address marketplace) onlyOwner public{
marketplaceAddress = marketplace;
}
| 52,875 |
1 | // Withdraw ether from smart contract, only owner can do thisaccount - Destination of ether funds amount - Amount that will be withdrawn / | function withdrawEther(address account, uint256 amount) external onlyOwner {
_withdrawEther(account, amount);
}
| function withdrawEther(address account, uint256 amount) external onlyOwner {
_withdrawEther(account, amount);
}
| 21,387 |
9 | // ensure msg.sender is an authorized ballot creator | require(creators[msg.sender]);
| require(creators[msg.sender]);
| 10,891 |
4 | // return r the sum of two points of G1 / | function plus(
G1Point memory p1,
G1Point memory p2
| function plus(
G1Point memory p1,
G1Point memory p2
| 35,017 |
22 | // take from both balances | editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId] = spentTokens + editionTokenBalance;
uint256 amountOfTokensToSpendFromTokenBalance = _value - editionTokenBalance;
ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] - amountOfTokensToSpendFromTokenBalance;
| editionTokenERC20TransferAmounts[editionId][_erc20Contract][_tokenId] = spentTokens + editionTokenBalance;
uint256 amountOfTokensToSpendFromTokenBalance = _value - editionTokenBalance;
ERC20Balances[_tokenId][_erc20Contract] = ERC20Balances[_tokenId][_erc20Contract] - amountOfTokensToSpendFromTokenBalance;
| 6,465 |
223 | // Get the current balance on the smart wallet for the supplied ERC20 token. | uint256 balance = 0;
bool balanceCheckWorked = true;
if (!suppressRevert) {
balance = token.balanceOf(address(this));
} else {
| uint256 balance = 0;
bool balanceCheckWorked = true;
if (!suppressRevert) {
balance = token.balanceOf(address(this));
} else {
| 32,086 |
1,305 | // Sets the values for {name} and {symbol}, initializes {decimals} witha default value of 18 and a {totalSupply} of the token. All four of these values are immutable: they can only be set once duringconstruction. / |
constructor () public {
|
constructor () public {
| 4,318 |
42 | // Prevent overflow when dividing MIN_INT256 by -1 | require(b != -1 || a != MIN_INT256);
| require(b != -1 || a != MIN_INT256);
| 27,154 |
13 | // collateralUsageLimit:when the position collateral usage surpasses this threshold, anyone will be able to trigger the stop loss slippageIncentive: when the bot repays the debt, it will be able to take an amount of supply token equivalent to the repaid debt plus this incentive specified in percentage. It has to be carefully configured with unwind factor unwindFactor:percentage of debt that can be repaid when the position is eligible for stop loss / | struct StopLossStore {
uint256 collateralUsageLimit; // ranges from 0 to 1e18
uint256 slippageIncentive; // ranges from 0 to 1e18
uint256 unwindFactor; // ranges from 0 to 1e18
}
| struct StopLossStore {
uint256 collateralUsageLimit; // ranges from 0 to 1e18
uint256 slippageIncentive; // ranges from 0 to 1e18
uint256 unwindFactor; // ranges from 0 to 1e18
}
| 63,277 |
12 | // The tokens can never be stolen. / | modifier notPowh(address aContract){
require(aContract != address(weak_hands));
_;
}
| modifier notPowh(address aContract){
require(aContract != address(weak_hands));
_;
}
| 47,122 |
399 | // Arithmetic library with operations for fixed-point numbers./Solmate (https:github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol) | library FixedPointMathLib {
/*///////////////////////////////////////////////////////////////
COMMON BASE UNITS
//////////////////////////////////////////////////////////////*/
uint256 internal constant YAD = 1e8;
uint256 internal constant WAD = 1e18;
uint256 internal constant RAY = 1e27;
uint256 internal constant RAD = 1e45;
/*///////////////////////////////////////////////////////////////
FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function fmul(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(x == 0 || (x * y) / x == y)
if iszero(or(iszero(x), eq(div(z, x), y))) {
revert(0, 0)
}
// If baseUnit is zero this will return zero instead of reverting.
z := div(z, baseUnit)
}
}
function fdiv(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * baseUnit in z for now.
z := mul(x, baseUnit)
// Equivalent to require(y != 0 && (x == 0 || (x * baseUnit) / x == baseUnit))
if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) {
revert(0, 0)
}
// We ensure y is not zero above, so there is never division by zero here.
z := div(z, y)
}
}
function fpow(
uint256 x,
uint256 n,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := baseUnit
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store baseUnit in z for now.
z := baseUnit
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, baseUnit)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, baseUnit)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, baseUnit)
}
}
}
}
}
/*///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
// Start off with z at 1.
z := 1
// Used below to help find a nearby power of 2.
let y := x
// Find the lowest power of 2 that is at least sqrt(x).
if iszero(lt(y, 0x100000000000000000000000000000000)) {
y := shr(128, y) // Like dividing by 2 ** 128.
z := shl(64, z)
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z)
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z)
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z)
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z)
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z)
}
if iszero(lt(y, 0x8)) {
// Equivalent to 2 ** z.
z := shl(1, z)
}
// Shifting right by 1 is like dividing by 2.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
// If zRoundDown is smaller, use it.
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
} | library FixedPointMathLib {
/*///////////////////////////////////////////////////////////////
COMMON BASE UNITS
//////////////////////////////////////////////////////////////*/
uint256 internal constant YAD = 1e8;
uint256 internal constant WAD = 1e18;
uint256 internal constant RAY = 1e27;
uint256 internal constant RAD = 1e45;
/*///////////////////////////////////////////////////////////////
FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function fmul(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(x == 0 || (x * y) / x == y)
if iszero(or(iszero(x), eq(div(z, x), y))) {
revert(0, 0)
}
// If baseUnit is zero this will return zero instead of reverting.
z := div(z, baseUnit)
}
}
function fdiv(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * baseUnit in z for now.
z := mul(x, baseUnit)
// Equivalent to require(y != 0 && (x == 0 || (x * baseUnit) / x == baseUnit))
if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) {
revert(0, 0)
}
// We ensure y is not zero above, so there is never division by zero here.
z := div(z, y)
}
}
function fpow(
uint256 x,
uint256 n,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := baseUnit
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store baseUnit in z for now.
z := baseUnit
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, baseUnit)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, baseUnit)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, baseUnit)
}
}
}
}
}
/*///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
// Start off with z at 1.
z := 1
// Used below to help find a nearby power of 2.
let y := x
// Find the lowest power of 2 that is at least sqrt(x).
if iszero(lt(y, 0x100000000000000000000000000000000)) {
y := shr(128, y) // Like dividing by 2 ** 128.
z := shl(64, z)
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z)
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z)
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z)
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z)
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z)
}
if iszero(lt(y, 0x8)) {
// Equivalent to 2 ** z.
z := shl(1, z)
}
// Shifting right by 1 is like dividing by 2.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
// If zRoundDown is smaller, use it.
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
} | 41,852 |
60 | // Modifiers and Structs ======================================================== only run certain methods when contract is open | modifier isOpenContract() {
require (contractStage == CONTRACT_OPEN);
_;
}
| modifier isOpenContract() {
require (contractStage == CONTRACT_OPEN);
_;
}
| 2,986 |
43 | // Author: Shravan SunderDate: 2022-02Description: This contract uses chainlink to get the floor price of a NFT from opensea api using ChainlinkNotes:/ | contract PriceOracleNFT is ChainlinkClient {
using Chainlink for Chainlink.Request;
string public testStatus = "init";
// 1 day
uint256 updateFrequency = 60 * 60 * 24;
struct Callback {
address callbackAddress;
bytes4 callbackFunctionSignature;
}
// the collection data used by state
struct CollectionPrice {
uint256 floorPrice;
uint256 timestamp;
bytes32 requestId;
}
// structure to keep track of floor price chainlink requests
struct FloorPriceRequests {
uint256 timestamp;
address collectionAddress;
}
// structure to keep track of current calls
struct CallInfo {
bytes32 slugRequestId;
bytes32 floorPriceRequestId;
Callback callback;
}
// state variables
/* map of floor price by collection name */
mapping(address => CollectionPrice) public floorPriceMap;
/* map of address to collection name */
mapping(address => string) public addressToCollectionSlugMap;
mapping(address => CallInfo) public addressToCallInfoMap;
mapping(bytes32 => address) public requestToAddressMap;
/* map of requests by collection name */
//mapping(string => bytes32) public floorPriceRequestsByName;
/* map of requests by requestId */
mapping(bytes32 => FloorPriceRequests) public floorPriceRequestsById;
uint256 private callId = 0;
// oracle data
address private oracle;
bytes32 private u256JobId;
bytes32 private bytes32JobId;
uint256 private fee;
// events
event OpenSeaFloorPriceRequested(address collectionAddress, string collectionSlug, bytes32 requestId, string url, uint256 timestamp);
event OpenSeaFloorPriceUpdated(address collectionAddress, bytes32 requestId, uint256 floorPrice, uint256 timestamp);
event OpeaFloorSlugRequested(address collectionAddress, bytes32 requestId);
event OpeaFloorSlugUpdated(address collectionAddress, string collectionSlug, bytes32 requestId);
constructor() {
setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB);
oracle = 0x58BBDbfb6fca3129b91f0DBE372098123B38B5e9;
u256JobId = "da20aae0e4c843f6949e5cb3f7cfe8c4";
bytes32JobId = "a7330d0b4b964c05abc66a26307047c0";
fee = 0.01 * 10**18;
}
function testCallback(uint256 _price) public {}
function test(address _collectionAddress) public {
testStatus = "test";
Callback memory c = Callback(address(this), this.testCallback.selector);
getFloorPrice(_collectionAddress, c);
}
/**
* This is the function to call to get the floor price of a NFT from opensea api using Chainlink
* @param _collectionAddress address of the collection
* @param _callback callback for the function, it should be of the form: function(uint256 floorPrice)
*/
function getFloorPrice(address _collectionAddress, Callback memory _callback) public returns (bytes20) {
callId++;
bytes16 guid = bytes16(keccak256(abi.encodePacked(callId)));
testStatus = "getFloorPrice";
// if (ERC20Interface(oracle).balanceOf(address(this)) == 0) {
// revert NoLinkTokenInContract();
// }
if (bytes(addressToCollectionSlugMap[_collectionAddress]).length == 0) {
testStatus = "getFloorPrice: no slug";
// we don't have slug for this collection contract
addressToCallInfoMap[_collectionAddress] = CallInfo(0, 0, _callback);
bytes32 result = requestOpenSeaCollectionSlug(_collectionAddress);
addressToCallInfoMap[_collectionAddress].slugRequestId = result;
} else {
testStatus = "getFloorPrice: floor price";
// we have slug for this collection contract
addressToCallInfoMap[_collectionAddress] = CallInfo(0, 0, _callback);
bytes32 result = requestOpenSeaFloorPrice(_collectionAddress, addressToCollectionSlugMap[_collectionAddress]);
addressToCallInfoMap[_collectionAddress].floorPriceRequestId = result;
}
return guid;
}
/**
* This will call an api via chainlink to get the floor price of a collection
* @param _collectionAddress address of contract
*/
function requestOpenSeaCollectionSlug(address _collectionAddress) internal returns (bytes32 requestId) {
testStatus = "requestOpenSeaCollectionSlug";
// create a new request
Chainlink.Request memory request = buildChainlinkRequest(bytes32JobId, address(this), this.fulfillCollectionSlug.selector);
// Set the URL to perform the GET request on
string memory url = getContractUrl(toString(_collectionAddress));
request.add("get", url);
request.add("path", "collection.slug");
// send the request
bytes32 result = sendChainlinkRequestTo(oracle, request, fee);
// emit event and save id
emit OpeaFloorSlugRequested(_collectionAddress, result);
return result;
}
/**
* Callback function to retrieve the response from the Chainlink request.
*/
function fulfillCollectionSlug(bytes32 _requestId, string memory _slug) public recordChainlinkFulfillment(_requestId) {
string memory collectionSlug = _slug;
emit OpeaFloorSlugUpdated(requestToAddressMap[_requestId], collectionSlug, _requestId);
addressToCollectionSlugMap[requestToAddressMap[_requestId]] = _slug;
// call the next step
address collectionAddress = requestToAddressMap[_requestId];
bytes32 result = requestOpenSeaFloorPrice(collectionAddress, _slug);
addressToCallInfoMap[collectionAddress].floorPriceRequestId = result;
}
/**
* This will call an api via chainlink to get the floor price of a collection
* @param _collectionSlug the slug for the collection in openSea
*/
function requestOpenSeaFloorPrice(address _collectionAddress, string memory _collectionSlug) internal returns (bytes32 requestId) {
testStatus = "requestOpenSeaFloorPrice";
// check if there is already a result that's recent
if (floorPriceMap[_collectionAddress].timestamp != 0) {
if (block.timestamp - floorPriceMap[_collectionAddress].timestamp < updateFrequency) {
return floorPriceMap[_collectionAddress].requestId;
}
}
bytes32 floorPriceRequestId = addressToCallInfoMap[_collectionAddress].floorPriceRequestId;
testStatus = "requestOpenSeaFloorPrice: check existing";
// check if a request is in progress that's valid
if (floorPriceRequestId != 0 && floorPriceRequestsById[floorPriceRequestId].timestamp != 0) {
if (block.timestamp - floorPriceRequestsById[floorPriceRequestId].timestamp < updateFrequency) {
return floorPriceRequestId;
}
// if there any current request and its too old, delete it and refetch
delete floorPriceRequestsById[floorPriceRequestId];
}
testStatus = "requestOpenSeaFloorPrice: create request";
// create a new request
Chainlink.Request memory request = buildChainlinkRequest(u256JobId, address(this), this.fulfillFloorPrice.selector);
// Set the URL to perform the GET request on
string memory url = getStatsUrl(_collectionSlug);
request.add("get", url);
request.add("path", "stats.floor_price");
// multiple by 10^18 to remove decimal places
int256 timesAmount = 10**18;
request.addInt("times", timesAmount);
testStatus = "requesting";
// send the request
bytes32 result = sendChainlinkRequestTo(oracle, request, fee);
// save the request data
floorPriceRequestsById[result] = FloorPriceRequests(block.timestamp, _collectionAddress);
// emit event and save id
emit OpenSeaFloorPriceRequested(_collectionAddress, _collectionSlug, result, url, block.timestamp);
return result;
}
/**
* Callback function to retrieve the response from the Chainlink request.
*/
function fulfillFloorPrice(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) {
testStatus = "fulfillFloorPrice";
address collectionAddress = floorPriceRequestsById[_requestId].collectionAddress;
floorPriceMap[collectionAddress] = CollectionPrice(_price, block.timestamp, _requestId);
emit OpenSeaFloorPriceUpdated(collectionAddress, _requestId, _price, block.timestamp);
// delete floor price request that is completed
delete floorPriceRequestsById[_requestId];
// invoke callback
Callback memory callback = addressToCallInfoMap[collectionAddress].callback;
(bool success, ) = callback.callbackAddress.call(abi.encodeWithSelector(callback.callbackFunctionSignature, _price));
delete addressToCallInfoMap[collectionAddress];
}
/**
* Concatenate the URL for getting status such as floor price
*/
function getStatsUrl(string memory slug) public pure returns (string memory) {
return string(abi.encodePacked("https://api.opensea.io/api/v1/collection/", slug, "/stats"));
}
/**
* Concatenate the URL for getting slug
*/
function getContractUrl(string memory contractAddress) public pure returns (string memory) {
return string(abi.encodePacked("https://api.opensea.io/api/v1/asset_contract/", contractAddress));
}
// /////////
// HELPERS
// /////////
function toString(address account) public pure returns (string memory) {
return toString(abi.encodePacked(account));
}
function toString(uint256 value) internal pure returns (string memory) {
return toString(abi.encodePacked(value));
}
function toString(bytes32 value) internal pure returns (string memory) {
return toString(abi.encodePacked(value));
}
function toString(bytes memory data) internal pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(data[i] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(data[i] & 0x0f))];
}
return string(str);
}
function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
uint8 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
// solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
}
| contract PriceOracleNFT is ChainlinkClient {
using Chainlink for Chainlink.Request;
string public testStatus = "init";
// 1 day
uint256 updateFrequency = 60 * 60 * 24;
struct Callback {
address callbackAddress;
bytes4 callbackFunctionSignature;
}
// the collection data used by state
struct CollectionPrice {
uint256 floorPrice;
uint256 timestamp;
bytes32 requestId;
}
// structure to keep track of floor price chainlink requests
struct FloorPriceRequests {
uint256 timestamp;
address collectionAddress;
}
// structure to keep track of current calls
struct CallInfo {
bytes32 slugRequestId;
bytes32 floorPriceRequestId;
Callback callback;
}
// state variables
/* map of floor price by collection name */
mapping(address => CollectionPrice) public floorPriceMap;
/* map of address to collection name */
mapping(address => string) public addressToCollectionSlugMap;
mapping(address => CallInfo) public addressToCallInfoMap;
mapping(bytes32 => address) public requestToAddressMap;
/* map of requests by collection name */
//mapping(string => bytes32) public floorPriceRequestsByName;
/* map of requests by requestId */
mapping(bytes32 => FloorPriceRequests) public floorPriceRequestsById;
uint256 private callId = 0;
// oracle data
address private oracle;
bytes32 private u256JobId;
bytes32 private bytes32JobId;
uint256 private fee;
// events
event OpenSeaFloorPriceRequested(address collectionAddress, string collectionSlug, bytes32 requestId, string url, uint256 timestamp);
event OpenSeaFloorPriceUpdated(address collectionAddress, bytes32 requestId, uint256 floorPrice, uint256 timestamp);
event OpeaFloorSlugRequested(address collectionAddress, bytes32 requestId);
event OpeaFloorSlugUpdated(address collectionAddress, string collectionSlug, bytes32 requestId);
constructor() {
setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB);
oracle = 0x58BBDbfb6fca3129b91f0DBE372098123B38B5e9;
u256JobId = "da20aae0e4c843f6949e5cb3f7cfe8c4";
bytes32JobId = "a7330d0b4b964c05abc66a26307047c0";
fee = 0.01 * 10**18;
}
function testCallback(uint256 _price) public {}
function test(address _collectionAddress) public {
testStatus = "test";
Callback memory c = Callback(address(this), this.testCallback.selector);
getFloorPrice(_collectionAddress, c);
}
/**
* This is the function to call to get the floor price of a NFT from opensea api using Chainlink
* @param _collectionAddress address of the collection
* @param _callback callback for the function, it should be of the form: function(uint256 floorPrice)
*/
function getFloorPrice(address _collectionAddress, Callback memory _callback) public returns (bytes20) {
callId++;
bytes16 guid = bytes16(keccak256(abi.encodePacked(callId)));
testStatus = "getFloorPrice";
// if (ERC20Interface(oracle).balanceOf(address(this)) == 0) {
// revert NoLinkTokenInContract();
// }
if (bytes(addressToCollectionSlugMap[_collectionAddress]).length == 0) {
testStatus = "getFloorPrice: no slug";
// we don't have slug for this collection contract
addressToCallInfoMap[_collectionAddress] = CallInfo(0, 0, _callback);
bytes32 result = requestOpenSeaCollectionSlug(_collectionAddress);
addressToCallInfoMap[_collectionAddress].slugRequestId = result;
} else {
testStatus = "getFloorPrice: floor price";
// we have slug for this collection contract
addressToCallInfoMap[_collectionAddress] = CallInfo(0, 0, _callback);
bytes32 result = requestOpenSeaFloorPrice(_collectionAddress, addressToCollectionSlugMap[_collectionAddress]);
addressToCallInfoMap[_collectionAddress].floorPriceRequestId = result;
}
return guid;
}
/**
* This will call an api via chainlink to get the floor price of a collection
* @param _collectionAddress address of contract
*/
function requestOpenSeaCollectionSlug(address _collectionAddress) internal returns (bytes32 requestId) {
testStatus = "requestOpenSeaCollectionSlug";
// create a new request
Chainlink.Request memory request = buildChainlinkRequest(bytes32JobId, address(this), this.fulfillCollectionSlug.selector);
// Set the URL to perform the GET request on
string memory url = getContractUrl(toString(_collectionAddress));
request.add("get", url);
request.add("path", "collection.slug");
// send the request
bytes32 result = sendChainlinkRequestTo(oracle, request, fee);
// emit event and save id
emit OpeaFloorSlugRequested(_collectionAddress, result);
return result;
}
/**
* Callback function to retrieve the response from the Chainlink request.
*/
function fulfillCollectionSlug(bytes32 _requestId, string memory _slug) public recordChainlinkFulfillment(_requestId) {
string memory collectionSlug = _slug;
emit OpeaFloorSlugUpdated(requestToAddressMap[_requestId], collectionSlug, _requestId);
addressToCollectionSlugMap[requestToAddressMap[_requestId]] = _slug;
// call the next step
address collectionAddress = requestToAddressMap[_requestId];
bytes32 result = requestOpenSeaFloorPrice(collectionAddress, _slug);
addressToCallInfoMap[collectionAddress].floorPriceRequestId = result;
}
/**
* This will call an api via chainlink to get the floor price of a collection
* @param _collectionSlug the slug for the collection in openSea
*/
function requestOpenSeaFloorPrice(address _collectionAddress, string memory _collectionSlug) internal returns (bytes32 requestId) {
testStatus = "requestOpenSeaFloorPrice";
// check if there is already a result that's recent
if (floorPriceMap[_collectionAddress].timestamp != 0) {
if (block.timestamp - floorPriceMap[_collectionAddress].timestamp < updateFrequency) {
return floorPriceMap[_collectionAddress].requestId;
}
}
bytes32 floorPriceRequestId = addressToCallInfoMap[_collectionAddress].floorPriceRequestId;
testStatus = "requestOpenSeaFloorPrice: check existing";
// check if a request is in progress that's valid
if (floorPriceRequestId != 0 && floorPriceRequestsById[floorPriceRequestId].timestamp != 0) {
if (block.timestamp - floorPriceRequestsById[floorPriceRequestId].timestamp < updateFrequency) {
return floorPriceRequestId;
}
// if there any current request and its too old, delete it and refetch
delete floorPriceRequestsById[floorPriceRequestId];
}
testStatus = "requestOpenSeaFloorPrice: create request";
// create a new request
Chainlink.Request memory request = buildChainlinkRequest(u256JobId, address(this), this.fulfillFloorPrice.selector);
// Set the URL to perform the GET request on
string memory url = getStatsUrl(_collectionSlug);
request.add("get", url);
request.add("path", "stats.floor_price");
// multiple by 10^18 to remove decimal places
int256 timesAmount = 10**18;
request.addInt("times", timesAmount);
testStatus = "requesting";
// send the request
bytes32 result = sendChainlinkRequestTo(oracle, request, fee);
// save the request data
floorPriceRequestsById[result] = FloorPriceRequests(block.timestamp, _collectionAddress);
// emit event and save id
emit OpenSeaFloorPriceRequested(_collectionAddress, _collectionSlug, result, url, block.timestamp);
return result;
}
/**
* Callback function to retrieve the response from the Chainlink request.
*/
function fulfillFloorPrice(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) {
testStatus = "fulfillFloorPrice";
address collectionAddress = floorPriceRequestsById[_requestId].collectionAddress;
floorPriceMap[collectionAddress] = CollectionPrice(_price, block.timestamp, _requestId);
emit OpenSeaFloorPriceUpdated(collectionAddress, _requestId, _price, block.timestamp);
// delete floor price request that is completed
delete floorPriceRequestsById[_requestId];
// invoke callback
Callback memory callback = addressToCallInfoMap[collectionAddress].callback;
(bool success, ) = callback.callbackAddress.call(abi.encodeWithSelector(callback.callbackFunctionSignature, _price));
delete addressToCallInfoMap[collectionAddress];
}
/**
* Concatenate the URL for getting status such as floor price
*/
function getStatsUrl(string memory slug) public pure returns (string memory) {
return string(abi.encodePacked("https://api.opensea.io/api/v1/collection/", slug, "/stats"));
}
/**
* Concatenate the URL for getting slug
*/
function getContractUrl(string memory contractAddress) public pure returns (string memory) {
return string(abi.encodePacked("https://api.opensea.io/api/v1/asset_contract/", contractAddress));
}
// /////////
// HELPERS
// /////////
function toString(address account) public pure returns (string memory) {
return toString(abi.encodePacked(account));
}
function toString(uint256 value) internal pure returns (string memory) {
return toString(abi.encodePacked(value));
}
function toString(bytes32 value) internal pure returns (string memory) {
return toString(abi.encodePacked(value));
}
function toString(bytes memory data) internal pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 + i * 2] = alphabet[uint256(uint8(data[i] >> 4))];
str[3 + i * 2] = alphabet[uint256(uint8(data[i] & 0x0f))];
}
return string(str);
}
function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
uint8 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
// solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
}
| 7,423 |
12 | // UTILITY FUNCTIONS/ Genranal | function getContractOwner()
public
returns(address)
| function getContractOwner()
public
returns(address)
| 12,125 |
5 | // get all pools addresses added in contract.return array of addresses / | function getPools() external view returns (address[] memory) {
return registeredPools;
}
| function getPools() external view returns (address[] memory) {
return registeredPools;
}
| 32,181 |
62 | // check is there any cover that still depend on this one | require(
!coverGateway.isCoverActiveExists(_offerId),
"Claim Gateway : There is any active cover"
);
| require(
!coverGateway.isCoverActiveExists(_offerId),
"Claim Gateway : There is any active cover"
);
| 10,567 |
300 | // transfer the rest including platformFeeInShares and any dust remaining (since this contract will never have shares of itself apart from fees.) | uint256 selfBalance = IERC20(address(this)).balanceOf(address(this));
if (selfBalance > 0) {
IERC20(address(this)).safeTransfer(_platformRewards(), selfBalance);
}
| uint256 selfBalance = IERC20(address(this)).balanceOf(address(this));
if (selfBalance > 0) {
IERC20(address(this)).safeTransfer(_platformRewards(), selfBalance);
}
| 47,813 |
5 | // MPHelper contract @FrankPoncelet / | contract MPHelper{
PunksMarket public mPContract;
constructor() {
mPContract = PunksMarket(payable(0x759c6C1923910930C18ef490B3c3DbeFf24003cE));
}
function getAllBids(uint256[] memory ids) external view returns (PunksMarket.Punk[] memory){
uint tokens = 0;
for (uint i=0; i<ids.length; i++) {
PunksMarket.Punk memory punk = mPContract.getPunksDetails(ids[i]);
if (punk.bid.hasBid && !isForSale(punk)){
tokens+=1;
}
}
PunksMarket.Punk[] memory punks = new PunksMarket.Punk[](tokens);
uint index = 0;
for (uint i=0; i<ids.length; i++) {
PunksMarket.Punk memory punk = mPContract.getPunksDetails(ids[i]);
if (punk.bid.hasBid && !isForSale(punk)){
punks[index]=mPContract.getPunksDetails(ids[i]);
index +=1;
}
}
return punks;
}
function getAllForSale(uint256[] memory ids) external view returns (PunksMarket.Punk[] memory){
uint tokens = 0;
for (uint i=0; i<ids.length; i++) {
PunksMarket.Punk memory punk = mPContract.getPunksDetails(ids[i]);
if (isForSale(punk)){
tokens+=1;
}
}
PunksMarket.Punk[] memory punks = new PunksMarket.Punk[](tokens);
uint index = 0;
for (uint i=0; i<ids.length; i++) {
PunksMarket.Punk memory punk = mPContract.getPunksDetails(ids[i]);
if (isForSale(punk)){
punks[index]=mPContract.getPunksDetails(ids[i]);
index +=1;
}
}
return punks;
}
function getDetailsForIds(uint256[] memory ids) external view returns (PunksMarket.Punk[] memory){
PunksMarket.Punk[] memory punks = new PunksMarket.Punk[](ids.length);
for (uint i=0; i<ids.length; i++) {
punks[i]=mPContract.getPunksDetails(ids[i]);
}
return punks;
}
function isForSale(PunksMarket.Punk memory punk) public pure returns (bool){
return punk.offer.isForSale && punk.owner==punk.offer.seller;
}
} | contract MPHelper{
PunksMarket public mPContract;
constructor() {
mPContract = PunksMarket(payable(0x759c6C1923910930C18ef490B3c3DbeFf24003cE));
}
function getAllBids(uint256[] memory ids) external view returns (PunksMarket.Punk[] memory){
uint tokens = 0;
for (uint i=0; i<ids.length; i++) {
PunksMarket.Punk memory punk = mPContract.getPunksDetails(ids[i]);
if (punk.bid.hasBid && !isForSale(punk)){
tokens+=1;
}
}
PunksMarket.Punk[] memory punks = new PunksMarket.Punk[](tokens);
uint index = 0;
for (uint i=0; i<ids.length; i++) {
PunksMarket.Punk memory punk = mPContract.getPunksDetails(ids[i]);
if (punk.bid.hasBid && !isForSale(punk)){
punks[index]=mPContract.getPunksDetails(ids[i]);
index +=1;
}
}
return punks;
}
function getAllForSale(uint256[] memory ids) external view returns (PunksMarket.Punk[] memory){
uint tokens = 0;
for (uint i=0; i<ids.length; i++) {
PunksMarket.Punk memory punk = mPContract.getPunksDetails(ids[i]);
if (isForSale(punk)){
tokens+=1;
}
}
PunksMarket.Punk[] memory punks = new PunksMarket.Punk[](tokens);
uint index = 0;
for (uint i=0; i<ids.length; i++) {
PunksMarket.Punk memory punk = mPContract.getPunksDetails(ids[i]);
if (isForSale(punk)){
punks[index]=mPContract.getPunksDetails(ids[i]);
index +=1;
}
}
return punks;
}
function getDetailsForIds(uint256[] memory ids) external view returns (PunksMarket.Punk[] memory){
PunksMarket.Punk[] memory punks = new PunksMarket.Punk[](ids.length);
for (uint i=0; i<ids.length; i++) {
punks[i]=mPContract.getPunksDetails(ids[i]);
}
return punks;
}
function isForSale(PunksMarket.Punk memory punk) public pure returns (bool){
return punk.offer.isForSale && punk.owner==punk.offer.seller;
}
} | 3,778 |
145 | // how much ETH did we just swap into? | uint256 newBalance = address(this).balance.sub(initialBalance);
| uint256 newBalance = address(this).balance.sub(initialBalance);
| 27,998 |
34 | // Withdraw Staking tokens from FairLaunchToken. | function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount);
}
| function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount);
}
| 11,269 |
5 | // Here we take advantage of the fact that we know RToken has 18 decimals to convert between uint256 an uint192. Fits due to assumed max totalSupply. | uint192 supply = _safeWrap(IRToken(address(erc20)).totalSupply());
if (supply == 0) return (lowBUPrice, highBUPrice);
| uint192 supply = _safeWrap(IRToken(address(erc20)).totalSupply());
if (supply == 0) return (lowBUPrice, highBUPrice);
| 40,306 |
71 | // Index of known members for each contract. These are EOAs that were added once, even if removed now. | mapping(address => address[]) public contractsToKnownMembersIndexes;
| mapping(address => address[]) public contractsToKnownMembersIndexes;
| 14,851 |
83 | // Validates that `_tokenOwner` owns and has approved Market to transfer NFTs. | function validateOwnershipAndApproval(
address _tokenOwner,
address _assetContract,
uint256 _tokenId,
uint256 _quantity,
TokenType _tokenType
) internal view {
bool isValid;
if (_tokenType == TokenType.ERC1155) {
| function validateOwnershipAndApproval(
address _tokenOwner,
address _assetContract,
uint256 _tokenId,
uint256 _quantity,
TokenType _tokenType
) internal view {
bool isValid;
if (_tokenType == TokenType.ERC1155) {
| 23,946 |
141 | // the Metadata extension, but not including the Enumerable extension, which is available separately as | * {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
| * {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
| 76,342 |
141 | // Mint a given discreet NFT if it is currently available. / | function mint(uint256 tokenId) external override {
require(
tokenId < 0x510,
"discreet: cannot mint out-of-range token"
);
if (tokenId < 0x360) {
require(
block.number >= migrationEnds,
"discreet: cannot mint tokens from original or extra set until migration is complete."
);
}
_safeMint(msg.sender, tokenId);
}
| function mint(uint256 tokenId) external override {
require(
tokenId < 0x510,
"discreet: cannot mint out-of-range token"
);
if (tokenId < 0x360) {
require(
block.number >= migrationEnds,
"discreet: cannot mint tokens from original or extra set until migration is complete."
);
}
_safeMint(msg.sender, tokenId);
}
| 28,163 |
3 | // Get price feed from BAND Protocol | IStdReference.ReferenceData memory data = bandRef.getReferenceData(
"ETH",
"USD"
);
| IStdReference.ReferenceData memory data = bandRef.getReferenceData(
"ETH",
"USD"
);
| 31,370 |
127 | // indexed events are emitted | emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
| emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ), priceInUSD );
emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() );
adjust(); // control variable is adjusted
return payout;
| 24,394 |
27 | // Вызываем событие | emit Restart(now);
| emit Restart(now);
| 12,612 |
1 | // Throws if the sender is not the owner. / | modifier onlyOwner {
require(msg.sender == owner, "Must be owner");
_;
}
| modifier onlyOwner {
require(msg.sender == owner, "Must be owner");
_;
}
| 4,121 |
24 | // 获取募资的代币价格 | function crowdPrice(uint256 id) public view returns (uint256) {
IBondData b = bondData(id);
(uint256 price, bool crowdPriceOk) = IOracle(oracle).get(b.crowdToken());
require(crowdPriceOk, "invalid crowd price");
return price;
}
| function crowdPrice(uint256 id) public view returns (uint256) {
IBondData b = bondData(id);
(uint256 price, bool crowdPriceOk) = IOracle(oracle).get(b.crowdToken());
require(crowdPriceOk, "invalid crowd price");
return price;
}
| 42,048 |
11 | // ERROR |
error InvalidOwner(address account);
error UnauthorizedAccount(address account);
error InvalidAuthorizedAccount(address account);
error CurrentAuthorizedState(address account, bool state);
|
error InvalidOwner(address account);
error UnauthorizedAccount(address account);
error InvalidAuthorizedAccount(address account);
error CurrentAuthorizedState(address account, bool state);
| 37,793 |
53 | // Prevent overflow when dividing INT256_MIN by -1 https:github.com/RequestNetwork/requestNetwork/issues/43 | require(!(a == - 2**255 && b == -1) && (b > 0));
return a / b;
| require(!(a == - 2**255 && b == -1) && (b > 0));
return a / b;
| 9,432 |
608 | // bnb or eth will be transferred to this account | address public fundsReceiver;
| address public fundsReceiver;
| 31,550 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.