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 |
|---|---|---|---|---|
6 | // getter for CIC backers / return backers of CIC contract | function getContractBackers(string calldata cic) public view returns (
| function getContractBackers(string calldata cic) public view returns (
| 25,432 |
183 | // Sets {name} as "Wallex Token", {symbol} as "WLXT" and {decimals} with 18. Setup roles {DEFAULT_ADMIN_ROLE}, {MINTER_ROLE}, {WIPER_ROLE} and {REGISTRY_MANAGER_ROLE}. Mints `initialSupply` tokens and assigns them to the caller. / | constructor(
uint256 _initialSupply,
IUserRegistry _userRegistry,
address _minter,
address _wiper,
address _registryManager
) public ERC20("Wallex Token", "WLXT") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, _minter);
_setupRole(WIPER_ROLE, _wiper);
| constructor(
uint256 _initialSupply,
IUserRegistry _userRegistry,
address _minter,
address _wiper,
address _registryManager
) public ERC20("Wallex Token", "WLXT") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, _minter);
_setupRole(WIPER_ROLE, _wiper);
| 19,231 |
215 | // for network token liquidity, mint governance tokens to the caller | if (reserveToken == _networkToken) {
govTokenGovernance.mint(msg.sender, reserveAmount);
}
| if (reserveToken == _networkToken) {
govTokenGovernance.mint(msg.sender, reserveAmount);
}
| 14,105 |
94 | // exlcude from fees and max transaction amount | mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
| mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
| 2,750 |
10 | // Array of username | bytes32[] public userArr;
| bytes32[] public userArr;
| 28,437 |
47 | // Burn `value` WETH10 token from account (`from`) and withdraw matching ETH to account (`to`)./ Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`),/ unless allowance is set to `type(uint256).max`/ Emits {Transfer} event to reflect WETH10 token burn of `value` to zero address from account (`from`)./ Requirements:/ - `from` account must have at least `value` balance of WETH10 token./ - `from` account must have approved caller to spend at least `value` of WETH10 token, unless `from` and caller are the same account. | function withdrawFrom(address from, address payable to, uint256 value) external;
| function withdrawFrom(address from, address payable to, uint256 value) external;
| 24,004 |
7 | // Throws unless `msg.sender` is the current owner of both NFT/_dadId The Dad NFT Id/_mumId The Mum NFT Id | function breed(uint32 _dadId, uint32 _mumId) external returns (uint256){
//Require that msg.sender owns both NFT
require(_PandaOwner[_dadId] == msg.sender && _PandaOwner[_mumId] == msg.sender);
return _breed(msg.sender, _dadId, _mumId);
}
| function breed(uint32 _dadId, uint32 _mumId) external returns (uint256){
//Require that msg.sender owns both NFT
require(_PandaOwner[_dadId] == msg.sender && _PandaOwner[_mumId] == msg.sender);
return _breed(msg.sender, _dadId, _mumId);
}
| 27,304 |
57 | // Set paramaters for the reward distribution _rewardPerBlock The reward token amount per a block _decrementUnitPerBlock The decerement amount of the reward token per a block / | function _setParams(uint256 _rewardPerBlock, uint256 _decrementUnitPerBlock) internal {
emit SetRewardParams(_rewardPerBlock, _decrementUnitPerBlock);
rewardPerBlock = _rewardPerBlock;
decrementUnitPerBlock = _decrementUnitPerBlock;
}
| function _setParams(uint256 _rewardPerBlock, uint256 _decrementUnitPerBlock) internal {
emit SetRewardParams(_rewardPerBlock, _decrementUnitPerBlock);
rewardPerBlock = _rewardPerBlock;
decrementUnitPerBlock = _decrementUnitPerBlock;
}
| 25,658 |
28 | // Function to liquidate a non-healthy position collateral-wise- The caller (liquidator) buy collateral asset of the user getting liquidated, and receivesthe collateral asset nftAsset The address of the underlying NFT used as collateral nftTokenId The token ID of the underlying NFT used as collateral / | ) external override nonReentrant whenNotPaused returns (uint256) {
address poolLiquidator = _addressesProvider.getLendPoolLiquidator();
//solium-disable-next-line
(bool success, bytes memory result) = poolLiquidator.delegatecall(
abi.encodeWithSignature("liquidate(address,uint256,uint256)", nftAsset, nftTokenId, amount)
);
bytes memory resultData = _verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED);
uint256 extraAmount = abi.decode(resultData, (uint256));
return (extraAmount);
}
| ) external override nonReentrant whenNotPaused returns (uint256) {
address poolLiquidator = _addressesProvider.getLendPoolLiquidator();
//solium-disable-next-line
(bool success, bytes memory result) = poolLiquidator.delegatecall(
abi.encodeWithSignature("liquidate(address,uint256,uint256)", nftAsset, nftTokenId, amount)
);
bytes memory resultData = _verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED);
uint256 extraAmount = abi.decode(resultData, (uint256));
return (extraAmount);
}
| 64,352 |
45 | // Determine the total value of assets held by the vault and itsstrategies.return uint256 value Total value in USD (1e18) / | function totalValue() external view returns (uint256 value) {
value = _totalValue();
}
| function totalValue() external view returns (uint256 value) {
value = _totalValue();
}
| 22,535 |
2,220 | // 1112 | entry "whilemeal" : ENG_ADVERB
| entry "whilemeal" : ENG_ADVERB
| 21,948 |
88 | // Returns the transactions' counter. / | function transactions() public view returns(uint256 txs,
uint256 vokenIssuedTxs,
| function transactions() public view returns(uint256 txs,
uint256 vokenIssuedTxs,
| 46,764 |
93 | // once enabled, can never be turned off | function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
| function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
| 4,572 |
2 | // fired at end of buy or reload | event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
| event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
| 38,113 |
36 | // transfers an alien deposit back to the sender | function refundAlienDeposit(address _addr) public onlyWhitelistControl {
// Note: this implementation requires that alienDeposits has a primitive value type.
// With a complex type, this code would produce a dangling reference.
uint256 withdrawAmount = alienDeposits[_addr];
require(withdrawAmount > 0);
delete alienDeposits[_addr]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
emit Refund(_addr, withdrawAmount);
_addr.transfer(withdrawAmount); // throws on failure
}
| function refundAlienDeposit(address _addr) public onlyWhitelistControl {
// Note: this implementation requires that alienDeposits has a primitive value type.
// With a complex type, this code would produce a dangling reference.
uint256 withdrawAmount = alienDeposits[_addr];
require(withdrawAmount > 0);
delete alienDeposits[_addr]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
emit Refund(_addr, withdrawAmount);
_addr.transfer(withdrawAmount); // throws on failure
}
| 40,550 |
8 | // Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.- MUST return a limited value if receiver is subject to some mint limit.- MUST return 2256 - 1 if there is no limit on the maximum amount of shares that may be minted.- MUST NOT revert. / | function maxMint(address receiver) external view returns (uint256 maxShares);
| function maxMint(address receiver) external view returns (uint256 maxShares);
| 43,997 |
18 | // Moves `amount` tokens from `sender` to `recipient` using theallowance mechanism. `amount` is then deducted from the caller'sallowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. / | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| 22 |
132 | // Miniting Essentials functions as per OpenZeppelin standards/ | modifier canMint() {
require(!mintingFinished);
_;
}
| modifier canMint() {
require(!mintingFinished);
_;
}
| 29,884 |
9 | // Remove a role from an account | function _removeRole(bytes32 role, address account) internal {
roles[role][account] = false;
userRoles[account] = bytes32(0);
}
| function _removeRole(bytes32 role, address account) internal {
roles[role][account] = false;
userRoles[account] = bytes32(0);
}
| 21,452 |
2 | // Move remaining presale claims to public mints | paidMilks[SKIM_MILK_ID] += claimMilks[SKIM_MILK_ID];
paidMilks[ONE_PERCENT_MILK_ID] += claimMilks[ONE_PERCENT_MILK_ID];
paidMilks[TWO_PERCENT_MILK_ID] += claimMilks[TWO_PERCENT_MILK_ID];
paidMilks[WHOLE_MILK_ID] += claimMilks[WHOLE_MILK_ID];
paidMilks[MUTANT_MILK_ID] += claimMilks[MUTANT_MILK_ID];
maxPaidMints += maxClaimMints - claimMints;
maxClaimMints = claimMints;
claimMilks = [0, 0, 0, 0, 0];
| paidMilks[SKIM_MILK_ID] += claimMilks[SKIM_MILK_ID];
paidMilks[ONE_PERCENT_MILK_ID] += claimMilks[ONE_PERCENT_MILK_ID];
paidMilks[TWO_PERCENT_MILK_ID] += claimMilks[TWO_PERCENT_MILK_ID];
paidMilks[WHOLE_MILK_ID] += claimMilks[WHOLE_MILK_ID];
paidMilks[MUTANT_MILK_ID] += claimMilks[MUTANT_MILK_ID];
maxPaidMints += maxClaimMints - claimMints;
maxClaimMints = claimMints;
claimMilks = [0, 0, 0, 0, 0];
| 41,926 |
33 | // Administrative functions | {
bool canSwitchPhase
= (currentPhase == Phase.Created && _nextPhase == Phase.Running)
|| (currentPhase == Phase.Running && _nextPhase == Phase.Paused)
// switch to migration phase only if crowdsale manager is set
|| ((currentPhase == Phase.Running || currentPhase == Phase.Paused)
&& _nextPhase == Phase.Migrating
&& crowdsaleManager != 0x0)
|| (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
// switch to migrated only if everyting is migrated
|| (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated
&& totalSupply == 0);
if(!canSwitchPhase) revert();
currentPhase = _nextPhase;
emit LogPhaseSwitch(_nextPhase);
}
| {
bool canSwitchPhase
= (currentPhase == Phase.Created && _nextPhase == Phase.Running)
|| (currentPhase == Phase.Running && _nextPhase == Phase.Paused)
// switch to migration phase only if crowdsale manager is set
|| ((currentPhase == Phase.Running || currentPhase == Phase.Paused)
&& _nextPhase == Phase.Migrating
&& crowdsaleManager != 0x0)
|| (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
// switch to migrated only if everyting is migrated
|| (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated
&& totalSupply == 0);
if(!canSwitchPhase) revert();
currentPhase = _nextPhase;
emit LogPhaseSwitch(_nextPhase);
}
| 4,458 |
243 | // calc 1 idleToken value in gov shares for user `_from` | sharePerTokenFrom = govTokenIdx.sub(usersGovTokensIndexes[govToken][_from]);
| sharePerTokenFrom = govTokenIdx.sub(usersGovTokensIndexes[govToken][_from]);
| 35,216 |
3 | // ========== EVENTS ========== // ========== STATE VARIABLES ========== // ========== CONSTRUCTOR ========== / | ) {
require(
_rewardsDistributor != address(0) &&
_varenToken != address(0) &&
_stakingToken != address(0),
"address(0)"
);
require(_rewardsDuration > 0, "rewardsDuration=0");
rewardsDistributor = _rewardsDistributor;
rewardTokens[0] = IERC20(_varenToken);
rewardTokens[1] = IERC20(_extraRewardToken);
stakingToken = IERC20(_stakingToken);
rewardsDuration = _rewardsDuration;
owner = _owner;
}
| ) {
require(
_rewardsDistributor != address(0) &&
_varenToken != address(0) &&
_stakingToken != address(0),
"address(0)"
);
require(_rewardsDuration > 0, "rewardsDuration=0");
rewardsDistributor = _rewardsDistributor;
rewardTokens[0] = IERC20(_varenToken);
rewardTokens[1] = IERC20(_extraRewardToken);
stakingToken = IERC20(_stakingToken);
rewardsDuration = _rewardsDuration;
owner = _owner;
}
| 31,106 |
155 | // Non-view function |
function setAssetPricer(address _asset, address _pricer) external;
function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external;
function setDisputePeriod(address _pricer, uint256 _disputePeriod) external;
function setExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
|
function setAssetPricer(address _asset, address _pricer) external;
function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external;
function setDisputePeriod(address _pricer, uint256 _disputePeriod) external;
function setExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
| 34,458 |
12 | // Triggered when the Redemption Fee Minimum is updated_oldRedemptionFeeMinimumOld redemption fee minimum _newRedemptionFeeMinimumNew redemption fee minimum / | event RedemptionFeeMinimumUpdated(
| event RedemptionFeeMinimumUpdated(
| 29,758 |
5 | // Execute fill | _buyERC721(order, signature, params.fillTo, params.revertIfIncomplete, params.amount);
| _buyERC721(order, signature, params.fillTo, params.revertIfIncomplete, params.amount);
| 21,584 |
2 | // If the user doesn't exist, add a new user | users[id] = UserInfo(id, reputation_score, 0, 0);
| users[id] = UserInfo(id, reputation_score, 0, 0);
| 2,785 |
0 | // loi.Add_Authority(authority); | return address(loi);
| return address(loi);
| 19,129 |
8 | // Fallback function. It just accepts incoming TRX/ | function () payable external {}
/*
function addTenAccounts(address[10] _newAccountAddress) public returns (bool)
{
uint256 i;
for(i=0; i<10;i++)
{
testWalletAddress[i] = _newAccountAddress[i];
}
return true;
}
| function () payable external {}
/*
function addTenAccounts(address[10] _newAccountAddress) public returns (bool)
{
uint256 i;
for(i=0; i<10;i++)
{
testWalletAddress[i] = _newAccountAddress[i];
}
return true;
}
| 446 |
8 | // assign reference | Voter storage sender = voters[msg.sender];
require(!sender.voted, "You already voted");
requre(to != msg.sender, "Self-delegation is disallowed")
| Voter storage sender = voters[msg.sender];
require(!sender.voted, "You already voted");
requre(to != msg.sender, "Self-delegation is disallowed")
| 12,557 |
21 | // function WETH() external pure returns (address); | function factory() external pure returns (address);
function addLiquidityETH(
address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
external payable returns (uint amountToken, uint amountETH, uint liquidity);
| function factory() external pure returns (address);
function addLiquidityETH(
address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline)
external payable returns (uint amountToken, uint amountETH, uint liquidity);
| 28,302 |
159 | // src/interfaces/IPot.sol/ pragma solidity ^0.5.0; / | interface IPot {
function rho () external returns (uint256);
function drip () external returns (uint256);
function chi () external view returns (uint256);
}
| interface IPot {
function rho () external returns (uint256);
function drip () external returns (uint256);
function chi () external view returns (uint256);
}
| 26,853 |
173 | // assumes that loan, collateral, and interest token are the same | borrowAmount = depositAmount
.mul(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION)
.div(_adjustValue(
interestRate,
2419200, // 28 day duration for margin trades
initialMargin))
.div(initialMargin);
| borrowAmount = depositAmount
.mul(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION)
.div(_adjustValue(
interestRate,
2419200, // 28 day duration for margin trades
initialMargin))
.div(initialMargin);
| 78,419 |
9 | // Check if the balance of the sender's account is larger than the amount being donated | require(msg.sender.balance >= amount, "Insufficient balance in sender's account");
| require(msg.sender.balance >= amount, "Insufficient balance in sender's account");
| 13,396 |
27 | // The reference to the store. | ERC20Store immutable public erc20Store;
address immutable public implOwner;
| ERC20Store immutable public erc20Store;
address immutable public implOwner;
| 53,725 |
8 | // Define what library the UA points too | function setSendVersion(uint16 _newVersion) external override {
sendVersion = _newVersion;
}
| function setSendVersion(uint16 _newVersion) external override {
sendVersion = _newVersion;
}
| 44,959 |
4 | // sanity checks the caller.If the caller is not admin, the transaction is reverted. keeps the security of the platform and prevents bad actorsfrom executing sensitive functions / state changes. / | modifier onlyAdmin() {
require(_msgSender() == admin, "Error: caller not admin");
_;
}
| modifier onlyAdmin() {
require(_msgSender() == admin, "Error: caller not admin");
_;
}
| 75,437 |
6 | // The interface fot the contract that calculatesthe options prices (the premiums) that are adjustedthrough balancing the `ImpliedVolRate` parameter. / | interface IPriceCalculator {
/**
* @param period The option period
* @param amount The option size
* @param strike The option strike
**/
function calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) external view returns (uint256 settlementFee, uint256 premium);
}
| interface IPriceCalculator {
/**
* @param period The option period
* @param amount The option size
* @param strike The option strike
**/
function calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) external view returns (uint256 settlementFee, uint256 premium);
}
| 7,158 |
9 | // See {ERC721Pausable} and {Pausable-_pause}. Requirements: - the caller must have the `PAUSER_ROLE`. / | function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "TREESToken: must have pauser role to pause.");
_pause();
}
| function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "TREESToken: must have pauser role to pause.");
_pause();
}
| 18,522 |
11 | // solhint-disable-previous-line no-empty-blocks |
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
|
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
| 4,830 |
31 | // Standard ERC23 token, backward compatible with ERC20 standards.Based on code by open-zeppelin: https:github.com/OpenZeppelin/zeppelin-solidity.git | contract ERC23StandardToken is ERC23BasicToken {
mapping (address => mapping (address => uint256)) allowed;
event Approval (address indexed owner, address indexed spender, uint256 value);
function transferFrom(address _from, address _to, uint256 _value) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
| contract ERC23StandardToken is ERC23BasicToken {
mapping (address => mapping (address => uint256)) allowed;
event Approval (address indexed owner, address indexed spender, uint256 value);
function transferFrom(address _from, address _to, uint256 _value) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
| 32,994 |
30 | // check treasury balance | assertEq(currency.balanceOf(TREASURY), prevTreasuryBalance + amount);
(, , uint256 newTreasuryWithdrawn) = registry.treasuryRecord();
assertEq(newTreasuryWithdrawn, accumulatedTreasury);
| assertEq(currency.balanceOf(TREASURY), prevTreasuryBalance + amount);
(, , uint256 newTreasuryWithdrawn) = registry.treasuryRecord();
assertEq(newTreasuryWithdrawn, accumulatedTreasury);
| 19,517 |
45 | // knights are only entering the game completely, when they are teleported to the scene id the character id/ | function teleportKnight(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false);
teleported[id] = true;
Character storage knight = characters[id];
require(knight.characterType >= numDragonTypes); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[knight.characterType]++;
NewTeleport(id);
}
| function teleportKnight(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false);
teleported[id] = true;
Character storage knight = characters[id];
require(knight.characterType >= numDragonTypes); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[knight.characterType]++;
NewTeleport(id);
}
| 49,300 |
144 | // Implementation of the BEP20 token. This implements a BEP20 token named daisy. On deployment it mints initialSupply to theowner's account address. Later for every transaction on the contract a 4% of transactionamount is calculated and is distributed/burned from owner's address as per the decidedfees structure. / | contract Daisy is Context, ERC20, Ownable {
using SafeMath for uint256;
using Address for address;
uint16 public _burnFee;
uint16 public _rewardFee;
uint16 public _blackholeMonitor;
uint16 public _reserveFee;
uint16 public _totalFee;
address public _blackholeWallet; // Blackhole wallet = reserver wallet with 0%
address public _reserveWallet; // Holds reserve's wallet address
address[] public _stakeholders; // Holds all stakeholders addresses
// Events
event StakeHolderAdded(address stakeholder);
event StakeHolderRemoved(address stakeholder);
event TransactionFeeDistributed(uint256 totalFeesDistributed);
event BlackholeWalletChanged(address fromAddress, address toAddress);
event ReserveWalletChanged(address fromAddress, address toAddress);
event RewardDistributedToAccount(address toAddress, uint256 totalReward, uint256 amount);
event Debug(string str, address addr, uint256 num);
/**
* @notice constructor
*
* Mints 1,000,000,000,000 tokens and sends to deployer's address
* Sets fees percents
* Sets wallet address for dev and reserve
*
* Requirements -
* - blackhole and reserveWallet cannot be 0 address
*/
constructor(
address blackholeWallet,
address reserveWallet
)
ERC20("Daisy", "$wick")
{
_mint(_msgSender(), 1000000000000E18); // Mint 1,000,000,000,000 tokens
_rewardFee = 100; // 1 percent
_burnFee = 100; // 1 percent
_blackholeMonitor = 0; // 0 percent
_reserveFee = 200; // 1 percent
_totalFee = _rewardFee + _burnFee + _blackholeMonitor + _reserveFee;
require(blackholeWallet != address(0), "Blackhole wallet address cannot be 0 address");
require(reserveWallet != address(0), "Reserve wallet address cannot be 0 address");
_blackholeWallet = blackholeWallet;
_reserveWallet = reserveWallet;
}
/**
* @notice Allow owner of contract to mint new tokens to given account
* of given amount.
*
* Requirements -
* - account address cannot be 0 address
* - amount cannot be 0
*/
function mint(address account, uint256 amount)
public
onlyOwner
{
_mint(account, amount);
}
/**
* @notice Burn given amount of tokens from senders account
* This reduces the total supply of tokens
*
* Requirements -
* - amount cannot be 0
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @notice Returns the number of tokens in circulation
*/
function circulationSupply() public view returns (uint256) {
return totalSupply().sub(balanceOf(owner()));
}
/**
* @notice returns the total supply staked by the _stakeholders combined
*/
function stakedSupply() public view returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < _stakeholders.length; i++) {
total = total.add(balanceOf(_stakeholders[i]));
}
return total;
}
/**
* @notice Transfers the amount to recipient.
* - Add or checks stakeholders array for recipient address
* - calls for fees distribution
*
* Requirements:
*
* - recipient cannot be the zero address.
* - the caller must have a balance of at least amount.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
require(balanceOf(_msgSender()) >= amount, "Not enough token balance.");
if (_checkWithoutFee()) {
_transfer(_msgSender(), recipient, amount);
} else {
// check if funds available in supply for fees distribution
uint256 fundsRequired = amount.mul(uint256(_totalFee)).div(10000);
require(balanceOf(owner()) >= fundsRequired, "Not enough supply available.");
// Run fees distribution functionality
_feesDistribution(amount);
// transfer all amount to recipient
_transfer(_msgSender(), recipient, amount);
}
// Add recipient to stakeholders if not exist
// Admin will not get added
_addStakeholder(recipient);
return true;
}
/**
* @notice Transfers the amount of token to recipient from sender's account.
* - Add or checks stakeholders array for recipient address
* - calls for fees distribution
* - Reduces the allowance of caller
*
* Requirements:
*
* - sender cannot be the zero address.
* - recipient cannot be the zero address.
* - the sender must have a balance of at least amount.
*/
function transferFrom(address sender, address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
require(balanceOf(sender) >= amount, "Not enough token balance.");
require(allowance(sender, _msgSender()) >= amount, "ERC20: transfer amount exceeds allowance");
if (_checkWithoutFee()) {
_transfer(sender, recipient, amount);
} else {
// check if funds available in supply for fees distribution
uint256 fundsRequired = amount.mul(uint256(_totalFee)).div(10000);
require(balanceOf(owner()) >= fundsRequired, "Not enough supply available.");
// Run fees distribution functionality
_feesDistribution(amount);
// transfer all amount to recipient
_transfer(sender, recipient, amount);
}
// Reduce the allowance of caller
_approve(
sender,
_msgSender(),
allowance(sender, _msgSender()).sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
// Add recipient to stakeholders if not exist
// Admin will not get added
_addStakeholder(recipient);
return true;
}
/**
* @notice Returns whether _address is stakeholder or not
* also returns the position of the address in _stakeholders array
*
* Requirements -
* - _address cannot be zero
*/
function isStakeholder(address _address)
public
view
returns(bool, uint256)
{
for (uint256 s = 0; s < _stakeholders.length; s += 1){
if (_address == _stakeholders[s]) return (true, s);
}
return (false, 0);
}
/**
* @notice Distributes all types of fees during the transaction
* The tokens are distributed from owners account
* Calculates the fee amounts on amount of transaction
*
* Reward fee = 1%
* Burn fee = 1%
* Blackhole = 0%
* Reserve Fee = 1%
*
* Requirements -
* - Owners account should have 5% of amount tokens in his wallet to payout fees
* - amount cannot be 0
*
* @param amount (uint256) - cannot be 0 amount
*/
function _feesDistribution(uint256 amount) internal {
uint256 tokensInCirculation = circulationSupply();
if (tokensInCirculation > 0) {
uint256 rewardFeeAmount = amount.mul(uint256(_rewardFee)).div(10000);
uint256 burnFeeAmount = amount.mul(uint256(_burnFee)).div(10000);
uint256 blackholeMonitorAmount = amount.mul(uint256(_blackholeMonitor)).div(10000);
uint256 reserveFeeAmount = amount.mul(uint256(_reserveFee)).div(10000);
// Distribute fees
_transfer(owner(), _blackholeWallet, blackholeMonitorAmount);
_transfer(owner(), _reserveWallet, reserveFeeAmount); // 1% of transaction amount sent to reserve wallet
// burn 1% of token amount completely
_burn(owner(), burnFeeAmount);
// Distribute 2% of transaction amount as fees between all token holders
_distributeFeesToTokenHolders(rewardFeeAmount, tokensInCirculation);
emit TransactionFeeDistributed(rewardFeeAmount + burnFeeAmount + blackholeMonitorAmount + reserveFeeAmount);
}
}
/**
* @notice Distribute fees of current transaction to all stake holders as per
* their holding share.
*
* rewardFeeAmount is total amount of fee of transaction to be distributed.
* tokensInCirculation is the total amount of token open for sale/exchange in
* market, but which are not hold by owner.
*
* Requirements -
* - tokensInCirculation cannot be 0
*/
function _distributeFeesToTokenHolders(uint256 rewardFeeAmount, uint256 tokensInCirculation) internal {
require(tokensInCirculation > 0, "No tokens in circulation");
uint256 len = _stakeholders.length;
for (uint256 index = 0; index < len; index++) {
uint256 rewardAmountForAccount = _rewardAmountForAccount(_stakeholders[index], tokensInCirculation, rewardFeeAmount);
if (rewardAmountForAccount > 0) {
_transfer(owner(), _stakeholders[index], rewardAmountForAccount);
emit RewardDistributedToAccount(_stakeholders[index], rewardFeeAmount, rewardAmountForAccount);
}
}
}
/**
* @notice Calculates the reward amount for given account
* This returns 0 if account is not a stakeholder
*
* @param account - user account address
* @param tokensInCirculation - Total number of tokens in circulation
* @param rewardFeeAmount - reward token amount for given transaction
*/
function _rewardAmountForAccount(address account, uint256 tokensInCirculation, uint256 rewardFeeAmount)
internal
view
returns(uint256)
{
(bool _isStakeholder, ) = isStakeholder(account);
if (!_isStakeholder) return 0;
uint256 holderBalance = balanceOf(account);
uint256 holdersShare = (rewardFeeAmount.mul(holderBalance)).div(tokensInCirculation);
return holdersShare;
}
/**
* @notice This determines when should fees be paid for transactions.
*/
function _checkWithoutFee() internal view returns (bool) {
if (_msgSender() == owner()) return true;
return false;
}
/**
* @notice Adds _stakeholder to _stakeholders array.
* This are individual accounts which holds the Daisy tokens
*
* - _stakeholder cannot be 0 address
*/
function _addStakeholder(address _stakeholder)
internal
{
require(_stakeholder != address(0), "Address cannot be 0 address");
(bool _isStakeholder, ) = isStakeholder(_stakeholder);
if (!_isStakeholder && (_stakeholder != owner()) && !_stakeholder.isContract()) {
_stakeholders.push(_stakeholder);
emit StakeHolderAdded(_stakeholder);
}
}
/**
* @notice A method to remove a _stakeholder from _stakeholders array.
* _stakeholder cannot be 0 address
*/
function removeStakeholder(address _stakeholder)
public
onlyOwner
{
require(_stakeholder != address(0), "Address cannot be 0 address");
(bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder);
if (_isStakeholder) {
_stakeholders[s] = _stakeholders[_stakeholders.length - 1];
_stakeholders.pop();
emit StakeHolderRemoved(_stakeholder);
}
}
/**
* @notice Updates Blackhole with given _account
* _account cannot be a contract or 0 address
*/
function updateBlackholeWallet(address _account)
public
onlyOwner
{
require(_account != address(0), "Account address is 0 address.");
require(!_account.isContract(), "Account address cannot be contract address");
_blackholeWallet = _account;
emit BlackholeWalletChanged(_account, _blackholeWallet);
}
/**
* @notice Updates _reserveWallet with given _account
* _account cannot be a contract or 0 address
*/
function updateReserveWallet(address _account)
public
onlyOwner
{
require(_account != address(0), "Account address is 0 address.");
require(!_account.isContract(), "Account address cannot be contract address");
_reserveWallet = _account;
emit ReserveWalletChanged(_account, _reserveWallet);
}
} | contract Daisy is Context, ERC20, Ownable {
using SafeMath for uint256;
using Address for address;
uint16 public _burnFee;
uint16 public _rewardFee;
uint16 public _blackholeMonitor;
uint16 public _reserveFee;
uint16 public _totalFee;
address public _blackholeWallet; // Blackhole wallet = reserver wallet with 0%
address public _reserveWallet; // Holds reserve's wallet address
address[] public _stakeholders; // Holds all stakeholders addresses
// Events
event StakeHolderAdded(address stakeholder);
event StakeHolderRemoved(address stakeholder);
event TransactionFeeDistributed(uint256 totalFeesDistributed);
event BlackholeWalletChanged(address fromAddress, address toAddress);
event ReserveWalletChanged(address fromAddress, address toAddress);
event RewardDistributedToAccount(address toAddress, uint256 totalReward, uint256 amount);
event Debug(string str, address addr, uint256 num);
/**
* @notice constructor
*
* Mints 1,000,000,000,000 tokens and sends to deployer's address
* Sets fees percents
* Sets wallet address for dev and reserve
*
* Requirements -
* - blackhole and reserveWallet cannot be 0 address
*/
constructor(
address blackholeWallet,
address reserveWallet
)
ERC20("Daisy", "$wick")
{
_mint(_msgSender(), 1000000000000E18); // Mint 1,000,000,000,000 tokens
_rewardFee = 100; // 1 percent
_burnFee = 100; // 1 percent
_blackholeMonitor = 0; // 0 percent
_reserveFee = 200; // 1 percent
_totalFee = _rewardFee + _burnFee + _blackholeMonitor + _reserveFee;
require(blackholeWallet != address(0), "Blackhole wallet address cannot be 0 address");
require(reserveWallet != address(0), "Reserve wallet address cannot be 0 address");
_blackholeWallet = blackholeWallet;
_reserveWallet = reserveWallet;
}
/**
* @notice Allow owner of contract to mint new tokens to given account
* of given amount.
*
* Requirements -
* - account address cannot be 0 address
* - amount cannot be 0
*/
function mint(address account, uint256 amount)
public
onlyOwner
{
_mint(account, amount);
}
/**
* @notice Burn given amount of tokens from senders account
* This reduces the total supply of tokens
*
* Requirements -
* - amount cannot be 0
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @notice Returns the number of tokens in circulation
*/
function circulationSupply() public view returns (uint256) {
return totalSupply().sub(balanceOf(owner()));
}
/**
* @notice returns the total supply staked by the _stakeholders combined
*/
function stakedSupply() public view returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < _stakeholders.length; i++) {
total = total.add(balanceOf(_stakeholders[i]));
}
return total;
}
/**
* @notice Transfers the amount to recipient.
* - Add or checks stakeholders array for recipient address
* - calls for fees distribution
*
* Requirements:
*
* - recipient cannot be the zero address.
* - the caller must have a balance of at least amount.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
require(balanceOf(_msgSender()) >= amount, "Not enough token balance.");
if (_checkWithoutFee()) {
_transfer(_msgSender(), recipient, amount);
} else {
// check if funds available in supply for fees distribution
uint256 fundsRequired = amount.mul(uint256(_totalFee)).div(10000);
require(balanceOf(owner()) >= fundsRequired, "Not enough supply available.");
// Run fees distribution functionality
_feesDistribution(amount);
// transfer all amount to recipient
_transfer(_msgSender(), recipient, amount);
}
// Add recipient to stakeholders if not exist
// Admin will not get added
_addStakeholder(recipient);
return true;
}
/**
* @notice Transfers the amount of token to recipient from sender's account.
* - Add or checks stakeholders array for recipient address
* - calls for fees distribution
* - Reduces the allowance of caller
*
* Requirements:
*
* - sender cannot be the zero address.
* - recipient cannot be the zero address.
* - the sender must have a balance of at least amount.
*/
function transferFrom(address sender, address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
require(balanceOf(sender) >= amount, "Not enough token balance.");
require(allowance(sender, _msgSender()) >= amount, "ERC20: transfer amount exceeds allowance");
if (_checkWithoutFee()) {
_transfer(sender, recipient, amount);
} else {
// check if funds available in supply for fees distribution
uint256 fundsRequired = amount.mul(uint256(_totalFee)).div(10000);
require(balanceOf(owner()) >= fundsRequired, "Not enough supply available.");
// Run fees distribution functionality
_feesDistribution(amount);
// transfer all amount to recipient
_transfer(sender, recipient, amount);
}
// Reduce the allowance of caller
_approve(
sender,
_msgSender(),
allowance(sender, _msgSender()).sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
// Add recipient to stakeholders if not exist
// Admin will not get added
_addStakeholder(recipient);
return true;
}
/**
* @notice Returns whether _address is stakeholder or not
* also returns the position of the address in _stakeholders array
*
* Requirements -
* - _address cannot be zero
*/
function isStakeholder(address _address)
public
view
returns(bool, uint256)
{
for (uint256 s = 0; s < _stakeholders.length; s += 1){
if (_address == _stakeholders[s]) return (true, s);
}
return (false, 0);
}
/**
* @notice Distributes all types of fees during the transaction
* The tokens are distributed from owners account
* Calculates the fee amounts on amount of transaction
*
* Reward fee = 1%
* Burn fee = 1%
* Blackhole = 0%
* Reserve Fee = 1%
*
* Requirements -
* - Owners account should have 5% of amount tokens in his wallet to payout fees
* - amount cannot be 0
*
* @param amount (uint256) - cannot be 0 amount
*/
function _feesDistribution(uint256 amount) internal {
uint256 tokensInCirculation = circulationSupply();
if (tokensInCirculation > 0) {
uint256 rewardFeeAmount = amount.mul(uint256(_rewardFee)).div(10000);
uint256 burnFeeAmount = amount.mul(uint256(_burnFee)).div(10000);
uint256 blackholeMonitorAmount = amount.mul(uint256(_blackholeMonitor)).div(10000);
uint256 reserveFeeAmount = amount.mul(uint256(_reserveFee)).div(10000);
// Distribute fees
_transfer(owner(), _blackholeWallet, blackholeMonitorAmount);
_transfer(owner(), _reserveWallet, reserveFeeAmount); // 1% of transaction amount sent to reserve wallet
// burn 1% of token amount completely
_burn(owner(), burnFeeAmount);
// Distribute 2% of transaction amount as fees between all token holders
_distributeFeesToTokenHolders(rewardFeeAmount, tokensInCirculation);
emit TransactionFeeDistributed(rewardFeeAmount + burnFeeAmount + blackholeMonitorAmount + reserveFeeAmount);
}
}
/**
* @notice Distribute fees of current transaction to all stake holders as per
* their holding share.
*
* rewardFeeAmount is total amount of fee of transaction to be distributed.
* tokensInCirculation is the total amount of token open for sale/exchange in
* market, but which are not hold by owner.
*
* Requirements -
* - tokensInCirculation cannot be 0
*/
function _distributeFeesToTokenHolders(uint256 rewardFeeAmount, uint256 tokensInCirculation) internal {
require(tokensInCirculation > 0, "No tokens in circulation");
uint256 len = _stakeholders.length;
for (uint256 index = 0; index < len; index++) {
uint256 rewardAmountForAccount = _rewardAmountForAccount(_stakeholders[index], tokensInCirculation, rewardFeeAmount);
if (rewardAmountForAccount > 0) {
_transfer(owner(), _stakeholders[index], rewardAmountForAccount);
emit RewardDistributedToAccount(_stakeholders[index], rewardFeeAmount, rewardAmountForAccount);
}
}
}
/**
* @notice Calculates the reward amount for given account
* This returns 0 if account is not a stakeholder
*
* @param account - user account address
* @param tokensInCirculation - Total number of tokens in circulation
* @param rewardFeeAmount - reward token amount for given transaction
*/
function _rewardAmountForAccount(address account, uint256 tokensInCirculation, uint256 rewardFeeAmount)
internal
view
returns(uint256)
{
(bool _isStakeholder, ) = isStakeholder(account);
if (!_isStakeholder) return 0;
uint256 holderBalance = balanceOf(account);
uint256 holdersShare = (rewardFeeAmount.mul(holderBalance)).div(tokensInCirculation);
return holdersShare;
}
/**
* @notice This determines when should fees be paid for transactions.
*/
function _checkWithoutFee() internal view returns (bool) {
if (_msgSender() == owner()) return true;
return false;
}
/**
* @notice Adds _stakeholder to _stakeholders array.
* This are individual accounts which holds the Daisy tokens
*
* - _stakeholder cannot be 0 address
*/
function _addStakeholder(address _stakeholder)
internal
{
require(_stakeholder != address(0), "Address cannot be 0 address");
(bool _isStakeholder, ) = isStakeholder(_stakeholder);
if (!_isStakeholder && (_stakeholder != owner()) && !_stakeholder.isContract()) {
_stakeholders.push(_stakeholder);
emit StakeHolderAdded(_stakeholder);
}
}
/**
* @notice A method to remove a _stakeholder from _stakeholders array.
* _stakeholder cannot be 0 address
*/
function removeStakeholder(address _stakeholder)
public
onlyOwner
{
require(_stakeholder != address(0), "Address cannot be 0 address");
(bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder);
if (_isStakeholder) {
_stakeholders[s] = _stakeholders[_stakeholders.length - 1];
_stakeholders.pop();
emit StakeHolderRemoved(_stakeholder);
}
}
/**
* @notice Updates Blackhole with given _account
* _account cannot be a contract or 0 address
*/
function updateBlackholeWallet(address _account)
public
onlyOwner
{
require(_account != address(0), "Account address is 0 address.");
require(!_account.isContract(), "Account address cannot be contract address");
_blackholeWallet = _account;
emit BlackholeWalletChanged(_account, _blackholeWallet);
}
/**
* @notice Updates _reserveWallet with given _account
* _account cannot be a contract or 0 address
*/
function updateReserveWallet(address _account)
public
onlyOwner
{
require(_account != address(0), "Account address is 0 address.");
require(!_account.isContract(), "Account address cannot be contract address");
_reserveWallet = _account;
emit ReserveWalletChanged(_account, _reserveWallet);
}
} | 5,629 |
228 | // Function to change the maximum number of free mints per user | function setMaxFreeMintPerUser(uint256 newMaxFreeMintPerUser) external onlyOwner {
maxFreeMintPerUser = newMaxFreeMintPerUser;
}
| function setMaxFreeMintPerUser(uint256 newMaxFreeMintPerUser) external onlyOwner {
maxFreeMintPerUser = newMaxFreeMintPerUser;
}
| 41,383 |
49 | // Returns the amount of tokens approved by the owner that can be transferred to the spender's account. / | function allowance(address tokenHolder, address spender) external view notPaused returns (uint256 tokens) {
uint256 _transferred = transferred[tokenHolder][spender]; /// Already transferred tokens by `spender`.
return allowances[tokenHolder][spender].sub(_transferred); /// Remained tokens to transfer by `spender`.
}
| function allowance(address tokenHolder, address spender) external view notPaused returns (uint256 tokens) {
uint256 _transferred = transferred[tokenHolder][spender]; /// Already transferred tokens by `spender`.
return allowances[tokenHolder][spender].sub(_transferred); /// Remained tokens to transfer by `spender`.
}
| 74,869 |
87 | // send leftover BNB to the marketing wallet so it doesn't get stuck on the contract. | if(address(this).balance > 1e17){
(success,) = address(marketingAddress).call{value: address(this).balance}("");
| if(address(this).balance > 1e17){
(success,) = address(marketingAddress).call{value: address(this).balance}("");
| 9,950 |
19 | // special case for equal ratios | if (_fromReserveRatio == _toReserveRatio)
return _toReserveBalance.mul(_amount) / _fromReserveBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _fromReserveBalance.add(_amount);
(result, precision) = power(baseN, _fromReserveBalance, _fromReserveRatio, _toReserveRatio);
uint256 temp1 = _toReserveBalance.mul(result);
uint256 temp2 = _toReserveBalance << precision;
return (temp1 - temp2) / result;
| if (_fromReserveRatio == _toReserveRatio)
return _toReserveBalance.mul(_amount) / _fromReserveBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _fromReserveBalance.add(_amount);
(result, precision) = power(baseN, _fromReserveBalance, _fromReserveRatio, _toReserveRatio);
uint256 temp1 = _toReserveBalance.mul(result);
uint256 temp2 = _toReserveBalance << precision;
return (temp1 - temp2) / result;
| 22,302 |
136 | // Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.The call is not executed if the target address is not a contract.from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the callreturn 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.onERC721Received.selector;
} catch (bytes memory reason) {
| 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.onERC721Received.selector;
} catch (bytes memory reason) {
| 21,736 |
400 | // Configuration parameters of a yield token. | struct YieldTokenConfig {
// The adapter used by the system to interop with the token.
address adapter;
// The maximum percent loss in expected value that can occur before certain actions are disabled measured in
// units of basis points.
uint256 maximumLoss;
// The maximum value that can be held by the system before certain actions are disabled measured in the
// underlying token.
uint256 maximumExpectedValue;
// The number of blocks that credit will be distributed over to depositors.
uint256 creditUnlockBlocks;
}
| struct YieldTokenConfig {
// The adapter used by the system to interop with the token.
address adapter;
// The maximum percent loss in expected value that can occur before certain actions are disabled measured in
// units of basis points.
uint256 maximumLoss;
// The maximum value that can be held by the system before certain actions are disabled measured in the
// underlying token.
uint256 maximumExpectedValue;
// The number of blocks that credit will be distributed over to depositors.
uint256 creditUnlockBlocks;
}
| 44,354 |
673 | // kyber network reserve compatible function | function trade(
IERC20 srcToken,
uint256 srcAmount,
IERC20 destToken,
address payable destAddress,
uint256 conversionRate,
bool validate
| function trade(
IERC20 srcToken,
uint256 srcAmount,
IERC20 destToken,
address payable destAddress,
uint256 conversionRate,
bool validate
| 16,237 |
148 | // Standard Uniswap V2 waygiven an output amount of an asset and pair reserves, returns a required input amount of the other asset / |
function getAmountIn(
uint amountOut,
uint reserveIn,
uint reserveOut
|
function getAmountIn(
uint amountOut,
uint reserveIn,
uint reserveOut
| 6,733 |
22 | // Enumerate NFTs assigned to an owner/Throws if `_index` >= `balanceOf(_owner)` or if/`_owner` is the zero address, representing invalid NFTs./_owner An address where we are interested in NFTs owned by them/_index A counter less than `balanceOf(_owner)`/ return The token identifier for the `_index`th NFT assigned to `_owner`,/ (sort order not specified) | function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
| function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
| 248 |
35 | // Allows the casino to withdraw tokens which do not belong to any stakeholder.This is the case for gas-payback-tokens and if people send their tokens directly to the contractwithout the approval of the casino./ | function withdrawExcess() public onlyAuthorized {
uint value = safeSub(tokenBalance(), totalStakes);
token.transfer(owner, value);
}
| function withdrawExcess() public onlyAuthorized {
uint value = safeSub(tokenBalance(), totalStakes);
token.transfer(owner, value);
}
| 40,586 |
91 | // Withdrawals may be paused if a hack has recently happened. Timestamp of when the pause happened. | uint256 public withdrawalsPaused;
| uint256 public withdrawalsPaused;
| 42,763 |
8 | // No double buying roses | if (roseOwners[senderHash].hasRose) {
sender.transfer(amntSent);
return;
}
| if (roseOwners[senderHash].hasRose) {
sender.transfer(amntSent);
return;
}
| 16,721 |
147 | // Owner drains tokens when the contract is paused emergency use only _amount drained token amount / | function drainToken(uint256 _amount) external whenPaused onlyOwner {
CELER_TOKEN.safeTransfer(msg.sender, _amount);
}
| function drainToken(uint256 _amount) external whenPaused onlyOwner {
CELER_TOKEN.safeTransfer(msg.sender, _amount);
}
| 5,231 |
166 | // Instructs the SetToken to wrap the passed quantity of ETH_setTokenSetToken instance to invoke _wethWETH address _quantityThe quantity to unwrap / | function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
| function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
| 27,825 |
58 | // See {IERC721-approve}. / | function approve(address to, uint256 tokenId) public virtual override {
| function approve(address to, uint256 tokenId) public virtual override {
| 3,135 |
94 | // putting up the flag for sale | animalAgainstId[animalId].upForSale=true;
animalAgainstId[animalId].priceForSale=convertedpricetoEther;
upForSaleList.push(animalId);
| animalAgainstId[animalId].upForSale=true;
animalAgainstId[animalId].priceForSale=convertedpricetoEther;
upForSaleList.push(animalId);
| 16,519 |
17 | // Event for white list minting | event WhiteListMint(address indexed user, uint256 tokenId, uint256 amount);
| event WhiteListMint(address indexed user, uint256 tokenId, uint256 amount);
| 20,651 |
23 | // @inheritdoc ERC165Upgradeable | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IOFTCore).interfaceId || super.supportsInterface(interfaceId);
}
| function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IOFTCore).interfaceId || super.supportsInterface(interfaceId);
}
| 16,888 |
167 | // Emit WhitelistEnforcementChanged(bool enforce); | emit WhitelistEnforcementChanged(enforce);
return uint256(Error.NO_ERROR);
| emit WhitelistEnforcementChanged(enforce);
return uint256(Error.NO_ERROR);
| 23,466 |
16 | // if they received more than they should have, add to the reclaim tally | reclaimAmount = reclaimAmount.add(amountReceived.sub(amountShouldHaveReceived));
| reclaimAmount = reclaimAmount.add(amountReceived.sub(amountShouldHaveReceived));
| 32,266 |
4 | // max number of NFTs a Premium whitelist can mint | uint256 public premiumNftPerAddressLimit = 20;
bool public paused = true;
bool public revealed = false;
| uint256 public premiumNftPerAddressLimit = 20;
bool public paused = true;
bool public revealed = false;
| 56,394 |
16 | // Sets dividend address. _divaddr Dividend address. / | function setDividends(address payable _divaddr) public {
require(accessControls.hasAdminRole(msg.sender), "MISOTokenFactory: Sender must be Admin");
misoDiv = _divaddr;
}
| function setDividends(address payable _divaddr) public {
require(accessControls.hasAdminRole(msg.sender), "MISOTokenFactory: Sender must be Admin");
misoDiv = _divaddr;
}
| 48,857 |
120 | // Calculate each order&39;s `lrcFee` and `lrcRewrard` and splict how much of `fillAmountS` shall be paid to matching order or miner as margin split. | calculateRingFees(
delegate,
params.ringSize,
orders,
params.feeRecipient,
_lrcTokenAddress
);
| calculateRingFees(
delegate,
params.ringSize,
orders,
params.feeRecipient,
_lrcTokenAddress
);
| 37,977 |
2 | // Transfers `asset`s of `tokenIds` to `to` address from `this` contract. / | function _offerAssets(
address to,
uint256[] memory tokenIds,
uint256[] memory amounts
| function _offerAssets(
address to,
uint256[] memory tokenIds,
uint256[] memory amounts
| 47,149 |
60 | // require that the transaction has not been reported yet by the reporter | require(!_reportedTxs[txId][msg.sender], "ERR_ALREADY_REPORTED");
| require(!_reportedTxs[txId][msg.sender], "ERR_ALREADY_REPORTED");
| 46,221 |
227 | // reverse-for-loops with unsigned integer/ solium-disable-next-line security/no-modify-for-iter-var / find the last non-zero byte in order to determine the length | if (result[i] != 0) {
uint256 length = i + 1;
| if (result[i] != 0) {
uint256 length = i + 1;
| 4,205 |
114 | // Pausing is a very serious situation - we revert to sound the alarms | require(!rewardGuardianPaused && !stakeGuardianPaused, "STAKE_OR_REWARD IS PAUSED");
require(_amount > 0,"AMOUNT MUST > 0");
require(DEBIToken(DIBI).balanceOf(msg.sender) >= _amount, "INSUFFICIENT DIBI");
STAKER storage staker = stakers[msg.sender];
| require(!rewardGuardianPaused && !stakeGuardianPaused, "STAKE_OR_REWARD IS PAUSED");
require(_amount > 0,"AMOUNT MUST > 0");
require(DEBIToken(DIBI).balanceOf(msg.sender) >= _amount, "INSUFFICIENT DIBI");
STAKER storage staker = stakers[msg.sender];
| 11,309 |
491 | // A malicious attacker could take advantage of this function to take a flash loan, burn agTokens to diminish the stocks users and then force close some perpetuals. We also need to check that assuming really small burn transaction fees (of 0.05%), an attacker could make a profit with such flash loan if current hedge is below the target hedge by making such flash loan. The formula for the cost of such flash loan is: `fees(limitHAHedge - targetHAHedge)stocksUsers / oracle` In order to avoid doing multiplications after divisions, and to get everything in the correct base, we do: | uint256 estimatedCost = (5 * (limitHAHedge - targetHAHedge) * stocksUsers * _collatBase) /
(rateUp * 10000 * BASE_PARAMS);
cashOutFees = cashOutFees < estimatedCost ? cashOutFees : estimatedCost;
emit PerpetualsForceClosed(perpetualIDs, outputPairs, msg.sender, cashOutFees + liquidationFees);
| uint256 estimatedCost = (5 * (limitHAHedge - targetHAHedge) * stocksUsers * _collatBase) /
(rateUp * 10000 * BASE_PARAMS);
cashOutFees = cashOutFees < estimatedCost ? cashOutFees : estimatedCost;
emit PerpetualsForceClosed(perpetualIDs, outputPairs, msg.sender, cashOutFees + liquidationFees);
| 30,238 |
5 | // store the loan terms | struct LoanTerms{
uint32 term;
uint32 interest;
uint32 loanAmount;
uint32 annualTax;
uint32 annualInsurance;
}
| struct LoanTerms{
uint32 term;
uint32 interest;
uint32 loanAmount;
uint32 annualTax;
uint32 annualInsurance;
}
| 24,525 |
218 | // Actual duration of the stake, expressed in hours | actualDuration = 0;
| actualDuration = 0;
| 24,403 |
12 | // if we're opening up voting status, clear any previous results. | if(isOpen)
{
clearOutAllPreviousVoting();
}
| if(isOpen)
{
clearOutAllPreviousVoting();
}
| 24,158 |
13 | // Executes a batch of transactions. This function can only be called when the contract is not paused.Only callable by the EXECUTOR_ROLE role. targets The array of target addresses for the transactions. values The array of values to be sent with each transaction. payloads The array of payload data for each transaction. predecessor The predecessor block's hash. salt The salt value for generating a deterministic pseudo-random address. / | function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata payloads,
bytes32 predecessor,
bytes32 salt
| function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata payloads,
bytes32 predecessor,
bytes32 salt
| 16,374 |
8 | // display the related token of the balance reported | function balanceReportedIn() public view override returns (address) {
return address(token);
}
| function balanceReportedIn() public view override returns (address) {
return address(token);
}
| 32,213 |
3 | // Set the native token (MATIC) | function set_nativeTokenAddress(address payable _nativeTokenAddress) external onlyOwner {
nativeTokenAddress = _nativeTokenAddress;
}
| function set_nativeTokenAddress(address payable _nativeTokenAddress) external onlyOwner {
nativeTokenAddress = _nativeTokenAddress;
}
| 9,210 |
22 | // TODO kmsAddr => kmsID | function getKMSID(address _kmsAddr) public view returns (string){
return Precompile.makeIDString(Precompile.CodeKMS(), _kmsAddr);
}
| function getKMSID(address _kmsAddr) public view returns (string){
return Precompile.makeIDString(Precompile.CodeKMS(), _kmsAddr);
}
| 11,646 |
319 | // F1 - F10: OK F3: _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple F6: There is an exploit to add lots of GOLN to the alchemybench, run convert, then remove the GOLN again. As the size of the AlchemyBench has grown, this requires large amounts of funds and isn't super profitable anymore The onlyEOA modifier prevents this being done with a flash loan. C1 - C24: OK | function convert(address token0, address token1) external onlyEOA() {
_convert(token0, token1);
}
| function convert(address token0, address token1) external onlyEOA() {
_convert(token0, token1);
}
| 37,058 |
155 | // Return all members of a role/No ordering guarantees, as per underlying EnumerableSet sturcture | function getRoleMembers(bytes32 role) public view returns (address[] memory) {
uint256 length = getRoleMemberCount(role);
address[] memory members = new address[](length);
for (uint256 i = 0; i < length; i++) {
members[i] = getRoleMember(role, i);
}
return members;
}
| function getRoleMembers(bytes32 role) public view returns (address[] memory) {
uint256 length = getRoleMemberCount(role);
address[] memory members = new address[](length);
for (uint256 i = 0; i < length; i++) {
members[i] = getRoleMember(role, i);
}
return members;
}
| 26,871 |
77 | // Modifier to allow function calls only from the ProxyAdmin. / | modifier onlyProxyAdmin() {
require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute");
_;
}
| modifier onlyProxyAdmin() {
require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute");
_;
}
| 9,944 |
60 | // Transfer tokens from one address to another.Note that while this function emits an Approval event, this is not required as per the specification,and other compliant implementations may not emit the event. _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred / | function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) {
_transfer(_from, _to, _value);
_approve(_from, msg.sender, _allowed[_from][msg.sender].sub(_value));
return true;
}
| function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) {
_transfer(_from, _to, _value);
_approve(_from, msg.sender, _allowed[_from][msg.sender].sub(_value));
return true;
}
| 39,729 |
70 | // Done with a valid stored block | return ErrorCode.ERR_NONE;
| return ErrorCode.ERR_NONE;
| 31,484 |
159 | // State public state = 0; | uint8 public statePhase = 0;
| uint8 public statePhase = 0;
| 39,497 |
774 | // Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. | return _addSwapFeeAmount(amountIn);
| return _addSwapFeeAmount(amountIn);
| 5,208 |
243 | // ScaleFactor (10e18) - fee | uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
| uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
| 35,159 |
18 | // Secondary market royalties in basis points (100 bps = 1%) | uint256 royaltiesBps;
| uint256 royaltiesBps;
| 37,821 |
10 | // Проверка на возврат кредита при невалидном индексе | try credit.getDebts(sender, credit.getLength(sender)) {
success = true;
} catch {
| try credit.getDebts(sender, credit.getLength(sender)) {
success = true;
} catch {
| 15,628 |
3 | // TrancheDataHelpers Library with helper functions the bond's retrieved tranche data./ | library TrancheDataHelpers {
/// @notice Iterates through the tranche data to find the seniority index of the given tranche.
/// @param td The tranche data object.
/// @param t The address of the tranche to check.
/// @return the index of the tranche in the tranches array.
function getTrancheIndex(TrancheData memory td, ITranche t) internal pure returns (uint256) {
for (uint8 i = 0; i < td.trancheCount; i++) {
if (td.tranches[i] == t) {
return i;
}
}
revert UnacceptableTrancheIndex(t);
}
}
| library TrancheDataHelpers {
/// @notice Iterates through the tranche data to find the seniority index of the given tranche.
/// @param td The tranche data object.
/// @param t The address of the tranche to check.
/// @return the index of the tranche in the tranches array.
function getTrancheIndex(TrancheData memory td, ITranche t) internal pure returns (uint256) {
for (uint8 i = 0; i < td.trancheCount; i++) {
if (td.tranches[i] == t) {
return i;
}
}
revert UnacceptableTrancheIndex(t);
}
}
| 13,766 |
13 | // remove from pending deposits, tokens can be sent immediately | globalState.totalPendingAmount -= withdrawAmount;
globalState.totalShares -= sharesNeeded;
finished = true;
| globalState.totalPendingAmount -= withdrawAmount;
globalState.totalShares -= sharesNeeded;
finished = true;
| 18,084 |
65 | // Unifying the interface with the Synthetix Reward Pool | interface IRewardPool {
function rewardToken() external view returns (address);
function lpToken() external view returns (address);
function duration() external view returns (uint256);
function periodFinish() external view returns (uint256);
function rewardRate() external view returns (uint256);
function rewardPerTokenStored() external view returns (uint256);
function stake(uint256 amountWei) external;
// `balanceOf` would give the amount staked.
// As this is 1 to 1, this is also the holder's share
function balanceOf(address holder) external view returns (uint256);
// total shares & total lpTokens staked
function totalSupply() external view returns(uint256);
function withdraw(uint256 amountWei) external;
function exit() external;
// get claimed rewards
function earned(address holder) external view returns (uint256);
// claim rewards
function getReward() external;
// notify
function notifyRewardAmount(uint256 _amount) external;
}
| interface IRewardPool {
function rewardToken() external view returns (address);
function lpToken() external view returns (address);
function duration() external view returns (uint256);
function periodFinish() external view returns (uint256);
function rewardRate() external view returns (uint256);
function rewardPerTokenStored() external view returns (uint256);
function stake(uint256 amountWei) external;
// `balanceOf` would give the amount staked.
// As this is 1 to 1, this is also the holder's share
function balanceOf(address holder) external view returns (uint256);
// total shares & total lpTokens staked
function totalSupply() external view returns(uint256);
function withdraw(uint256 amountWei) external;
function exit() external;
// get claimed rewards
function earned(address holder) external view returns (uint256);
// claim rewards
function getReward() external;
// notify
function notifyRewardAmount(uint256 _amount) external;
}
| 37,248 |
83 | // Calculates the latest borrowed amount by the new market borrowed index. | uint256 _accountBorrows = _borrowBalanceInternal(_borrower);
| uint256 _accountBorrows = _borrowBalanceInternal(_borrower);
| 34,493 |
39 | // Clean up the existing top bid | delete highestBids[_nftAddress][_tokenId];
| delete highestBids[_nftAddress][_tokenId];
| 14,156 |
760 | // (currentTs - previousTs) / timeWindow | uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
| uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
| 65,188 |
11 | // Details of a particular subscription | struct Subscription {
bool active;
address subscriberAddress; // addres the subscriptions refers to
uint startDate; // Block timestamp at which the subscription was made
uint stakedAmount; // How much was staked
uint maxReward; // Maximum reward given if user stays until the end of the staking period
uint withdrawAmount; // Total amount withdrawn (initial amount + final calculated reward)
uint withdrawDate; // Block timestamp at which the subscription was withdrawn (or 0 while staking is in progress)
}
| struct Subscription {
bool active;
address subscriberAddress; // addres the subscriptions refers to
uint startDate; // Block timestamp at which the subscription was made
uint stakedAmount; // How much was staked
uint maxReward; // Maximum reward given if user stays until the end of the staking period
uint withdrawAmount; // Total amount withdrawn (initial amount + final calculated reward)
uint withdrawDate; // Block timestamp at which the subscription was withdrawn (or 0 while staking is in progress)
}
| 31,464 |
238 | // Max referral commission rate: 10%. | uint16 public constant MAXIMUM_REFERRAL_COMMISSION_RATE = 1000;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount);
event ReferralCommissionPaid(address indexed user, address indexed referrer, uint256 commissionAmount);
event RewardLockedUp(address indexed user, uint256 indexed pid, uint256 amountLockedUp);
constructor(
| uint16 public constant MAXIMUM_REFERRAL_COMMISSION_RATE = 1000;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount);
event ReferralCommissionPaid(address indexed user, address indexed referrer, uint256 commissionAmount);
event RewardLockedUp(address indexed user, uint256 indexed pid, uint256 amountLockedUp);
constructor(
| 24,597 |
8 | // calculamos el hash del alumno | function hashIdAlumno(string memory _nombre, address _direccion, uint _edad) private {
hash_Id_alumno = keccak256(abi.encodePacked(_nombre, _direccion, _edad));
}
| function hashIdAlumno(string memory _nombre, address _direccion, uint _edad) private {
hash_Id_alumno = keccak256(abi.encodePacked(_nombre, _direccion, _edad));
}
| 45,830 |
44 | // transfer excess funds back to builder wallet.Called internally-1. Change in already funded phases with lower overall cost2. Phase changeOrder when new phase cost is lower than older cost3. Task changeOrder when new task cost is lower than older cost _amount uint256 - amount of excess fund / | function autoWithdraw(uint256 _amount) internal virtual;
| function autoWithdraw(uint256 _amount) internal virtual;
| 6,343 |
7 | // Locker Unit | uint256 lastClaim;
| uint256 lastClaim;
| 57,123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.