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 |
|---|---|---|---|---|
13 | // _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); |
_forwardFunds();
|
_forwardFunds();
| 3,788 |
40 | // Liquidates position and sends a liquidation bonus from user's commitment to a caller. can only be called from account that has the LIQUIDATOR role/ | function liquidatePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman nonReentrant {
Position storage position = positionInfo[positionId];
_checkPositionIsOpen(position);
uint256 canReturn;
uint256 poolInterest = calculateBorrowInterest(positionId);
uint256 liquidationBonus = calculateAutoCloseBonus();
uint256 liquidatorBonus;
uint256 scaledRate;
if(position.isShort) {
uint256 positionBalance = position.input.add(position.commitment);
uint256 valueToConvert;
(valueToConvert, liquidatorBonus) = _safeSubtract(positionBalance, liquidationBonus);
canReturn = swapTokens(USDC_ADDRESS, position.token, valueToConvert);
require(canReturn >= minimalSwapAmount, "INSUFFICIENT_SWAP");
scaledRate = calculateScaledRate(valueToConvert, canReturn);
} else {
uint256 swap = swapTokens(position.token, USDC_ADDRESS, position.input);
require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP");
scaledRate = calculateScaledRate(swap, position.input);
uint256 canReturnOverall = swap.add(position.commitment);
(canReturn, liquidatorBonus) = _safeSubtract(canReturnOverall, liquidationBonus);
}
require(canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG), "CANNOT_LIQUIDATE");
_liquidate(position, canReturn, poolInterest);
transferEscrowToUser(position.owner, address(0x0), position.commitment);
USDC.safeTransfer(msg.sender, liquidatorBonus);
deletePosition(positionId, position, liquidatorBonus, scaledRate);
}
| function liquidatePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman nonReentrant {
Position storage position = positionInfo[positionId];
_checkPositionIsOpen(position);
uint256 canReturn;
uint256 poolInterest = calculateBorrowInterest(positionId);
uint256 liquidationBonus = calculateAutoCloseBonus();
uint256 liquidatorBonus;
uint256 scaledRate;
if(position.isShort) {
uint256 positionBalance = position.input.add(position.commitment);
uint256 valueToConvert;
(valueToConvert, liquidatorBonus) = _safeSubtract(positionBalance, liquidationBonus);
canReturn = swapTokens(USDC_ADDRESS, position.token, valueToConvert);
require(canReturn >= minimalSwapAmount, "INSUFFICIENT_SWAP");
scaledRate = calculateScaledRate(valueToConvert, canReturn);
} else {
uint256 swap = swapTokens(position.token, USDC_ADDRESS, position.input);
require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP");
scaledRate = calculateScaledRate(swap, position.input);
uint256 canReturnOverall = swap.add(position.commitment);
(canReturn, liquidatorBonus) = _safeSubtract(canReturnOverall, liquidationBonus);
}
require(canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG), "CANNOT_LIQUIDATE");
_liquidate(position, canReturn, poolInterest);
transferEscrowToUser(position.owner, address(0x0), position.commitment);
USDC.safeTransfer(msg.sender, liquidatorBonus);
deletePosition(positionId, position, liquidatorBonus, scaledRate);
}
| 47,685 |
11 | // The percent increase for any given type | mapping(uint => uint256) internal percentIncrease;
mapping(uint => uint256) internal percentBase;
| mapping(uint => uint256) internal percentIncrease;
mapping(uint => uint256) internal percentBase;
| 36,987 |
39 | // decreaseApproval of spender when not paused / | function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
| function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
| 20,350 |
638 | // Get the transaction data | bytes memory txData = _block.readTransactionData(auxiliaryData.txIndex);
| bytes memory txData = _block.readTransactionData(auxiliaryData.txIndex);
| 31,745 |
45 | // There is a tax on the way out too... | uint256 _amountToSend = _origValue.sub(m_devPercent_out.mul(_origValue));
uint256 _profit = m_investorFundPercent_out.mul(_origValue);
_amountToSend = _amountToSend.sub(m_investorFundPercent_out.mul(_profit));
totalInvestmentFund = totalInvestmentFund.sub(_origValue);
if(!msg.sender.send(_amountToSend)) {
investorMapping.data[msg.sender].value = _origValue;
totalInvestmentFund = totalInvestmentFund.add(_origValue);
| uint256 _amountToSend = _origValue.sub(m_devPercent_out.mul(_origValue));
uint256 _profit = m_investorFundPercent_out.mul(_origValue);
_amountToSend = _amountToSend.sub(m_investorFundPercent_out.mul(_profit));
totalInvestmentFund = totalInvestmentFund.sub(_origValue);
if(!msg.sender.send(_amountToSend)) {
investorMapping.data[msg.sender].value = _origValue;
totalInvestmentFund = totalInvestmentFund.add(_origValue);
| 9,031 |
430 | // adjustments[4]/mload(0x4e40), Constraint expression for memory/multi_column_perm/perm/init0: (memory/multi_column_perm/perm/interaction_elm - (column20_row0 + memory/multi_column_perm/hash_interaction_elm0column20_row1))column24_inter1_row0 + column19_row0 + memory/multi_column_perm/hash_interaction_elm0column19_row1 - memory/multi_column_perm/perm/interaction_elm. |
let val := addmod(
addmod(
addmod(
mulmod(
addmod(
|
let val := addmod(
addmod(
addmod(
mulmod(
addmod(
| 3,717 |
64 | // Returns the storage slot that the proxiable contract assumes is being used to store the implementationaddress. IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risksbricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that thisfunction revert if invoked through a proxy. / | function proxiableUUID() external view returns (bytes32);
| function proxiableUUID() external view returns (bytes32);
| 10,557 |
23 | // Set correct size of returned array solhint-disable-next-line no-inline-assembly | assembly {
mstore(array, moduleCount)
}
| assembly {
mstore(array, moduleCount)
}
| 22,426 |
27 | // check if owner | require(seller == ownerOf(catId), "Bitcat: you need to be the cat owner to resell it.");
| require(seller == ownerOf(catId), "Bitcat: you need to be the cat owner to resell it.");
| 23,575 |
67 | // 代币合约 [功能]限制最大发币量;<TokenVesting> 创建锁仓(在用户钱包内);/ | contract Token is TokenVesting {
// 代币总量限制
uint256 public totalLimit;
// 验证 代币总量限制
modifier totalSupplyLimit(uint256 _value) {
if (totalLimit > 0) {
require(
totalSupply() + _value <= totalLimit,
"Token: The mint total amount exceeds the limit"
);
}
_;
}
// /**
// * @dev 初始化
// *
// * @param _totalLimit 代币最大数量限制
// * @param _initMint 初次铸币数量
// * @param _name 代码名称
// * @param _symbol 代币简称
// *
// */
// constructor(
// uint256 _totalLimit,
// uint256 _initMint,
// string memory _name,
// string memory _symbol
// ) ERC20(_name, _symbol) {
// if (_totalLimit > 0) {
// require(_initMint <= _totalLimit, "Token: Not exceed limit");
// totalLimit = _totalLimit * 10**decimals();
// }
// _mint(msg.sender, _initMint * 10**decimals());
// }
constructor() ERC20("DMTT", "TMD") {
uint256 _totalLimit = 300000000;
uint256 _initMint = 100000000;
if (_totalLimit > 0) {
require(_initMint <= _totalLimit, "Token: Not exceed limit");
totalLimit = _totalLimit * 10**decimals();
}
_mint(msg.sender, _initMint * 10**decimals());
}
/**
* @dev 铸币 且增加代币总量
*
* [要求]
* 只有合约部署者可操作
* 总量不可超过限制
*/
function mint(address _to, uint256 _amount)
public
onlyOwner
totalSupplyLimit(_amount)
{
_mint(_to, _amount);
}
/**
* @dev 转账
* [要求]
* 不得超过可用余额(锁仓未解锁金额不可使用)
*/
function transfer(address to, uint256 amount)
public
virtual
override
availableBalance(amount)
returns (bool)
{
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev 授权他人
* [要求]
* 不得超过可用余额(锁仓未解锁金额不可使用)
*/
function approve(address spender, uint256 amount)
public
virtual
override
availableBalance(amount)
returns (bool)
{
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev 销毁调用者的`amount` 代币
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev 销毁 `account` 中的 `amount` 代币,从调用者的账户中扣除
*/
function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
}
| contract Token is TokenVesting {
// 代币总量限制
uint256 public totalLimit;
// 验证 代币总量限制
modifier totalSupplyLimit(uint256 _value) {
if (totalLimit > 0) {
require(
totalSupply() + _value <= totalLimit,
"Token: The mint total amount exceeds the limit"
);
}
_;
}
// /**
// * @dev 初始化
// *
// * @param _totalLimit 代币最大数量限制
// * @param _initMint 初次铸币数量
// * @param _name 代码名称
// * @param _symbol 代币简称
// *
// */
// constructor(
// uint256 _totalLimit,
// uint256 _initMint,
// string memory _name,
// string memory _symbol
// ) ERC20(_name, _symbol) {
// if (_totalLimit > 0) {
// require(_initMint <= _totalLimit, "Token: Not exceed limit");
// totalLimit = _totalLimit * 10**decimals();
// }
// _mint(msg.sender, _initMint * 10**decimals());
// }
constructor() ERC20("DMTT", "TMD") {
uint256 _totalLimit = 300000000;
uint256 _initMint = 100000000;
if (_totalLimit > 0) {
require(_initMint <= _totalLimit, "Token: Not exceed limit");
totalLimit = _totalLimit * 10**decimals();
}
_mint(msg.sender, _initMint * 10**decimals());
}
/**
* @dev 铸币 且增加代币总量
*
* [要求]
* 只有合约部署者可操作
* 总量不可超过限制
*/
function mint(address _to, uint256 _amount)
public
onlyOwner
totalSupplyLimit(_amount)
{
_mint(_to, _amount);
}
/**
* @dev 转账
* [要求]
* 不得超过可用余额(锁仓未解锁金额不可使用)
*/
function transfer(address to, uint256 amount)
public
virtual
override
availableBalance(amount)
returns (bool)
{
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev 授权他人
* [要求]
* 不得超过可用余额(锁仓未解锁金额不可使用)
*/
function approve(address spender, uint256 amount)
public
virtual
override
availableBalance(amount)
returns (bool)
{
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev 销毁调用者的`amount` 代币
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev 销毁 `account` 中的 `amount` 代币,从调用者的账户中扣除
*/
function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
}
| 26,575 |
251 | // Base events | event CreatedCollection(uint256 id, BigFanMetadata.Collection collection);
event CreatedCard(address recipient, uint256 tokenId, string playerName, string country, string position, uint256 collectionId, uint256 age, uint256 points, uint256 caps, uint256 price);
event UpdatedCard(uint256 tokenId);
event DeletedCard(uint256 tokenId);
event BoughtToken(address recipient, uint256 tokenId, uint256 amount);
| event CreatedCollection(uint256 id, BigFanMetadata.Collection collection);
event CreatedCard(address recipient, uint256 tokenId, string playerName, string country, string position, uint256 collectionId, uint256 age, uint256 points, uint256 caps, uint256 price);
event UpdatedCard(uint256 tokenId);
event DeletedCard(uint256 tokenId);
event BoughtToken(address recipient, uint256 tokenId, uint256 amount);
| 17,279 |
40 | // addresses that claimed a free mint (from the giga-radlist) | mapping(address => bool) public freeMinters;
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
| mapping(address => bool) public freeMinters;
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
| 40,048 |
93 | // Finalizes crowdsale | function _finalization()
internal
whenNotFinalized
| function _finalization()
internal
whenNotFinalized
| 7,524 |
35 | // Store the promise expiration date (as a unix timestamp) | promiseExpirationDate[promiseId] = _code & 0xFFFFFFFF; // the first 32bit word of the _code
require(promiseExpirationDate[promiseId] != 0);
uint256 fee = 0;
if (feePercent != 0) {
| promiseExpirationDate[promiseId] = _code & 0xFFFFFFFF; // the first 32bit word of the _code
require(promiseExpirationDate[promiseId] != 0);
uint256 fee = 0;
if (feePercent != 0) {
| 5,802 |
36 | // Allows the current owner to relinquish control of the contract. Renouncing to ownership will leave the contract without an owner.It will not be possible to call the functions with the `onlyOwner`modifier anymore. / | function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
| function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
| 6,611 |
81 | // function fuse() external view returns (address); TODO | function comptroller() external view returns (address);
function registry() external view returns (address payable);
function userFeeVeriForwarder() external view returns (address);
| function comptroller() external view returns (address);
function registry() external view returns (address payable);
function userFeeVeriForwarder() external view returns (address);
| 51,254 |
0 | // Mapping variable ~ allowanceMoney | mapping(address => uint) public allowanceMoney;
| mapping(address => uint) public allowanceMoney;
| 43,877 |
919 | // Construct a new CEther money market comptroller_ The address of the Comptroller interestRateModel_ The address of the interest rate model initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 name_ ERC-20 name of this token symbol_ ERC-20 symbol of this token decimals_ ERC-20 decimal precision of this token admin_ Address of the administrator of this token / |
constructor(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
|
constructor(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
| 1,423 |
61 | // 회사의 지갑 주소 | address public company;
| address public company;
| 11,258 |
83 | // Set allowance for other address and notify Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it_spender The address authorized to spend _value the max amount they can spend _extraData some extra information to send to the approved contract / | function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
onlyTranferable
returns (bool success)
| function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
onlyTranferable
returns (bool success)
| 12,441 |
44 | // Execute mint | _mint(to, lpTokensMinted);
| _mint(to, lpTokensMinted);
| 22,939 |
364 | // Assign the minimum credit available to consider for harvesting | MIN_AMOUNT_HARVEST = _minAmountHarvest;
| MIN_AMOUNT_HARVEST = _minAmountHarvest;
| 2,285 |
90 | // Check that no votes have been registered for the proposal apart from the proposal creator, pool creator can remove any proposal. | if (!isAdmin(msg.sender)) {
require(currentProposal.voterAddresses.length() == 1);
}
| if (!isAdmin(msg.sender)) {
require(currentProposal.voterAddresses.length() == 1);
}
| 10,812 |
43 | // Returns single data by tokenId / | function getSingleItem(uint256 _tokenId) public view returns (MarketplaceItem memory) {
return marketplaceItems[_tokenId];
}
| function getSingleItem(uint256 _tokenId) public view returns (MarketplaceItem memory) {
return marketplaceItems[_tokenId];
}
| 21,842 |
33 | // For debugging and testing/ | function getVoter() public view returns(bytes32, bool) {
return (votersMap[msg.sender].commit, votersMap[msg.sender].voted);
}
| function getVoter() public view returns(bytes32, bool) {
return (votersMap[msg.sender].commit, votersMap[msg.sender].voted);
}
| 22,184 |
88 | // Validate that address array lengths match, and calling address array are not emptyand contain no duplicate elements.A Array of addresses B Array of addresses / | function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
| function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
| 24,620 |
43 | // Mark the strategy as not supported | strategies[_addr].isSupported = false;
| strategies[_addr].isSupported = false;
| 41,822 |
107 | // Transfer tokens from one address to another_from address The address which you want to send tokens from_to address The address which you want to transfer to_amount uint256 the amount of tokens to be transferred/ | function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) {
require(_to != address(0), "You can not transfer to address(0).");
require(_amount <= unlockedBalanceOf(_from), "There is not enough unlocked balance.");
require(_amount <= allowed[_from][msg.sender], "There is not enough allowance.");
consolidateBalance(_from);
return super.transferFrom(_from, _to, _amount);
}
| function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) {
require(_to != address(0), "You can not transfer to address(0).");
require(_amount <= unlockedBalanceOf(_from), "There is not enough unlocked balance.");
require(_amount <= allowed[_from][msg.sender], "There is not enough allowance.");
consolidateBalance(_from);
return super.transferFrom(_from, _to, _amount);
}
| 22,653 |
39 | // addresses are "0x" followed by 20 bytes of data which take up 2 characters each | bytes memory result = new bytes(42);
| bytes memory result = new bytes(42);
| 40,375 |
10 | // ERC20 // UACToken / | modifier onlyBy(address _account) {
require(msg.sender == _account);
_;
}
| modifier onlyBy(address _account) {
require(msg.sender == _account);
_;
}
| 17,155 |
50 | // trading enabled | uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
| uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
| 9,504 |
203 | // Sets {token} as the base token. WARNING: This function should only be called from the constructor. Mostapplications that interact with token contracts will not expect{token} to ever change, and may work incorrectly if it does. / | function _setupToken(IERC20 token_) internal {
_token = token_;
}
| function _setupToken(IERC20 token_) internal {
_token = token_;
}
| 43,841 |
25 | // If a strategy was not matched, this means that it is not used by any smart vault and should not be included in the list. | revert InvalidStrategies();
| revert InvalidStrategies();
| 35,765 |
150 | // weight in bits 0-87 bits. | fundingCycle.weight = uint256(uint88(_packedIntrinsicProperties));
| fundingCycle.weight = uint256(uint88(_packedIntrinsicProperties));
| 12,421 |
0 | // uint256 EGGS_PER_SHRIMP_PER_SECOND=1; | uint256 public EGGS_TO_HATCH_1SHRIMP=86400;//for final version should be seconds in a day
uint256 public STARTING_SHRIMP=300;
uint256 PSN=10000;
uint256 PSNH=5000;
bool public initialized=true;
address public ceoAddress;
mapping (address => uint256) public hatcheryShrimp;
mapping (address => uint256) public claimedEggs;
mapping (address => uint256) public lastHatch;
mapping (address => address) public referrals;
| uint256 public EGGS_TO_HATCH_1SHRIMP=86400;//for final version should be seconds in a day
uint256 public STARTING_SHRIMP=300;
uint256 PSN=10000;
uint256 PSNH=5000;
bool public initialized=true;
address public ceoAddress;
mapping (address => uint256) public hatcheryShrimp;
mapping (address => uint256) public claimedEggs;
mapping (address => uint256) public lastHatch;
mapping (address => address) public referrals;
| 31,316 |
154 | // Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian) | emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian);
| emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian);
| 8,639 |
2 | // deposit swapExactEthForTokens | function depositExactEthForTokenOrder(address router,address pair,uint amountIn,uint amountOut) external payable;
| function depositExactEthForTokenOrder(address router,address pair,uint amountIn,uint amountOut) external payable;
| 58,671 |
191 | // Used to determine if the Vault will operate on a strategy. | bool trusted;
| bool trusted;
| 19,915 |
9 | // todo: 增加对价格校验的逻辑,和 chainlink 拿价格比较相差幅度 | bytes32[] memory ids = pendingPrice.ids;
require(pendingPrice.blockNumber > 0 && ids.length > 0, "LibPriceFacade: requestId does not exist");
LatestCallbackPrice storage cachePrice = pfs.callbackPrices[pendingPrice.token];
cachePrice.timestamp = block.timestamp;
cachePrice.price = price;
for (uint i; i < ids.length;) {
LibTrading.openMarketTradeCallback(ids[i], price);
unchecked {
i++;
| bytes32[] memory ids = pendingPrice.ids;
require(pendingPrice.blockNumber > 0 && ids.length > 0, "LibPriceFacade: requestId does not exist");
LatestCallbackPrice storage cachePrice = pfs.callbackPrices[pendingPrice.token];
cachePrice.timestamp = block.timestamp;
cachePrice.price = price;
for (uint i; i < ids.length;) {
LibTrading.openMarketTradeCallback(ids[i], price);
unchecked {
i++;
| 3,744 |
35 | // Adventure Time for Genesis Adventurer holders!/This contract mints Adventure Time for Loot holders and provides/ administrative functions to the Loot DAO. It allows:/Genesis Adventurer holders to claim Adventure Time/A DAO to set seasons for new opportunities to claim Adventure Time/A DAO to mint Adventure Time for use within the Loot ecosystem/ @custom:unaudited This contract has not been audited. Use at your own risk. | contract AdventureTime is Context, Ownable, ERC20 {
// Genesis Adventurer contract is available at https://etherscan.io/token/0x8db687aceb92c66f013e1d614137238cc698fedb
address public gaContractAddress;
IERC721Enumerable private _gaContract;
// Give out 100,000 Adventure Time for every Genesis Adventurer that a user holds
uint256 public adventureTimePerTokenId = 20320 * (10**decimals());
uint256 public tokenIdStart = 1;
uint256 public tokenIdEnd = 2540;
// Seasons are used to allow users to claim tokens regularly. Seasons are
// decided by the DAO.
uint256 public season = 0;
// Track claimed tokens within a season
// IMPORTANT: The format of the mapping is:
// claimedForSeason[season][tokenId][claimed]
mapping(uint256 => mapping(uint256 => bool)) public seasonClaimedByTokenId;
constructor(address _gaContractAddress, address _genesisDaoAddress)
Ownable()
ERC20("Adventure Time", "ATIME")
{
// Transfer ownership to the Genesis Project DAO
// Ownable by OpenZeppelin automatically sets owner to msg.sender, but
// we're going to be using a separate wallet for deployment
transferOwnership(_genesisDaoAddress);
gaContractAddress = _gaContractAddress;
_gaContract = IERC721Enumerable(gaContractAddress);
}
function claimById(uint256 tokenId) external {
// Follow the Checks-Effects-Interactions pattern to prevent reentrancy
// attacks
// Checks
// Check that the msgSender owns the token that is being claimed
require(
_msgSender() == _gaContract.ownerOf(tokenId),
"MUST_OWN_TOKEN_ID"
);
// Further Checks, Effects, and Interactions are contained within the
// _claim() function
_claim(tokenId);
}
function claimAllForOwner() external {
uint256 tokenBalanceOwner = _gaContract.balanceOf(_msgSender());
// Checks
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
// i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed
for (uint256 i = 0; i < tokenBalanceOwner; i++) {
// Further Checks, Effects, and Interactions are contained within
// the _claim() function
_claim(_gaContract.tokenOfOwnerByIndex(_msgSender(), i));
}
}
/// @notice Claim Adventure Time for a given Genesis Adventurer ID
/// @param tokenId The tokenId of the GA NFT
function _claim(uint256 tokenId) internal {
// Follow the Checks-Effects-Interactions pattern to prevent reentrancy
// attacks
// Checks
// Check that the msgSender owns the token that is being claimed
require(
_msgSender() == _gaContract.ownerOf(tokenId),
"MUST_OWN_TOKEN_ID"
);
// Check that the token ID is in range
// We use >= and <= to here because all of the token IDs are 0-indexed
require(
tokenId >= tokenIdStart && tokenId <= tokenIdEnd,
"TOKEN_ID_OUT_OF_RANGE"
);
// Check that Adventure Time have not already been claimed this season
// for a given tokenId
require(
!seasonClaimedByTokenId[season][tokenId],
"TIME_CLAIMED_FOR_TOKEN_ID"
);
// Effects
// Mark that Adventure Time has been claimed for this season for the
// given tokenId
seasonClaimedByTokenId[season][tokenId] = true;
// Interactions
// Send Adventure Time to the owner of the token ID
_mint(_msgSender(), adventureTimePerTokenId);
}
/// @notice Allows the DAO to mint new tokens for use within the Loot
/// Ecosystem
/// @param amountDisplayValue The amount of Loot to mint. This should be
/// input as the display value, not in raw decimals. If you want to mint
/// 100 Loot, you should enter "100" rather than the value of 100 * 10^18.
function daoMint(uint256 amountDisplayValue) external onlyOwner {
_mint(owner(), amountDisplayValue * (10**decimals()));
}
/// @notice Allows the DAO to set a new contract address for Loot. This is
/// relevant in the event that Loot migrates to a new contract.
/// @param gaContractAddress_ The new contract address for Loot
function daoSetGAContractAddress(address gaContractAddress_)
external
onlyOwner
{
gaContractAddress = gaContractAddress_;
_gaContract = IERC721Enumerable(gaContractAddress);
}
/// @notice Allows the DAO to set the token IDs that are eligible to claim
/// Loot
/// @param tokenIdStart_ The start of the eligible token range
/// @param tokenIdEnd_ The end of the eligible token range
/// @dev This is relevant in case a future GA contract has a different
/// total supply of GA's
function daoSetTokenIdRange(uint256 tokenIdStart_, uint256 tokenIdEnd_)
external
onlyOwner
{
tokenIdStart = tokenIdStart_;
tokenIdEnd = tokenIdEnd_;
}
/// @notice Allows the DAO to set a season for new Adventure Time claims
/// @param season_ The season to use for claiming Loot
function daoSetSeason(uint256 season_) public onlyOwner {
season = season_;
}
/// @notice Allows the DAO to set the amount of Adventure Time that is
/// claimed per token ID
/// @param adventureTimeDisplayValue The amount of Loot a user can claim.
/// This should be input as the display value, not in raw decimals. If you
/// want to mint 100 Loot, you should enter "100" rather than the value of
/// 100 * 10^18.
function daoSetAdventureTimePerTokenId(uint256 adventureTimeDisplayValue)
public
onlyOwner
{
adventureTimePerTokenId = adventureTimeDisplayValue * (10**decimals());
}
/// @notice Allows the DAO to set the season and Adventure Time per token ID
/// in one transaction. This ensures that there is not a gap where a user
/// can claim more Adventure Time than others
/// @param season_ The season to use for claiming loot
/// @param adventureTimeDisplayValue The amount of Loot a user can claim.
/// This should be input as the display value, not in raw decimals. If you
/// want to mint 100 Loot, you should enter "100" rather than the value of
/// 100 * 10^18.
/// @dev We would save a tiny amount of gas by modifying the season and
/// adventureTime variables directly. It is better practice for security,
/// however, to avoid repeating code. This function is so rarely used that
/// it's not worth moving these values into their own internal function to
/// skip the gas used on the modifier check.
function daoSetSeasonAndAdventureTimePerTokenId(
uint256 season_,
uint256 adventureTimeDisplayValue
) external onlyOwner {
daoSetSeason(season_);
daoSetAdventureTimePerTokenId(adventureTimeDisplayValue);
}
}
| contract AdventureTime is Context, Ownable, ERC20 {
// Genesis Adventurer contract is available at https://etherscan.io/token/0x8db687aceb92c66f013e1d614137238cc698fedb
address public gaContractAddress;
IERC721Enumerable private _gaContract;
// Give out 100,000 Adventure Time for every Genesis Adventurer that a user holds
uint256 public adventureTimePerTokenId = 20320 * (10**decimals());
uint256 public tokenIdStart = 1;
uint256 public tokenIdEnd = 2540;
// Seasons are used to allow users to claim tokens regularly. Seasons are
// decided by the DAO.
uint256 public season = 0;
// Track claimed tokens within a season
// IMPORTANT: The format of the mapping is:
// claimedForSeason[season][tokenId][claimed]
mapping(uint256 => mapping(uint256 => bool)) public seasonClaimedByTokenId;
constructor(address _gaContractAddress, address _genesisDaoAddress)
Ownable()
ERC20("Adventure Time", "ATIME")
{
// Transfer ownership to the Genesis Project DAO
// Ownable by OpenZeppelin automatically sets owner to msg.sender, but
// we're going to be using a separate wallet for deployment
transferOwnership(_genesisDaoAddress);
gaContractAddress = _gaContractAddress;
_gaContract = IERC721Enumerable(gaContractAddress);
}
function claimById(uint256 tokenId) external {
// Follow the Checks-Effects-Interactions pattern to prevent reentrancy
// attacks
// Checks
// Check that the msgSender owns the token that is being claimed
require(
_msgSender() == _gaContract.ownerOf(tokenId),
"MUST_OWN_TOKEN_ID"
);
// Further Checks, Effects, and Interactions are contained within the
// _claim() function
_claim(tokenId);
}
function claimAllForOwner() external {
uint256 tokenBalanceOwner = _gaContract.balanceOf(_msgSender());
// Checks
require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED");
// i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed
for (uint256 i = 0; i < tokenBalanceOwner; i++) {
// Further Checks, Effects, and Interactions are contained within
// the _claim() function
_claim(_gaContract.tokenOfOwnerByIndex(_msgSender(), i));
}
}
/// @notice Claim Adventure Time for a given Genesis Adventurer ID
/// @param tokenId The tokenId of the GA NFT
function _claim(uint256 tokenId) internal {
// Follow the Checks-Effects-Interactions pattern to prevent reentrancy
// attacks
// Checks
// Check that the msgSender owns the token that is being claimed
require(
_msgSender() == _gaContract.ownerOf(tokenId),
"MUST_OWN_TOKEN_ID"
);
// Check that the token ID is in range
// We use >= and <= to here because all of the token IDs are 0-indexed
require(
tokenId >= tokenIdStart && tokenId <= tokenIdEnd,
"TOKEN_ID_OUT_OF_RANGE"
);
// Check that Adventure Time have not already been claimed this season
// for a given tokenId
require(
!seasonClaimedByTokenId[season][tokenId],
"TIME_CLAIMED_FOR_TOKEN_ID"
);
// Effects
// Mark that Adventure Time has been claimed for this season for the
// given tokenId
seasonClaimedByTokenId[season][tokenId] = true;
// Interactions
// Send Adventure Time to the owner of the token ID
_mint(_msgSender(), adventureTimePerTokenId);
}
/// @notice Allows the DAO to mint new tokens for use within the Loot
/// Ecosystem
/// @param amountDisplayValue The amount of Loot to mint. This should be
/// input as the display value, not in raw decimals. If you want to mint
/// 100 Loot, you should enter "100" rather than the value of 100 * 10^18.
function daoMint(uint256 amountDisplayValue) external onlyOwner {
_mint(owner(), amountDisplayValue * (10**decimals()));
}
/// @notice Allows the DAO to set a new contract address for Loot. This is
/// relevant in the event that Loot migrates to a new contract.
/// @param gaContractAddress_ The new contract address for Loot
function daoSetGAContractAddress(address gaContractAddress_)
external
onlyOwner
{
gaContractAddress = gaContractAddress_;
_gaContract = IERC721Enumerable(gaContractAddress);
}
/// @notice Allows the DAO to set the token IDs that are eligible to claim
/// Loot
/// @param tokenIdStart_ The start of the eligible token range
/// @param tokenIdEnd_ The end of the eligible token range
/// @dev This is relevant in case a future GA contract has a different
/// total supply of GA's
function daoSetTokenIdRange(uint256 tokenIdStart_, uint256 tokenIdEnd_)
external
onlyOwner
{
tokenIdStart = tokenIdStart_;
tokenIdEnd = tokenIdEnd_;
}
/// @notice Allows the DAO to set a season for new Adventure Time claims
/// @param season_ The season to use for claiming Loot
function daoSetSeason(uint256 season_) public onlyOwner {
season = season_;
}
/// @notice Allows the DAO to set the amount of Adventure Time that is
/// claimed per token ID
/// @param adventureTimeDisplayValue The amount of Loot a user can claim.
/// This should be input as the display value, not in raw decimals. If you
/// want to mint 100 Loot, you should enter "100" rather than the value of
/// 100 * 10^18.
function daoSetAdventureTimePerTokenId(uint256 adventureTimeDisplayValue)
public
onlyOwner
{
adventureTimePerTokenId = adventureTimeDisplayValue * (10**decimals());
}
/// @notice Allows the DAO to set the season and Adventure Time per token ID
/// in one transaction. This ensures that there is not a gap where a user
/// can claim more Adventure Time than others
/// @param season_ The season to use for claiming loot
/// @param adventureTimeDisplayValue The amount of Loot a user can claim.
/// This should be input as the display value, not in raw decimals. If you
/// want to mint 100 Loot, you should enter "100" rather than the value of
/// 100 * 10^18.
/// @dev We would save a tiny amount of gas by modifying the season and
/// adventureTime variables directly. It is better practice for security,
/// however, to avoid repeating code. This function is so rarely used that
/// it's not worth moving these values into their own internal function to
/// skip the gas used on the modifier check.
function daoSetSeasonAndAdventureTimePerTokenId(
uint256 season_,
uint256 adventureTimeDisplayValue
) external onlyOwner {
daoSetSeason(season_);
daoSetAdventureTimePerTokenId(adventureTimeDisplayValue);
}
}
| 81,947 |
22 | // 거래소에 인출을 허락한 토큰의 양이 판매할 양보다 많아야 합니다. | require(erc20.allowance(msg.sender, this) >= amount);
| require(erc20.allowance(msg.sender, this) >= amount);
| 39,410 |
524 | // add new value to total history | totalStakedHistory.add(block.number.toUint64(), newStake);
| totalStakedHistory.add(block.number.toUint64(), newStake);
| 56,065 |
20 | // The render provider payment address for all secondary sales royalty/ revenues | address payable public renderProviderSecondarySalesAddress;
| address payable public renderProviderSecondarySalesAddress;
| 20,247 |
182 | // Set the governance address after confirming contract identity _governanceAddress - Incoming governance address / | function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"Staking: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
| function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"Staking: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
| 45,208 |
113 | // The returrn value is time-based on last time the contract had rewards active multipliede by the reward-rate. It's evened out with a division of bonus effective supply. | return rewardPerTokenStored
.add(
lastTimeRewardsActive()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(stakingTokenMultiplier)
.div(effectiveTotalSupply)
);
| return rewardPerTokenStored
.add(
lastTimeRewardsActive()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(stakingTokenMultiplier)
.div(effectiveTotalSupply)
);
| 22,448 |
157 | // data symmetric key is XORed with exchange key | bool validDataKey = keccak256(abi.encodePacked(dataKey)) == exchange.dataKeyHash;
exchange.state = PrivateDataExchangeState.Closed;
uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue);
address cheater;
if (validDataKey) {// the data key was valid -> data requester cheated
require(exchange.passportOwner.send(val));
cheater = exchange.dataRequester;
| bool validDataKey = keccak256(abi.encodePacked(dataKey)) == exchange.dataKeyHash;
exchange.state = PrivateDataExchangeState.Closed;
uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue);
address cheater;
if (validDataKey) {// the data key was valid -> data requester cheated
require(exchange.passportOwner.send(val));
cheater = exchange.dataRequester;
| 82,002 |
18 | // Allows a user to sell from a vault/_amount Number of shares to sell/ return Bool the function executed correctly | function sellVault(uint256 _amount)
external
hasEnough(_amount)
positiveAmount(_amount)
minimumPeriodPast
returns (bool success)
| function sellVault(uint256 _amount)
external
hasEnough(_amount)
positiveAmount(_amount)
minimumPeriodPast
returns (bool success)
| 2,198 |
194 | // Request unstake a validator./validatorId validator id. | function unstake(uint256 validatorId) external;
| function unstake(uint256 validatorId) external;
| 44,602 |
234 | // can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier`onlyOwner`, which can be applied to your functions to restrict their use tothe owner. / | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
| abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
| 1,211 |
204 | // get price for print 'printNum' Note: printNum == totalSupply at time of minting since we're 0 indexed / | function getPrintPrice(uint256 printNum) public view returns (uint256 price) {
uint256 decimals = 10 ** SIG_DIGITS;
// A + Bx + Cx^2
price = A.add(B.mul(printNum)).add(C.mul(printNum ** 2));
// convert to wei
price = price.mul(1 ether).div(decimals);
}
| function getPrintPrice(uint256 printNum) public view returns (uint256 price) {
uint256 decimals = 10 ** SIG_DIGITS;
// A + Bx + Cx^2
price = A.add(B.mul(printNum)).add(C.mul(printNum ** 2));
// convert to wei
price = price.mul(1 ether).div(decimals);
}
| 79,063 |
63 | // Assign values to the 9 parameters | itemSKU=items[_upc].sku;
itemUPC=items[_upc].upc;
productID=items[_upc].productID;
productNotes=items[_upc].productNotes;
productPrice=items[_upc].productPrice;
itemState=uint8(items[_upc].itemState);
distributorID=items[_upc].distributorID;
retailerID=items[_upc].retailerID;
consumerID=items[_upc].consumerID;
| itemSKU=items[_upc].sku;
itemUPC=items[_upc].upc;
productID=items[_upc].productID;
productNotes=items[_upc].productNotes;
productPrice=items[_upc].productPrice;
itemState=uint8(items[_upc].itemState);
distributorID=items[_upc].distributorID;
retailerID=items[_upc].retailerID;
consumerID=items[_upc].consumerID;
| 13,960 |
16 | // Liquifies tokens to counter. / | function divest(uint256 amountOfTokens) onlyTokenHolders public returns(uint256) {
//They cannot divest 0 tokens.
require(amountOfTokens > 0, "You cannot divest 0 tokens.");
//The cannot transfer more than they own
require(amountOfTokens <= balanceOf(msg.sender), "You cannot divest more tokens than you have.");
//Do the sell
return burnTokens(msg.sender, amountOfTokens);
}
| function divest(uint256 amountOfTokens) onlyTokenHolders public returns(uint256) {
//They cannot divest 0 tokens.
require(amountOfTokens > 0, "You cannot divest 0 tokens.");
//The cannot transfer more than they own
require(amountOfTokens <= balanceOf(msg.sender), "You cannot divest more tokens than you have.");
//Do the sell
return burnTokens(msg.sender, amountOfTokens);
}
| 58,305 |
67 | // if address already staked, verify further | if (balances[account] > 0) {
| if (balances[account] > 0) {
| 14,690 |
10 | // Reset pending addresses. | delete _pendingWhitelistAddition;
| delete _pendingWhitelistAddition;
| 16,874 |
203 | // setting relayer in the TWAP | newTwap.modifyParameters("relayer", address(rewardRelayer));
| newTwap.modifyParameters("relayer", address(rewardRelayer));
| 20,347 |
30 | // Make the result negative if the sign bit is not 0 | if (sign != 0) {
result *= - 1;
}
| if (sign != 0) {
result *= - 1;
}
| 27,289 |
13 | // Gets account&39;s balance/_addr Address of the account/ return Account balance | function balanceOf(address _addr)
public
constant
| function balanceOf(address _addr)
public
constant
| 33,224 |
37 | // Iterable mapping from address to uint; | struct Map {
address[] keys;
mapping(address => uint256) values;
mapping(address => uint256) indexOf;
mapping(address => bool) inserted;
}
| struct Map {
address[] keys;
mapping(address => uint256) values;
mapping(address => uint256) indexOf;
mapping(address => bool) inserted;
}
| 59,926 |
36 | // Setup auto-approval for Zora v3 access to sell NFT/Still requires approval for module/nftOwner owner of the nft/operator operator wishing to transfer/burn/etc the NFTs | function isApprovedForAll(address nftOwner, address operator)
public
view
override(ERC721AUpgradeable)
returns (bool)
| function isApprovedForAll(address nftOwner, address operator)
public
view
override(ERC721AUpgradeable)
returns (bool)
| 26,695 |
238 | // max duration of a purchased sBond | uint16 public BOND_LIFE_MAX = 90; // in days
bool public PAUSED_BUY_JUNIOR_TOKEN = false;
bool public PAUSED_BUY_SENIOR_BOND = false;
function setHarvestCost(uint256 newValue_)
public
onlyDao
| uint16 public BOND_LIFE_MAX = 90; // in days
bool public PAUSED_BUY_JUNIOR_TOKEN = false;
bool public PAUSED_BUY_SENIOR_BOND = false;
function setHarvestCost(uint256 newValue_)
public
onlyDao
| 24,429 |
218 | // The loan is in auction, higest price liquidator will got chance to claim it. | Auction,
| Auction,
| 54,038 |
71 | // Returns the last updated price. Decimals is 8. // Returns the timestamp of the last updated price. / | function latestTimestamp() external returns (uint256);
| function latestTimestamp() external returns (uint256);
| 7,107 |
4 | // native => bool | mapping(address => bool) public isNative;
| mapping(address => bool) public isNative;
| 11,881 |
217 | // If this is an excluded wallet, then it's simpler as they are not charged taxes. Take tokens from sender. | wallets[sender].tokensOwned -= tAmount;
| wallets[sender].tokensOwned -= tAmount;
| 26,645 |
103 | // MIT License =========== Copyright (c) 2020 Synthetix Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT | library SafeDecimal {
using SafeMath for uint;
uint8 public constant decimals = 18;
uint public constant UNIT = 10 ** uint(decimals);
function unit() external pure returns (uint) {
return UNIT;
}
function multiply(uint x, uint y) internal pure returns (uint) {
return x.mul(y).div(UNIT);
}
// https://mpark.github.io/programming/2014/08/18/exponentiation-by-squaring/
function power(uint x, uint n) internal pure returns (uint) {
uint result = UNIT;
while (n > 0) {
if (n % 2 != 0) {
result = multiply(result, x);
}
x = multiply(x, x);
n /= 2;
}
return result;
}
}
| library SafeDecimal {
using SafeMath for uint;
uint8 public constant decimals = 18;
uint public constant UNIT = 10 ** uint(decimals);
function unit() external pure returns (uint) {
return UNIT;
}
function multiply(uint x, uint y) internal pure returns (uint) {
return x.mul(y).div(UNIT);
}
// https://mpark.github.io/programming/2014/08/18/exponentiation-by-squaring/
function power(uint x, uint n) internal pure returns (uint) {
uint result = UNIT;
while (n > 0) {
if (n % 2 != 0) {
result = multiply(result, x);
}
x = multiply(x, x);
n /= 2;
}
return result;
}
}
| 11,543 |
78 | // Change the paused state of the contract Only the contract owner may call this. / | function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
| function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
| 4,725 |
29 | // Contributors storage mapping. | mapping(address => Contributor) private contributors;
| mapping(address => Contributor) private contributors;
| 49,293 |
21 | // Consumes at least all inbox messages put into L1 inbox before your prev node’s L1 blocknum | assertion.afterState.inboxCount >= assertion.beforeState.inboxMaxCount ||
| assertion.afterState.inboxCount >= assertion.beforeState.inboxMaxCount ||
| 8,519 |
9 | // modifier, Only manager can be granted exclusive access to specific functions. / | modifier onlyManager() {
require(_managerAddress == msg.sender,"Managerable: caller is not the Manager");
_;
}
| modifier onlyManager() {
require(_managerAddress == msg.sender,"Managerable: caller is not the Manager");
_;
}
| 35,021 |
71 | // get rate update block | bytes32 compactData = tokenRatesCompactData[tokenData[token].compactDataArrayIndex];
uint updateRateBlock = getLast4Bytes(compactData);
if (currentBlockNumber >= updateRateBlock + validRateDurationInBlocks) return 0; // rate is expired
| bytes32 compactData = tokenRatesCompactData[tokenData[token].compactDataArrayIndex];
uint updateRateBlock = getLast4Bytes(compactData);
if (currentBlockNumber >= updateRateBlock + validRateDurationInBlocks) return 0; // rate is expired
| 80,969 |
8 | // Owner of account approves the transfer of an amount to another account | mapping(address => mapping(address=>uint256)) allowed;
| mapping(address => mapping(address=>uint256)) allowed;
| 56,712 |
454 | // If there are any children tokens then send them as part of the burn | if (parentToChildMapping[_tokenId].length() > 0) {
| if (parentToChildMapping[_tokenId].length() > 0) {
| 29,824 |
16 | // Collect all reward tokens left in pool after certain time has passed toTransfer: address to transfer leftover tokens to / | function getLeftovers(address toTransfer) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
require((endBlock + factory.getDelta()) >= block.number, "Too early");
for (uint256 i; i < _numOfRewardTokens; i++) {
ERC20 token = rewardToken[i];
token.safeTransfer(toTransfer, token.balanceOf(address(this)));
}
}
| function getLeftovers(address toTransfer) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
require((endBlock + factory.getDelta()) >= block.number, "Too early");
for (uint256 i; i < _numOfRewardTokens; i++) {
ERC20 token = rewardToken[i];
token.safeTransfer(toTransfer, token.balanceOf(address(this)));
}
}
| 12,269 |
40 | // 获取 token/ETH 交易对的价格(目前是 USDT 和 USDC ),单位是 1e18 | chainlinkContract = AggregatorInterface(tokenChainlinkMap[token]);
int256 tokenPrice = chainlinkContract.latestAnswer();
return (uint256(basePrice).mul(uint256(tokenPrice)).div(1e8), true);
| chainlinkContract = AggregatorInterface(tokenChainlinkMap[token]);
int256 tokenPrice = chainlinkContract.latestAnswer();
return (uint256(basePrice).mul(uint256(tokenPrice)).div(1e8), true);
| 39,674 |
56 | // ComplexChildToken Complex child token to be generated by TokenFather. / | contract ComplexChildToken is ChildToken, Refundable, MintableToken, BurnableToken {
string public name;
string public symbol;
uint8 public decimals;
bool public canBurn;
event Burn(address indexed burner, uint256 value);
function ComplexChildToken(address _owner, string _name, string _symbol, uint256 _initSupply, uint8 _decimals,
bool _canMint, bool _canBurn) public {
require(_owner != address(0));
owner = _owner;
name = _name;
symbol = _symbol;
decimals = _decimals;
uint256 amount = _initSupply;
totalSupply_ = totalSupply_.add(amount);
balances[owner] = balances[owner].add(amount);
Transfer(address(0), owner, amount);
if (!_canMint) {
mintingFinished = true;
}
canBurn = _canBurn;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(canBurn);
BurnableToken.burn(_value);
}
function ownerCanBurn(bool _canBurn) onlyOwner public {
canBurn = _canBurn;
}
} | contract ComplexChildToken is ChildToken, Refundable, MintableToken, BurnableToken {
string public name;
string public symbol;
uint8 public decimals;
bool public canBurn;
event Burn(address indexed burner, uint256 value);
function ComplexChildToken(address _owner, string _name, string _symbol, uint256 _initSupply, uint8 _decimals,
bool _canMint, bool _canBurn) public {
require(_owner != address(0));
owner = _owner;
name = _name;
symbol = _symbol;
decimals = _decimals;
uint256 amount = _initSupply;
totalSupply_ = totalSupply_.add(amount);
balances[owner] = balances[owner].add(amount);
Transfer(address(0), owner, amount);
if (!_canMint) {
mintingFinished = true;
}
canBurn = _canBurn;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(canBurn);
BurnableToken.burn(_value);
}
function ownerCanBurn(bool _canBurn) onlyOwner public {
canBurn = _canBurn;
}
} | 32,296 |
54 | // change sell price | function changePatentSale(uint16 assetId, uint256 newPrice) external whenNotPaused {
Patent memory patent = patents[assetId];
require(patent.patentOwner == msg.sender);
if (patent.lastPrice > 0) {
require(newPrice <= 2 * patent.lastPrice);
} else {
require(newPrice <= 1 ether);
}
require(patent.onSale == true);
patent.price = newPrice;
patents[assetId] = patent;
// Emit the event
emit ChangePatentSale(assetId, newPrice);
}
| function changePatentSale(uint16 assetId, uint256 newPrice) external whenNotPaused {
Patent memory patent = patents[assetId];
require(patent.patentOwner == msg.sender);
if (patent.lastPrice > 0) {
require(newPrice <= 2 * patent.lastPrice);
} else {
require(newPrice <= 1 ether);
}
require(patent.onSale == true);
patent.price = newPrice;
patents[assetId] = patent;
// Emit the event
emit ChangePatentSale(assetId, newPrice);
}
| 68,975 |
32 | // DorsalFin | rgbToHex(randomDorsalR, randomDorsalG, randomDorsalB)
];
| rgbToHex(randomDorsalR, randomDorsalG, randomDorsalB)
];
| 10,326 |
173 | // add an admin.Can only be called by contract owner. / | function approveAdmin(address admin) external;
| function approveAdmin(address admin) external;
| 35,166 |
0 | // Add to ERC165 Interface Check | supportedInterfaces[
this.totalSupply.selector ^
this.tokenByIndex.selector ^
this.tokenOfOwnerByIndex.selector
] = true;
| supportedInterfaces[
this.totalSupply.selector ^
this.tokenByIndex.selector ^
this.tokenOfOwnerByIndex.selector
] = true;
| 15,771 |
75 | // set up for assembly call | uint _toCopy;
bool _success;
bytes memory _returnData = new bytes(_maxCopy);
| uint _toCopy;
bool _success;
bytes memory _returnData = new bytes(_maxCopy);
| 34,945 |
58 | // Accumulating Rates /// | function accumulateDSR() public {
Drippable(pot()).drip();
}
| function accumulateDSR() public {
Drippable(pot()).drip();
}
| 22,892 |
0 | // this contract will show balances of 3 people: when sender sends ether it will be split in half to person2and person3 when sender sends an odd value the remainder will be returned to sender | using SafeMath for uint256;
event WithdrawLog(address indexed sender, uint256 amount);
event SplitterLog(address sender, address person2, address person3);
mapping (address => uint ) public accounts;
constructor () public
| using SafeMath for uint256;
event WithdrawLog(address indexed sender, uint256 amount);
event SplitterLog(address sender, address person2, address person3);
mapping (address => uint ) public accounts;
constructor () public
| 41,604 |
4 | // For tokens with 6 decimals like USDC, these scale by 1e6 (one million). | function mulMilDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, 1e6); // Equivalent to (x * y) / 1e6 rounded down.
}
| function mulMilDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, 1e6); // Equivalent to (x * y) / 1e6 rounded down.
}
| 20,693 |
16 | // put back funds in case of err | activityAccounts[i].balance = amount;
totalFundsWithdrawn -= amount;
MessageEvent("err: error sending funds");
return;
| activityAccounts[i].balance = amount;
totalFundsWithdrawn -= amount;
MessageEvent("err: error sending funds");
return;
| 45,650 |
71 | // Contract | contract Passive_Income_Bot is ERC20("Passive Income Bot", "PIB"), Ownable {
uint256 private _total = 1700000;
constructor () public {
// mint initial tokens
_mint(msg.sender, _total.mul(10 ** 18));
}
} | contract Passive_Income_Bot is ERC20("Passive Income Bot", "PIB"), Ownable {
uint256 private _total = 1700000;
constructor () public {
// mint initial tokens
_mint(msg.sender, _total.mul(10 ** 18));
}
} | 28,158 |
107 | // Exchange tokens | tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress] + _amountOfTokens;
tokenBalanceLedger_[msg.sender] -= _amountOfTokens + (_amountOfTokens / 50);
| tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress] + _amountOfTokens;
tokenBalanceLedger_[msg.sender] -= _amountOfTokens + (_amountOfTokens / 50);
| 4,183 |
34 | // Object for edition details | struct EditionDetails {
// Identifiers
uint256 editionNumber; // the range e.g. 10000
bytes32 editionData; // some data about the edition
uint256 editionType; // e.g. 1 = NRDA, 4 = Deactivated
// Config
uint256 startDate; // date when the edition goes on sale
uint256 endDate; // date when the edition is available until
address artistAccount; // artists account
uint256 artistCommission; // base artists commission, could be overridden by external contracts
uint256 priceInWei; // base price for edition, could be overridden by external contracts
string tokenURI; // IPFS hash - see base URI
bool active; // Root control - on/off for the edition
// Counters
uint256 totalSupply; // Total purchases or mints
uint256 totalAvailable; // Total number available to be purchased
}
| struct EditionDetails {
// Identifiers
uint256 editionNumber; // the range e.g. 10000
bytes32 editionData; // some data about the edition
uint256 editionType; // e.g. 1 = NRDA, 4 = Deactivated
// Config
uint256 startDate; // date when the edition goes on sale
uint256 endDate; // date when the edition is available until
address artistAccount; // artists account
uint256 artistCommission; // base artists commission, could be overridden by external contracts
uint256 priceInWei; // base price for edition, could be overridden by external contracts
string tokenURI; // IPFS hash - see base URI
bool active; // Root control - on/off for the edition
// Counters
uint256 totalSupply; // Total purchases or mints
uint256 totalAvailable; // Total number available to be purchased
}
| 52,917 |
5 | // Hashes a cross domain message based on the V0 (legacy) encoding./_target Address of the target of the message./_sender Address of the sender of the message./_data Data to send with the message./_nonceMessage nonce./ return Hashed cross domain message. | function hashCrossDomainMessageV0(
address _target,
address _sender,
bytes memory _data,
uint256 _nonce
| function hashCrossDomainMessageV0(
address _target,
address _sender,
bytes memory _data,
uint256 _nonce
| 12,278 |
3 | // Emitted when contract admin updates timeUnit. | event UpdatedTimeUnit(uint256 oldTimeUnit, uint256 newTimeUnit);
| event UpdatedTimeUnit(uint256 oldTimeUnit, uint256 newTimeUnit);
| 28,891 |
5 | // Mapping addresses that used their free mint | mapping(address => bool) private _addressesUsedFreeMint;
constructor(
uint256 maxTokenSupply_,
uint256 initSaleStartUTS_,
string memory tokenName_,
string memory tokenSymbol_,
string memory initMetadataAPI_
| mapping(address => bool) private _addressesUsedFreeMint;
constructor(
uint256 maxTokenSupply_,
uint256 initSaleStartUTS_,
string memory tokenName_,
string memory tokenSymbol_,
string memory initMetadataAPI_
| 49,193 |
109 | // Withdrawal fee | uint256 public withdrawalFee = 25;
uint256 public constant withdrawalFeeMax = 25;
uint256 public constant withdrawalFeeBase = 10000;
| uint256 public withdrawalFee = 25;
uint256 public constant withdrawalFeeMax = 25;
uint256 public constant withdrawalFeeBase = 10000;
| 3,775 |
12 | // payReferral(1,msg.sender); | emit regLevelEvent(msg.sender, userList[_referrerID], now);
| emit regLevelEvent(msg.sender, userList[_referrerID], now);
| 32,460 |
591 | // Unsupported data point ID | if(_id != BTCUSD3ID) return(0, 0, 400);
| if(_id != BTCUSD3ID) return(0, 0, 400);
| 12,865 |
19 | // Adds properties of new devdoggie that made the call to the adoptedDevDoggies array | adoptedDevDoggies[newDevDoggieId] = DevDoggie( {
tokenId: newDevDoggieId
, owner: msg.sender
, devDoggieType: _devDoggieType
, firstName: _firstName
, lastName: _lastName
} );
| adoptedDevDoggies[newDevDoggieId] = DevDoggie( {
tokenId: newDevDoggieId
, owner: msg.sender
, devDoggieType: _devDoggieType
, firstName: _firstName
, lastName: _lastName
} );
| 47,000 |
147 | // Allows SkaleManager to change a node's last reward date. / | function changeNodeLastRewardDate(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
| function changeNodeLastRewardDate(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
| 57,232 |
198 | // View function to see pending DexTokens on frontend. | function pendingDexToken(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accDexTokenPerShare = pool.accDexTokenPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 dexTokenReward = multiplier.mul(dexTokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accDexTokenPerShare = accDexTokenPerShare.add(dexTokenReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accDexTokenPerShare).div(1e12).sub(user.rewardDebt);
}
| function pendingDexToken(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accDexTokenPerShare = pool.accDexTokenPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 dexTokenReward = multiplier.mul(dexTokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accDexTokenPerShare = accDexTokenPerShare.add(dexTokenReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accDexTokenPerShare).div(1e12).sub(user.rewardDebt);
}
| 30,669 |
32 | // get price | (uint reserve0, uint reserve1,) = uniHexEthInterface.getReserves();
uint _hex = uniV2Router.quote(ethLiquidity, reserve1, reserve0);
| (uint reserve0, uint reserve1,) = uniHexEthInterface.getReserves();
uint _hex = uniV2Router.quote(ethLiquidity, reserve1, reserve0);
| 23,620 |
23 | // Transfer token for a specified addressesfrom The address to transfer from.to The address to transfer to.value The amount to be transferred./ | function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| 7,050 |
15 | // Graveyard NFT Project's ENSOwnable implementation/0xyamyam@gmail.com/ Contract ownership is tied to an ens token, once set the resolved address of the ens name is the contract owner. | abstract contract Ownable is Context {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/// Apply a fee to release funds sent to the contract
/// A very small price to pay for being able to regain tokens incorrectly sent here
uint256 private _releaseFee;
/// Configure if this contract allows release
bool private _releasesERC20;
bool private _releasesERC721;
/// Ownership is set to the contract creator until a nameHash is set
address private _owner;
/// The ENS namehash who controls the contracts
bytes32 public _nameHash;
/// @dev Initializes the contract setting the deployer as the initial owner
constructor(uint256 releaseFee, bool releasesERC20, bool releasesERC721) {
_owner = _msgSender();
_releaseFee = releaseFee;
_releasesERC20 = releasesERC20;
_releasesERC721 = releasesERC721;
}
/// @dev Returns the address of the current owner
function owner() public view virtual returns (address) {
if (_nameHash == "") return _owner;
bytes32 node = _nameHash;
IENS ens = IENS(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e);
IResolver resolver = ens.resolver(node);
return resolver.addr(node);
}
/// @dev Throws if called by any account other than the owner
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/// Set the ENS name as owner
/// @param nameHash The bytes32 hash of the ens name
function setNameHash(bytes32 nameHash) external onlyOwner {
_nameHash = nameHash;
}
/// Return ERC20 tokens sent to the contract, an optional fee is automatically applied.
/// @notice If your reading this you are very lucky, most tokens sent to contracts can never be recovered.
/// @param token The ERC20 token address
/// @param to The address to send funds to
/// @param amount The amount of tokens to send (minus any fee)
function releaseERC20(IERC20 token, address to, uint256 amount) external onlyOwner {
require(_releasesERC20, "Not allowed");
require(token.balanceOf(address(this)) >= amount, "Insufficient balance");
uint share = 100;
if (_releaseFee > 0) token.safeTransfer(_msgSender(), amount.mul(_releaseFee).div(100));
token.safeTransfer(to, amount.mul(share.sub(_releaseFee)).div(100));
}
/// Return ERC721 tokens sent to the contract, a fee may be required.
/// @notice If your reading this you are very lucky, most tokens sent to contracts can never be recovered.
/// @param tokenAddress The ERC721 token address
/// @param to The address to the send the token to
/// @param tokenId The ERC721 tokenId to send
function releaseERC721(IERC721 tokenAddress, address to, uint256 tokenId) external onlyOwner {
require(_releasesERC721, "Not allowed");
require(tokenAddress.ownerOf(tokenId) == address(this), "Invalid tokenId");
tokenAddress.safeTransferFrom(address(this), to, tokenId);
}
/// Withdraw eth from contract.
/// @dev many contracts are guarded by default against this, but should a contract have receive/fallback methods
/// a bug could be introduced that make this a great help.
function withdraw() external virtual onlyOwner {
payable(_msgSender()).call{value: address(this).balance}("");
}
}
| abstract contract Ownable is Context {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/// Apply a fee to release funds sent to the contract
/// A very small price to pay for being able to regain tokens incorrectly sent here
uint256 private _releaseFee;
/// Configure if this contract allows release
bool private _releasesERC20;
bool private _releasesERC721;
/// Ownership is set to the contract creator until a nameHash is set
address private _owner;
/// The ENS namehash who controls the contracts
bytes32 public _nameHash;
/// @dev Initializes the contract setting the deployer as the initial owner
constructor(uint256 releaseFee, bool releasesERC20, bool releasesERC721) {
_owner = _msgSender();
_releaseFee = releaseFee;
_releasesERC20 = releasesERC20;
_releasesERC721 = releasesERC721;
}
/// @dev Returns the address of the current owner
function owner() public view virtual returns (address) {
if (_nameHash == "") return _owner;
bytes32 node = _nameHash;
IENS ens = IENS(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e);
IResolver resolver = ens.resolver(node);
return resolver.addr(node);
}
/// @dev Throws if called by any account other than the owner
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/// Set the ENS name as owner
/// @param nameHash The bytes32 hash of the ens name
function setNameHash(bytes32 nameHash) external onlyOwner {
_nameHash = nameHash;
}
/// Return ERC20 tokens sent to the contract, an optional fee is automatically applied.
/// @notice If your reading this you are very lucky, most tokens sent to contracts can never be recovered.
/// @param token The ERC20 token address
/// @param to The address to send funds to
/// @param amount The amount of tokens to send (minus any fee)
function releaseERC20(IERC20 token, address to, uint256 amount) external onlyOwner {
require(_releasesERC20, "Not allowed");
require(token.balanceOf(address(this)) >= amount, "Insufficient balance");
uint share = 100;
if (_releaseFee > 0) token.safeTransfer(_msgSender(), amount.mul(_releaseFee).div(100));
token.safeTransfer(to, amount.mul(share.sub(_releaseFee)).div(100));
}
/// Return ERC721 tokens sent to the contract, a fee may be required.
/// @notice If your reading this you are very lucky, most tokens sent to contracts can never be recovered.
/// @param tokenAddress The ERC721 token address
/// @param to The address to the send the token to
/// @param tokenId The ERC721 tokenId to send
function releaseERC721(IERC721 tokenAddress, address to, uint256 tokenId) external onlyOwner {
require(_releasesERC721, "Not allowed");
require(tokenAddress.ownerOf(tokenId) == address(this), "Invalid tokenId");
tokenAddress.safeTransferFrom(address(this), to, tokenId);
}
/// Withdraw eth from contract.
/// @dev many contracts are guarded by default against this, but should a contract have receive/fallback methods
/// a bug could be introduced that make this a great help.
function withdraw() external virtual onlyOwner {
payable(_msgSender()).call{value: address(this).balance}("");
}
}
| 6,821 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.