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 |
|---|---|---|---|---|
450 | // ========== Minter Only ========== / | function mint(address account, uint256 amount) external onlyMinter {
_mint(account, amount);
}
| function mint(address account, uint256 amount) external onlyMinter {
_mint(account, amount);
}
| 42,772 |
55 | // Definition of Wallets for Marketing or team. | address payable public marketingWallet =
payable(0x21d3be3fb3F25d4E0B867958D8A91dA84879c417);
address payable public ecosystemWallet =
payable(0x0cb72c337a1171C8ef074858FfCE10b81A6Ce01C);
| address payable public marketingWallet =
payable(0x21d3be3fb3F25d4E0B867958D8A91dA84879c417);
address payable public ecosystemWallet =
payable(0x0cb72c337a1171C8ef074858FfCE10b81A6Ce01C);
| 7,339 |
55 | // transfer erc20 token to this contract | IERC20(_erc20Contract).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(_erc20Contract).safeIncreaseAllowance(_yErc20Contract, _amount);
| IERC20(_erc20Contract).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(_erc20Contract).safeIncreaseAllowance(_yErc20Contract, _amount);
| 49,677 |
162 | // market fee to cut | uint256 saleShareAmount = 0;
| uint256 saleShareAmount = 0;
| 17,207 |
39 | // blockNumber => blockHash all block commitment hash headers Mapping actually better than array IMO, use tip as len | mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3
| mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3
| 21,387 |
492 | // Update the base token URI / | function setBaseURI(string calldata _newBaseURI) external onlyOwner {
require(!metadataFrozen, "METADATA_HAS_BEEN_FROZEN");
baseTokenURI = _newBaseURI;
}
| function setBaseURI(string calldata _newBaseURI) external onlyOwner {
require(!metadataFrozen, "METADATA_HAS_BEEN_FROZEN");
baseTokenURI = _newBaseURI;
}
| 1,181 |
96 | // The minimum amount of shares to be minted in the contructor. / | uint256 internal constant MINIMUM_CONSTRUCTOR_MINT = 1e4;
| uint256 internal constant MINIMUM_CONSTRUCTOR_MINT = 1e4;
| 42,259 |
234 | // Decode a CBOR value into a Witnet.Result instance./_cborValue An instance of `Witnet.Value`./ return A `Witnet.Result` instance. | function resultFromCborValue(Witnet.CBOR memory _cborValue)
public pure
returns (Witnet.Result memory)
| function resultFromCborValue(Witnet.CBOR memory _cborValue)
public pure
returns (Witnet.Result memory)
| 22,450 |
89 | // Set the output so it can be exited later. | inFlightExit.outputs[_outputIndex - MAX_INPUTS] = output;
| inFlightExit.outputs[_outputIndex - MAX_INPUTS] = output;
| 26,732 |
75 | // do not allow to drain lpToken if less than 3 months after farming | require(_token != bsd, "!bsd");
for (uint256 pid = 0; pid < poolLength; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.lpToken, "!pool.lpToken");
}
| require(_token != bsd, "!bsd");
for (uint256 pid = 0; pid < poolLength; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.lpToken, "!pool.lpToken");
}
| 33,306 |
0 | // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a cliff period of a year and a duration of four years, are safe to use. | using SafeMath for uint256;
using SafeERC20 for IERC20;
event Registered(address account, uint256 amount);
event Revoked(address account);
event Claimed(address account, uint256 amount);
address public vestingToken;
uint256 public totalReleased;
uint256 public totalAllocated;
| using SafeMath for uint256;
using SafeERC20 for IERC20;
event Registered(address account, uint256 amount);
event Revoked(address account);
event Claimed(address account, uint256 amount);
address public vestingToken;
uint256 public totalReleased;
uint256 public totalAllocated;
| 13,803 |
189 | // charge exit fee | uint256 exitFee=_chargeJoinAndExitFee(SmartPoolStorage.FeeType.EXIT_FEE,amount);
uint256 exitAmount=amount.sub(exitFee);
| uint256 exitFee=_chargeJoinAndExitFee(SmartPoolStorage.FeeType.EXIT_FEE,amount);
uint256 exitAmount=amount.sub(exitFee);
| 11,009 |
79 | // return The EIP-1967 proxy admin / | function getAdmin()
public
view
returns (address)
| function getAdmin()
public
view
returns (address)
| 42,971 |
8 | // pay to first investors in line | pay();
| pay();
| 766 |
1 | // Combines account details with their twab history. details The account details. twabs The history of twabs for this account. / | struct Account {
AccountDetails details;
ObservationLib.Observation[65535] twabs;
}
| struct Account {
AccountDetails details;
ObservationLib.Observation[65535] twabs;
}
| 24,622 |
6 | // The total number of proposals | uint public proposalCount;
| uint public proposalCount;
| 48,930 |
6 | // You can create temporary structs in memory with keyword "memory" | struct Person {
bytes32 name;
uint8 age;
}
| struct Person {
bytes32 name;
uint8 age;
}
| 48,884 |
33 | // sequentially call contacts, abort on failed calls | invokeContracts(script);
| invokeContracts(script);
| 36,901 |
529 | // Ensure the Safe is registered with the Master. | require(master.getSafeId(safe) != 0);
emit ImpoundExecuted(msg.sender, safe, feiAmount, assetAmount);
| require(master.getSafeId(safe) != 0);
emit ImpoundExecuted(msg.sender, safe, feiAmount, assetAmount);
| 61,710 |
5 | // Approve transfer _spender holder address _value tokens amountreturn result / | function approve(address _spender, uint256 _value) public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| function approve(address _spender, uint256 _value) public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| 9,083 |
90 | // Protected storage | function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address);
function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address);
function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external;
function confirmWithdrawalAddress(address _nodeAddress) external;
| function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address);
function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address);
function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external;
function confirmWithdrawalAddress(address _nodeAddress) external;
| 47,214 |
194 | // Token with Governance. | contract NFTGAMETOKEN is BEP20 {
// Transfer tax rate in basis points. (default 5%)
uint16 public transferTaxRate = 500;
// Burn rate % of transfer tax. (default 20% x 5% = 1% of total amount).
uint16 public burnRate = 20;
// Max transfer tax rate: 10%.
uint16 public constant MAXIMUM_TRANSFER_TAX_RATE = 1000;
// Burn address
address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
// Max transfer amount rate in basis points. (default is 0.5% of total supply)
uint16 public maxTransferAmountRate = 50;
// Addresses that excluded from antiWhale
mapping(address => bool) private _excludedFromAntiWhale;
// Automatic swap and liquify enabled
bool public swapAndLiquifyEnabled = false;
// Min amount to liquify. (default 500 NFTGAME)
uint256 public minAmountToLiquify = 500 ether;
// The swap router, modifiable. Will be changed to PantherSwap's router when our own AMM release
IUniswapV2Router02 public pantherSwapRouter;
// The trading pair
address public pantherSwapPair;
// In swap and liquify
bool private _inSwapAndLiquify;
// The operator can only update the transfer tax rate
address private _operator;
// Events
event OperatorTransferred(address indexed previousOperator, address indexed newOperator);
event TransferTaxRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event BurnRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event SwapAndLiquifyEnabledUpdated(address indexed operator, bool enabled);
event MinAmountToLiquifyUpdated(address indexed operator, uint256 previousAmount, uint256 newAmount);
event PantherSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
modifier onlyOperator() {
require(_operator == msg.sender, "operator: caller is not the operator");
_;
}
modifier antiWhale(address sender, address recipient, uint256 amount) {
if (maxTransferAmount() > 0) {
if (
_excludedFromAntiWhale[sender] == false
&& _excludedFromAntiWhale[recipient] == false
) {
require(amount <= maxTransferAmount(), "NFTGAME::antiWhale: Transfer amount exceeds the maxTransferAmount");
}
}
_;
}
modifier lockTheSwap {
_inSwapAndLiquify = true;
_;
_inSwapAndLiquify = false;
}
modifier transferTaxFree {
uint16 _transferTaxRate = transferTaxRate;
transferTaxRate = 0;
_;
transferTaxRate = _transferTaxRate;
}
/**
* @notice Constructs the contract.
*/
constructor() public BEP20("NFT GAME TOKEN", "NFTGAME") {
_operator = _msgSender();
emit OperatorTransferred(address(0), _operator);
_excludedFromAntiWhale[msg.sender] = true;
_excludedFromAntiWhale[address(0)] = true;
_excludedFromAntiWhale[address(this)] = true;
_excludedFromAntiWhale[BURN_ADDRESS] = true;
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/// @dev overrides transfer function to meet tokenomics
function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) {
// swap and liquify
if (
swapAndLiquifyEnabled == true
&& _inSwapAndLiquify == false
&& address(pantherSwapRouter) != address(0)
&& pantherSwapPair != address(0)
&& sender != pantherSwapPair
&& sender != owner()
) {
swapAndLiquify();
}
if (recipient == BURN_ADDRESS || transferTaxRate == 0) {
super._transfer(sender, recipient, amount);
} else {
// default tax is 5% of every transfer
uint256 taxAmount = amount.mul(transferTaxRate).div(10000);
uint256 burnAmount = taxAmount.mul(burnRate).div(100);
uint256 liquidityAmount = taxAmount.sub(burnAmount);
require(taxAmount == burnAmount + liquidityAmount, "NFTGAME::transfer: Burn value invalid");
// default 95% of transfer sent to recipient
uint256 sendAmount = amount.sub(taxAmount);
require(amount == sendAmount + taxAmount, "NFTGAME::transfer: Tax value invalid");
super._transfer(sender, BURN_ADDRESS, burnAmount);
super._transfer(sender, address(this), liquidityAmount);
super._transfer(sender, recipient, sendAmount);
amount = sendAmount;
}
}
/// @dev Swap and liquify
function swapAndLiquify() private lockTheSwap transferTaxFree {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 maxTransferAmount = maxTransferAmount();
contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance;
if (contractTokenBalance >= minAmountToLiquify) {
// only min amount to liquify
uint256 liquifyAmount = minAmountToLiquify;
// split the liquify amount into halves
uint256 half = liquifyAmount.div(2);
uint256 otherHalf = liquifyAmount.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half);
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
}
/// @dev Swap tokens for eth
function swapTokensForEth(uint256 tokenAmount) private {
// generate the pantherSwap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = pantherSwapRouter.WETH();
_approve(address(this), address(pantherSwapRouter), tokenAmount);
// make the swap
pantherSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
/// @dev Add liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(pantherSwapRouter), tokenAmount);
// add the liquidity
pantherSwapRouter.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
operator(),
block.timestamp
);
}
/**
* @dev Returns the max transfer amount.
*/
function maxTransferAmount() public view returns (uint256) {
return totalSupply().mul(maxTransferAmountRate).div(1000000);
}
/**
* @dev Returns the address is excluded from antiWhale or not.
*/
function isExcludedFromAntiWhale(address _account) public view returns (bool) {
return _excludedFromAntiWhale[_account];
}
// To receive BNB from pantherSwapRouter when swapping
receive() external payable {}
/**
* @dev Update the transfer tax rate.
* Can only be called by the current operator.
*/
function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOperator {
require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "NFTGAME::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate.");
emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate);
transferTaxRate = _transferTaxRate;
}
/**
* @dev Update the burn rate.
* Can only be called by the current operator.
*/
function updateBurnRate(uint16 _burnRate) public onlyOperator {
require(_burnRate <= 100, "NFTGAME::updateBurnRate: Burn rate must not exceed the maximum rate.");
emit BurnRateUpdated(msg.sender, burnRate, _burnRate);
burnRate = _burnRate;
}
/**
* @dev Update the max transfer amount rate.
* Can only be called by the current operator.
*/
function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOperator {
require(_maxTransferAmountRate <= 10000, "NFTGAME::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate.");
emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate);
maxTransferAmountRate = _maxTransferAmountRate;
}
/**
* @dev Update the min amount to liquify.
* Can only be called by the current operator.
*/
function updateMinAmountToLiquify(uint256 _minAmount) public onlyOperator {
emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount);
minAmountToLiquify = _minAmount;
}
/**
* @dev Exclude or include an address from antiWhale.
* Can only be called by the current operator.
*/
function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyOperator {
_excludedFromAntiWhale[_account] = _excluded;
}
/**
* @dev Update the swapAndLiquifyEnabled.
* Can only be called by the current operator.
*/
function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOperator {
emit SwapAndLiquifyEnabledUpdated(msg.sender, _enabled);
swapAndLiquifyEnabled = _enabled;
}
/**
* @dev Update the swap router.
* Can only be called by the current operator.
*/
function updatePantherSwapRouter(address _router) public onlyOperator {
pantherSwapRouter = IUniswapV2Router02(_router);
pantherSwapPair = IUniswapV2Factory(pantherSwapRouter.factory()).getPair(address(this), pantherSwapRouter.WETH());
require(pantherSwapPair != address(0), "NFTGAME::updatePantherSwapRouter: Invalid pair address.");
emit PantherSwapRouterUpdated(msg.sender, address(pantherSwapRouter), pantherSwapPair);
}
/**
* @dev Returns the address of the current operator.
*/
function operator() public view returns (address) {
return _operator;
}
/**
* @dev Transfers operator of the contract to a new account (`newOperator`).
* Can only be called by the current operator.
*/
function transferOperator(address newOperator) public onlyOperator {
require(newOperator != address(0), "NFTGAME::transferOperator: new operator is the zero address");
emit OperatorTransferred(_operator, newOperator);
_operator = newOperator;
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "NFTGAME::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "NFTGAME::delegateBySig: invalid nonce");
require(now <= expiry, "NFTGAME::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "NFTGAME::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "NFTGAME::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | contract NFTGAMETOKEN is BEP20 {
// Transfer tax rate in basis points. (default 5%)
uint16 public transferTaxRate = 500;
// Burn rate % of transfer tax. (default 20% x 5% = 1% of total amount).
uint16 public burnRate = 20;
// Max transfer tax rate: 10%.
uint16 public constant MAXIMUM_TRANSFER_TAX_RATE = 1000;
// Burn address
address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
// Max transfer amount rate in basis points. (default is 0.5% of total supply)
uint16 public maxTransferAmountRate = 50;
// Addresses that excluded from antiWhale
mapping(address => bool) private _excludedFromAntiWhale;
// Automatic swap and liquify enabled
bool public swapAndLiquifyEnabled = false;
// Min amount to liquify. (default 500 NFTGAME)
uint256 public minAmountToLiquify = 500 ether;
// The swap router, modifiable. Will be changed to PantherSwap's router when our own AMM release
IUniswapV2Router02 public pantherSwapRouter;
// The trading pair
address public pantherSwapPair;
// In swap and liquify
bool private _inSwapAndLiquify;
// The operator can only update the transfer tax rate
address private _operator;
// Events
event OperatorTransferred(address indexed previousOperator, address indexed newOperator);
event TransferTaxRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event BurnRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event SwapAndLiquifyEnabledUpdated(address indexed operator, bool enabled);
event MinAmountToLiquifyUpdated(address indexed operator, uint256 previousAmount, uint256 newAmount);
event PantherSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
modifier onlyOperator() {
require(_operator == msg.sender, "operator: caller is not the operator");
_;
}
modifier antiWhale(address sender, address recipient, uint256 amount) {
if (maxTransferAmount() > 0) {
if (
_excludedFromAntiWhale[sender] == false
&& _excludedFromAntiWhale[recipient] == false
) {
require(amount <= maxTransferAmount(), "NFTGAME::antiWhale: Transfer amount exceeds the maxTransferAmount");
}
}
_;
}
modifier lockTheSwap {
_inSwapAndLiquify = true;
_;
_inSwapAndLiquify = false;
}
modifier transferTaxFree {
uint16 _transferTaxRate = transferTaxRate;
transferTaxRate = 0;
_;
transferTaxRate = _transferTaxRate;
}
/**
* @notice Constructs the contract.
*/
constructor() public BEP20("NFT GAME TOKEN", "NFTGAME") {
_operator = _msgSender();
emit OperatorTransferred(address(0), _operator);
_excludedFromAntiWhale[msg.sender] = true;
_excludedFromAntiWhale[address(0)] = true;
_excludedFromAntiWhale[address(this)] = true;
_excludedFromAntiWhale[BURN_ADDRESS] = true;
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/// @dev overrides transfer function to meet tokenomics
function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) {
// swap and liquify
if (
swapAndLiquifyEnabled == true
&& _inSwapAndLiquify == false
&& address(pantherSwapRouter) != address(0)
&& pantherSwapPair != address(0)
&& sender != pantherSwapPair
&& sender != owner()
) {
swapAndLiquify();
}
if (recipient == BURN_ADDRESS || transferTaxRate == 0) {
super._transfer(sender, recipient, amount);
} else {
// default tax is 5% of every transfer
uint256 taxAmount = amount.mul(transferTaxRate).div(10000);
uint256 burnAmount = taxAmount.mul(burnRate).div(100);
uint256 liquidityAmount = taxAmount.sub(burnAmount);
require(taxAmount == burnAmount + liquidityAmount, "NFTGAME::transfer: Burn value invalid");
// default 95% of transfer sent to recipient
uint256 sendAmount = amount.sub(taxAmount);
require(amount == sendAmount + taxAmount, "NFTGAME::transfer: Tax value invalid");
super._transfer(sender, BURN_ADDRESS, burnAmount);
super._transfer(sender, address(this), liquidityAmount);
super._transfer(sender, recipient, sendAmount);
amount = sendAmount;
}
}
/// @dev Swap and liquify
function swapAndLiquify() private lockTheSwap transferTaxFree {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 maxTransferAmount = maxTransferAmount();
contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance;
if (contractTokenBalance >= minAmountToLiquify) {
// only min amount to liquify
uint256 liquifyAmount = minAmountToLiquify;
// split the liquify amount into halves
uint256 half = liquifyAmount.div(2);
uint256 otherHalf = liquifyAmount.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half);
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
}
/// @dev Swap tokens for eth
function swapTokensForEth(uint256 tokenAmount) private {
// generate the pantherSwap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = pantherSwapRouter.WETH();
_approve(address(this), address(pantherSwapRouter), tokenAmount);
// make the swap
pantherSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
/// @dev Add liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(pantherSwapRouter), tokenAmount);
// add the liquidity
pantherSwapRouter.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
operator(),
block.timestamp
);
}
/**
* @dev Returns the max transfer amount.
*/
function maxTransferAmount() public view returns (uint256) {
return totalSupply().mul(maxTransferAmountRate).div(1000000);
}
/**
* @dev Returns the address is excluded from antiWhale or not.
*/
function isExcludedFromAntiWhale(address _account) public view returns (bool) {
return _excludedFromAntiWhale[_account];
}
// To receive BNB from pantherSwapRouter when swapping
receive() external payable {}
/**
* @dev Update the transfer tax rate.
* Can only be called by the current operator.
*/
function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOperator {
require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "NFTGAME::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate.");
emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate);
transferTaxRate = _transferTaxRate;
}
/**
* @dev Update the burn rate.
* Can only be called by the current operator.
*/
function updateBurnRate(uint16 _burnRate) public onlyOperator {
require(_burnRate <= 100, "NFTGAME::updateBurnRate: Burn rate must not exceed the maximum rate.");
emit BurnRateUpdated(msg.sender, burnRate, _burnRate);
burnRate = _burnRate;
}
/**
* @dev Update the max transfer amount rate.
* Can only be called by the current operator.
*/
function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOperator {
require(_maxTransferAmountRate <= 10000, "NFTGAME::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate.");
emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate);
maxTransferAmountRate = _maxTransferAmountRate;
}
/**
* @dev Update the min amount to liquify.
* Can only be called by the current operator.
*/
function updateMinAmountToLiquify(uint256 _minAmount) public onlyOperator {
emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount);
minAmountToLiquify = _minAmount;
}
/**
* @dev Exclude or include an address from antiWhale.
* Can only be called by the current operator.
*/
function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyOperator {
_excludedFromAntiWhale[_account] = _excluded;
}
/**
* @dev Update the swapAndLiquifyEnabled.
* Can only be called by the current operator.
*/
function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOperator {
emit SwapAndLiquifyEnabledUpdated(msg.sender, _enabled);
swapAndLiquifyEnabled = _enabled;
}
/**
* @dev Update the swap router.
* Can only be called by the current operator.
*/
function updatePantherSwapRouter(address _router) public onlyOperator {
pantherSwapRouter = IUniswapV2Router02(_router);
pantherSwapPair = IUniswapV2Factory(pantherSwapRouter.factory()).getPair(address(this), pantherSwapRouter.WETH());
require(pantherSwapPair != address(0), "NFTGAME::updatePantherSwapRouter: Invalid pair address.");
emit PantherSwapRouterUpdated(msg.sender, address(pantherSwapRouter), pantherSwapPair);
}
/**
* @dev Returns the address of the current operator.
*/
function operator() public view returns (address) {
return _operator;
}
/**
* @dev Transfers operator of the contract to a new account (`newOperator`).
* Can only be called by the current operator.
*/
function transferOperator(address newOperator) public onlyOperator {
require(newOperator != address(0), "NFTGAME::transferOperator: new operator is the zero address");
emit OperatorTransferred(_operator, newOperator);
_operator = newOperator;
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "NFTGAME::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "NFTGAME::delegateBySig: invalid nonce");
require(now <= expiry, "NFTGAME::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "NFTGAME::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "NFTGAME::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | 17,755 |
682 | // Swaps all collected ERC20 tokens (of the specified type) into burn tokens using an external DEX and burns themcollectedToken token contract address of the collected ERC20 tokens that should be burned (must be an IERC20 contract) emits event BoughtBackAndBurned() / | function buyBackAndBurnERC20(address collectedToken) external whenNotPaused nonReentrant {
// check input parameter
require(collectedToken != address(0), 'BuyBackAndBurnV1: invalid token address');
// check how much of the given token is ready for burn
uint256 amount = collectedERC20ToBurn[collectedToken];
require(amount > 0, 'BuyBackAndBurnV1: no tokens to burn');
// register approval for router to spend collectedToken, if not already done
if (IERC20(collectedToken).allowance(address(this), address(router)) < amount) {
IERC20(collectedToken).approve(address(router), type(uint256).max);
}
// swap collected tokens to burn tokens using external DEX
uint256 burnAmount = router.tradeERC20(IERC20(collectedToken), burnToken, amount);
// burn all available burn tokens (swapped and directly collected))
uint256 balanceBurnToken = burnToken.balanceOf(address(this));
ERC20Burnable(address(burnToken)).burn(balanceBurnToken);
// update records - set collected tokens to 0
collectedERC20ToBurn[collectedToken] = 0;
// collected tokens successfully swapped and burned => emit event
emit BoughtBackAndBurned(collectedToken, amount, address(burnToken), balanceBurnToken);
}
| function buyBackAndBurnERC20(address collectedToken) external whenNotPaused nonReentrant {
// check input parameter
require(collectedToken != address(0), 'BuyBackAndBurnV1: invalid token address');
// check how much of the given token is ready for burn
uint256 amount = collectedERC20ToBurn[collectedToken];
require(amount > 0, 'BuyBackAndBurnV1: no tokens to burn');
// register approval for router to spend collectedToken, if not already done
if (IERC20(collectedToken).allowance(address(this), address(router)) < amount) {
IERC20(collectedToken).approve(address(router), type(uint256).max);
}
// swap collected tokens to burn tokens using external DEX
uint256 burnAmount = router.tradeERC20(IERC20(collectedToken), burnToken, amount);
// burn all available burn tokens (swapped and directly collected))
uint256 balanceBurnToken = burnToken.balanceOf(address(this));
ERC20Burnable(address(burnToken)).burn(balanceBurnToken);
// update records - set collected tokens to 0
collectedERC20ToBurn[collectedToken] = 0;
// collected tokens successfully swapped and burned => emit event
emit BoughtBackAndBurned(collectedToken, amount, address(burnToken), balanceBurnToken);
}
| 20,292 |
62 | // StakeStart/ | event StakeStart(
| event StakeStart(
| 75,922 |
121 | // validates reserve ratio | modifier validReserveRatio(uint32 _ratio) {
require(_ratio > 0 && _ratio <= RATIO_RESOLUTION);
_;
}
| modifier validReserveRatio(uint32 _ratio) {
require(_ratio > 0 && _ratio <= RATIO_RESOLUTION);
_;
}
| 6,985 |
34 | // Refunds tokens for all voters / | function refundTokens(address to) public onlyOwner returns (bool) {
if(to != address(0)) {
return _refundTokens(to);
}
for(uint256 i = 0; i < voters.length; i++) {
_refundTokens(voters[i]);
}
return true;
}
| function refundTokens(address to) public onlyOwner returns (bool) {
if(to != address(0)) {
return _refundTokens(to);
}
for(uint256 i = 0; i < voters.length; i++) {
_refundTokens(voters[i]);
}
return true;
}
| 53,901 |
218 | // Modify vendor's name _vendorId The vendor id _name Then vendor name / | function updateVendorName(uint256 _vendorId, string _name)
public
| function updateVendorName(uint256 _vendorId, string _name)
public
| 48,068 |
406 | // TODO: grab LP Token decimals explicitly? | uint256 normalizedUnderlyerAmount =
lpTokenAmount.mul(virtualPrice).div(1e18);
uint256 underlyerAmount =
normalizedUnderlyerAmount.mul(10**uint256(decimals)).div(
10**uint256(18)
);
| uint256 normalizedUnderlyerAmount =
lpTokenAmount.mul(virtualPrice).div(1e18);
uint256 underlyerAmount =
normalizedUnderlyerAmount.mul(10**uint256(decimals)).div(
10**uint256(18)
);
| 8,600 |
14 | // pair.pairBase => tokenIn[] | mapping(address => address[]) pairMarginTokens;
| mapping(address => address[]) pairMarginTokens;
| 2,364 |
221 | // See {IERC721-getApproved}. / | function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
| function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
| 16,312 |
95 | // Given a tick and a token amount, calculates the amount of token received in exchange/tick Tick value used to calculate the quote/baseAmount Amount of token to be converted/baseToken Address of an ERC20 token contract used as the baseAmount denomination/quoteToken Address of an ERC20 token contract used as the quoteAmount denomination/ return quoteAmount Amount of quoteToken received for baseAmount of baseToken | function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
| function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
| 25,721 |
4 | // else the caller must have approved the token for the fill | ERC20(currency).safeTransferFrom(msg.sender, recipient, amount);
| ERC20(currency).safeTransferFrom(msg.sender, recipient, amount);
| 11,123 |
111 | // The currently in range liquidity available to the pool/This value has no relationship to the total liquidity across all ticks | function liquidity() external view returns (uint128);
| function liquidity() external view returns (uint128);
| 16,175 |
37 | // END FUNCTIONS RELATED TO EXTERNAL CONTRACT INTERACTIONS / | function implementsERC721() public pure returns (bool) {
return true;
}
| function implementsERC721() public pure returns (bool) {
return true;
}
| 27,833 |
34 | // To exclude division by zero There is a check for a non zero eend.allWhiteCollateral above Cell 26 | eend.whiteCoefficient = wdiv(eend.allBlackCollateral, eend.allWhiteCollateral);
| eend.whiteCoefficient = wdiv(eend.allBlackCollateral, eend.allWhiteCollateral);
| 9,321 |
54 | // ========== RESTRICTED FUNCTIONS ========== / | function addOwner(address _newOwner) external isAnOwner {
addOwnerShip(_newOwner);
}
| function addOwner(address _newOwner) external isAnOwner {
addOwnerShip(_newOwner);
}
| 22,038 |
11 | // Returns the current dynasty in the block store. return dynasty_ The current dynasty. / | function getCurrentDynasty() external view returns (uint256 dynasty_) {
dynasty_ = currentDynasty;
}
| function getCurrentDynasty() external view returns (uint256 dynasty_) {
dynasty_ = currentDynasty;
}
| 31,889 |
111 | // Internal func to get estimated Uniswap output from WETH to token trade / | ) internal view returns (uint256) {
uint256[] memory amountsOut = IUniswapV2Router02(_uniswap).getAmountsOut(_amountIn, _path);
return amountsOut[amountsOut.length - 1];
}
| ) internal view returns (uint256) {
uint256[] memory amountsOut = IUniswapV2Router02(_uniswap).getAmountsOut(_amountIn, _path);
return amountsOut[amountsOut.length - 1];
}
| 36,528 |
2 | // SwapFlashLoan | function MAX_BPS() external view returns (uint256);
function addLiquidity(uint256[] memory amounts, uint256 minToMint, uint256 deadline) external returns (uint256);
function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory);
function calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex) external view returns (uint256 availableTokenAmount);
function calculateSwap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx) external view returns (uint256);
function calculateTokenAmount(uint256[] memory amounts, bool deposit) external view returns (uint256);
function getA() external view returns (uint256);
function getAPrecise() external view returns (uint256);
function getAdminBalance(uint256 index) external view returns (uint256);
function getToken(uint8 index) external view returns (address);
| function MAX_BPS() external view returns (uint256);
function addLiquidity(uint256[] memory amounts, uint256 minToMint, uint256 deadline) external returns (uint256);
function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory);
function calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex) external view returns (uint256 availableTokenAmount);
function calculateSwap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx) external view returns (uint256);
function calculateTokenAmount(uint256[] memory amounts, bool deposit) external view returns (uint256);
function getA() external view returns (uint256);
function getAPrecise() external view returns (uint256);
function getAdminBalance(uint256 index) external view returns (uint256);
function getToken(uint8 index) external view returns (address);
| 26,914 |
16 | // Internal Functions for ERC20 standard logics / |
function _transfer(address from, address to, uint256 amount)
internal
returns (bool success)
|
function _transfer(address from, address to, uint256 amount)
internal
returns (bool success)
| 23,151 |
5 | // Check if a key exists in the registry _k The key to check / | function exists(uint16 _k) public view returns (bool) {
if (_k == 0) return false;
uint8 hIndex = uint8(_k >> 8);
uint8 lIndex = uint8(_k & 255);
uint8 hByte = hBytes[hIndex];
if (hByte == 0) {
return false;
}
if (lBytes.length <= hByte - 1) return false;
uint256 lByte = lBytes[hByte - 1];
if ((lByte & (uint(1) << lIndex)) == 0) {
return false;
}
return true;
}
| function exists(uint16 _k) public view returns (bool) {
if (_k == 0) return false;
uint8 hIndex = uint8(_k >> 8);
uint8 lIndex = uint8(_k & 255);
uint8 hByte = hBytes[hIndex];
if (hByte == 0) {
return false;
}
if (lBytes.length <= hByte - 1) return false;
uint256 lByte = lBytes[hByte - 1];
if ((lByte & (uint(1) << lIndex)) == 0) {
return false;
}
return true;
}
| 5,991 |
397 | // Gets the average rate of a CA currency./curr Currency Name./ return rate Average rate X 100(of last 3 days). | function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) {
if (curr == "DAI") {
DSValue ds = DSValue(daiFeedAddress);
rate = uint(ds.read()).div(uint(10) ** 16);
} else if (isIA) {
| function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) {
if (curr == "DAI") {
DSValue ds = DSValue(daiFeedAddress);
rate = uint(ds.read()).div(uint(10) ** 16);
} else if (isIA) {
| 33,450 |
60 | // CREDIT ACCOUNT |
string public constant CA_CONNECTED_CREDIT_MANAGER_ONLY = "CA1";
string public constant CA_FACTORY_ONLY = "CA2";
|
string public constant CA_CONNECTED_CREDIT_MANAGER_ONLY = "CA1";
string public constant CA_FACTORY_ONLY = "CA2";
| 30,382 |
65 | // use to save miner info | struct Miner{
uint256 time;
uint256 etherAmount;
bool isExist;
}
| struct Miner{
uint256 time;
uint256 etherAmount;
bool isExist;
}
| 48,304 |
123 | // Total debt issued for this specific collateral type | uint256 debtAmount; // [wad]
| uint256 debtAmount; // [wad]
| 40,580 |
89 | // How many active milestones have been created | uint256 public milestoneCount = 0;
bool public milestoningFinished = false;
constructor(
uint256 _openingTime,
uint256 _closingTime
)
TimedCrowdsale(_openingTime, _closingTime)
| uint256 public milestoneCount = 0;
bool public milestoningFinished = false;
constructor(
uint256 _openingTime,
uint256 _closingTime
)
TimedCrowdsale(_openingTime, _closingTime)
| 11,209 |
15 | // Read and write to persistent storage at a fraction of the cost./Solmate (https:github.com/Rari-Capital/solmate/blob/main/src/utils/SSTORE2.sol)/Modified from 0xSequence (https:github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol) | library SSTORE2 {
uint256 internal constant DATA_OFFSET = 1; // We skip the first byte as it's a STOP opcode to ensure the contract can't be called.
/*///////////////////////////////////////////////////////////////
WRITE LOGIC
//////////////////////////////////////////////////////////////*/
function write(bytes memory data) internal returns (address pointer) {
// Prefix the bytecode with a STOP opcode to ensure it cannot be called.
bytes memory runtimeCode = abi.encodePacked(hex'00', data);
bytes memory creationCode = abi.encodePacked(
//---------------------------------------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//---------------------------------------------------------------------------------------------------------------//
// 0x60 | 0x600B | PUSH1 11 | codeOffset //
// 0x59 | 0x59 | MSIZE | 0 codeOffset //
// 0x81 | 0x81 | DUP2 | codeOffset 0 codeOffset //
// 0x38 | 0x38 | CODESIZE | codeSize codeOffset 0 codeOffset //
// 0x03 | 0x03 | SUB | (codeSize - codeOffset) 0 codeOffset //
// 0x80 | 0x80 | DUP | (codeSize - codeOffset) (codeSize - codeOffset) 0 codeOffset //
// 0x92 | 0x92 | SWAP3 | codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //
// 0x59 | 0x59 | MSIZE | 0 codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //
// 0x39 | 0x39 | CODECOPY | 0 (codeSize - codeOffset) //
// 0xf3 | 0xf3 | RETURN | //
//---------------------------------------------------------------------------------------------------------------//
hex'60_0B_59_81_38_03_80_92_59_39_F3', // Returns all code in the contract except for the first 11 (0B in hex) bytes.
runtimeCode // The bytecode we want the contract to have after deployment. Capped at 1 byte less than the code size limit.
);
assembly {
// Deploy a new contract with the generated creation code.
// We start 32 bytes into the code to avoid copying the byte length.
pointer := create(0, add(creationCode, 32), mload(creationCode))
}
require(pointer != address(0), 'DEPLOYMENT_FAILED');
}
/*///////////////////////////////////////////////////////////////
READ LOGIC
//////////////////////////////////////////////////////////////*/
function read(address pointer) internal view returns (bytes memory) {
return readBytecode(pointer, DATA_OFFSET, pointer.code.length - DATA_OFFSET);
}
function read(address pointer, uint256 start) internal view returns (bytes memory) {
start += DATA_OFFSET;
return readBytecode(pointer, start, pointer.code.length - start);
}
function read(
address pointer,
uint256 start,
uint256 end
) internal view returns (bytes memory) {
start += DATA_OFFSET;
end += DATA_OFFSET;
require(pointer.code.length >= end, 'OUT_OF_BOUNDS');
return readBytecode(pointer, start, end - start);
}
/*///////////////////////////////////////////////////////////////
INTERNAL HELPER LOGIC
//////////////////////////////////////////////////////////////*/
function readBytecode(
address pointer,
uint256 start,
uint256 size
) private view returns (bytes memory data) {
assembly {
// Get a pointer to some free memory.
data := mload(0x40)
// Update the free memory pointer to prevent overriding our data.
// We use and(x, not(31)) as a cheaper equivalent to sub(x, mod(x, 32)).
// Adding 31 to size and running the result through the logic above ensures
// the memory pointer remains word-aligned, following the Solidity convention.
mstore(0x40, add(data, and(add(add(size, 32), 31), not(31))))
// Store the size of the data in the first 32 byte chunk of free memory.
mstore(data, size)
// Copy the code into memory right after the 32 bytes we used to store the size.
extcodecopy(pointer, add(data, 32), start, size)
}
}
} | library SSTORE2 {
uint256 internal constant DATA_OFFSET = 1; // We skip the first byte as it's a STOP opcode to ensure the contract can't be called.
/*///////////////////////////////////////////////////////////////
WRITE LOGIC
//////////////////////////////////////////////////////////////*/
function write(bytes memory data) internal returns (address pointer) {
// Prefix the bytecode with a STOP opcode to ensure it cannot be called.
bytes memory runtimeCode = abi.encodePacked(hex'00', data);
bytes memory creationCode = abi.encodePacked(
//---------------------------------------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//---------------------------------------------------------------------------------------------------------------//
// 0x60 | 0x600B | PUSH1 11 | codeOffset //
// 0x59 | 0x59 | MSIZE | 0 codeOffset //
// 0x81 | 0x81 | DUP2 | codeOffset 0 codeOffset //
// 0x38 | 0x38 | CODESIZE | codeSize codeOffset 0 codeOffset //
// 0x03 | 0x03 | SUB | (codeSize - codeOffset) 0 codeOffset //
// 0x80 | 0x80 | DUP | (codeSize - codeOffset) (codeSize - codeOffset) 0 codeOffset //
// 0x92 | 0x92 | SWAP3 | codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //
// 0x59 | 0x59 | MSIZE | 0 codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //
// 0x39 | 0x39 | CODECOPY | 0 (codeSize - codeOffset) //
// 0xf3 | 0xf3 | RETURN | //
//---------------------------------------------------------------------------------------------------------------//
hex'60_0B_59_81_38_03_80_92_59_39_F3', // Returns all code in the contract except for the first 11 (0B in hex) bytes.
runtimeCode // The bytecode we want the contract to have after deployment. Capped at 1 byte less than the code size limit.
);
assembly {
// Deploy a new contract with the generated creation code.
// We start 32 bytes into the code to avoid copying the byte length.
pointer := create(0, add(creationCode, 32), mload(creationCode))
}
require(pointer != address(0), 'DEPLOYMENT_FAILED');
}
/*///////////////////////////////////////////////////////////////
READ LOGIC
//////////////////////////////////////////////////////////////*/
function read(address pointer) internal view returns (bytes memory) {
return readBytecode(pointer, DATA_OFFSET, pointer.code.length - DATA_OFFSET);
}
function read(address pointer, uint256 start) internal view returns (bytes memory) {
start += DATA_OFFSET;
return readBytecode(pointer, start, pointer.code.length - start);
}
function read(
address pointer,
uint256 start,
uint256 end
) internal view returns (bytes memory) {
start += DATA_OFFSET;
end += DATA_OFFSET;
require(pointer.code.length >= end, 'OUT_OF_BOUNDS');
return readBytecode(pointer, start, end - start);
}
/*///////////////////////////////////////////////////////////////
INTERNAL HELPER LOGIC
//////////////////////////////////////////////////////////////*/
function readBytecode(
address pointer,
uint256 start,
uint256 size
) private view returns (bytes memory data) {
assembly {
// Get a pointer to some free memory.
data := mload(0x40)
// Update the free memory pointer to prevent overriding our data.
// We use and(x, not(31)) as a cheaper equivalent to sub(x, mod(x, 32)).
// Adding 31 to size and running the result through the logic above ensures
// the memory pointer remains word-aligned, following the Solidity convention.
mstore(0x40, add(data, and(add(add(size, 32), 31), not(31))))
// Store the size of the data in the first 32 byte chunk of free memory.
mstore(data, size)
// Copy the code into memory right after the 32 bytes we used to store the size.
extcodecopy(pointer, add(data, 32), start, size)
}
}
} | 8,637 |
35 | // Add to payee balance _payee The address of the payee to add. _shares The number of shares to add to the payee. / | function addToPayeeBalance(address token, address _payee, uint256 _shares) internal {
require(_payee != address(0));
require(_shares > 0);
require(shares[token][_payee] > 0);
shares[token][_payee] += _shares;
totalShares[token] += _shares;
}
| function addToPayeeBalance(address token, address _payee, uint256 _shares) internal {
require(_payee != address(0));
require(_shares > 0);
require(shares[token][_payee] > 0);
shares[token][_payee] += _shares;
totalShares[token] += _shares;
}
| 44,656 |
53 | // Set the current sell price in wei for one metadollar/priceInWei - is the amount in wei for one metadollar | function setSellPrice(uint256 priceInWei) isOwner {
require(priceInWei >= 0);
sellPrice = priceInWei;
}
| function setSellPrice(uint256 priceInWei) isOwner {
require(priceInWei >= 0);
sellPrice = priceInWei;
}
| 35,034 |
42 | // Select the second bit Solidity does not allow conversion of ints to bools, so we do it explicitly. | bool sendValue;
if ((flagByte & 0x40) > 0) { // 0x40 == 0b010000000;
sendValue = true;
}
| bool sendValue;
if ((flagByte & 0x40) > 0) { // 0x40 == 0b010000000;
sendValue = true;
}
| 15,493 |
29 | // external / | {
rewardDistribution = _rewardDistribution;
}
| {
rewardDistribution = _rewardDistribution;
}
| 25,535 |
0 | // Counter underflow is impossible as _burnCounter cannot be incremented more than `_currentIndex` times. | unchecked {
return ERC721SupplyStorage.layout().currentIndex - ERC721SupplyStorage.layout().burnCounter;
}
| unchecked {
return ERC721SupplyStorage.layout().currentIndex - ERC721SupplyStorage.layout().burnCounter;
}
| 10,845 |
11 | // The next free block on which a user can commence their unstake | uint256 public nextUnallocatedEpoch;
event JoinQueue(address exiter, uint256 amount);
event Withdrawal(address exiter, uint256 amount);
constructor(
address _TEMPLE,
uint256 _maxPerEpoch,
uint256 _maxPerAddress,
| uint256 public nextUnallocatedEpoch;
event JoinQueue(address exiter, uint256 amount);
event Withdrawal(address exiter, uint256 amount);
constructor(
address _TEMPLE,
uint256 _maxPerEpoch,
uint256 _maxPerAddress,
| 33,351 |
116 | // allows a keeper to activate/register themselves after bonding / | function activate() external {
require(bondings[msg.sender] != 0, "Keep3r::activate: bond first");
require(bondings[msg.sender] < now, "Keep3r::activate: still bonding");
if (!keepers[msg.sender]) {
firstSeen[msg.sender] = now;
}
keepers[msg.sender] = true;
totalBonded = totalBonded.add(pendingbonds[msg.sender]);
bonds[msg.sender] = bonds[msg.sender].add(pendingbonds[msg.sender]);
pendingbonds[msg.sender] = 0;
if (lastJob[msg.sender] == 0) {
lastJob[msg.sender] = now;
keeperList.push(msg.sender);
}
emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender]);
}
| function activate() external {
require(bondings[msg.sender] != 0, "Keep3r::activate: bond first");
require(bondings[msg.sender] < now, "Keep3r::activate: still bonding");
if (!keepers[msg.sender]) {
firstSeen[msg.sender] = now;
}
keepers[msg.sender] = true;
totalBonded = totalBonded.add(pendingbonds[msg.sender]);
bonds[msg.sender] = bonds[msg.sender].add(pendingbonds[msg.sender]);
pendingbonds[msg.sender] = 0;
if (lastJob[msg.sender] == 0) {
lastJob[msg.sender] = now;
keeperList.push(msg.sender);
}
emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender]);
}
| 57,132 |
23 | // address _addr = ECDSA.recover(hash, v, r, s); | address _addr = ecrecover(hash, v, r, s);
require(
ipfsSigners[_addr] == true,
string(
abi.encodePacked(
"Not an IPFS signer",
toAsciiString(_addr),
" ",
uriHash
| address _addr = ecrecover(hash, v, r, s);
require(
ipfsSigners[_addr] == true,
string(
abi.encodePacked(
"Not an IPFS signer",
toAsciiString(_addr),
" ",
uriHash
| 64,183 |
172 | // Minting Function | function batchSpawnAsset(address _to, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator {
uint256 _id;
uint256 _assetType;
for(uint i = 0; i < _assetIds.length; i++) {
_id = _assetIds[i];
_assetType = _assetTypes[i];
_createAsset(_to, _assetType, _id, _isAttached, address(0));
}
}
| function batchSpawnAsset(address _to, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator {
uint256 _id;
uint256 _assetType;
for(uint i = 0; i < _assetIds.length; i++) {
_id = _assetIds[i];
_assetType = _assetTypes[i];
_createAsset(_to, _assetType, _id, _isAttached, address(0));
}
}
| 52,107 |
11 | // 0x1e0 = offset to 2nd proof length of proofOutput is at s + 0x60 | mstore(0x220, 0xc0) // location of inputNotes
mstore(0x260, 0x00) // publicOwner is 0
mstore(0x280, 0x00) // publicValue is 0
mstore(0x2a0, calldataload(0x124))
| mstore(0x220, 0xc0) // location of inputNotes
mstore(0x260, 0x00) // publicOwner is 0
mstore(0x280, 0x00) // publicValue is 0
mstore(0x2a0, calldataload(0x124))
| 43,020 |
2 | // 配对合约set | EnumerableSet.AddressSet private _pairs;
| EnumerableSet.AddressSet private _pairs;
| 39,998 |
51 | // Insert before `prevId` as the head | self.nodes[_id].nextId = self.head;
self.nodes[self.head].prevId = _id;
self.head = _id;
| self.nodes[_id].nextId = self.head;
self.nodes[self.head].prevId = _id;
self.head = _id;
| 35,124 |
2 | // Tells the address of the implementation where every call will be delegated. return address of the implementation to which it will be delegated/ | function implementation() public view virtual returns (address);
| function implementation() public view virtual returns (address);
| 23,277 |
1 | // Destroys `amount` tokens from the caller, reducing the total supply. Claims RGT earned by `account` beforehand (so RariGovernanceTokenDistributor can continue distributing RGT considering the new RSPT balance of the caller). / | function burn(uint256 amount) external;
| function burn(uint256 amount) external;
| 8,988 |
4 | // getArtworkIDByTokenID use for getting artwork ID from token ID/_tokenId - the id of edition | function getArtworkIDByTokenID(
uint256 _tokenId
| function getArtworkIDByTokenID(
uint256 _tokenId
| 20,850 |
42 | // sha3("setFreezing(address,uint256,uint256,uint8)").slice(0,10) | bytes4 constant setFreezingSig = bytes4(0x51c3b8a6);
| bytes4 constant setFreezingSig = bytes4(0x51c3b8a6);
| 8,181 |
62 | // Reduce burn amount further by the mm burn rate, as insurance for cases when not liquidated in time | marginToBurn = marginRemaining.mulDown(
params.get(Risk.Parameters.MaintenanceMarginBurnRate)
);
marginRemaining -= marginToBurn;
| marginToBurn = marginRemaining.mulDown(
params.get(Risk.Parameters.MaintenanceMarginBurnRate)
);
marginRemaining -= marginToBurn;
| 26,319 |
73 | // ``` | * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
| * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
| 68 |
32 | // Internal functions //Adds a new transaction to the transaction mapping, if transaction does not exist yet./destination Transaction target address./value Transaction ether value./data Transaction data payload./ return Returns transaction ID. | function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
| function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
| 14,641 |
3 | // Modulo is a number of equiprobable outcomes in a game:- 2 for coin flip- 6 for dice- 66 = 36 for double dice- 100 for etheroll- 37 for rouletteetc. It's called so because 256-bit entropy is treated like a huge integer and the remainder of its division by modulo is considered bet outcome. | uint constant MAX_MODULO = 100;
| uint constant MAX_MODULO = 100;
| 37,595 |
50 | // Returns the confirmation status of a transaction./transactionId Transaction ID./ return Confirmation status. | function isConfirmed(uint transactionId)
public
constant
returns (bool)
| function isConfirmed(uint transactionId)
public
constant
returns (bool)
| 48,892 |
116 | // check if we're buy side or sell side in a swap; if buy side apply buy side taxes; if sell side then apply those taxes; duh | bool buySide = false;
if (sender == address(uniswapV2Pair)) {
buySide = true;
}
| bool buySide = false;
if (sender == address(uniswapV2Pair)) {
buySide = true;
}
| 34,074 |
81 | // Reward token to current reward rate mapping | mapping(address => uint256) public rewardRates;
| mapping(address => uint256) public rewardRates;
| 28,863 |
3 | // Verifies the signature for a given ForwardRequest./req The ForwardRequest structure./signature The signature provided by the signer./ return A boolean indicating whether the signature is valid. | function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {
address signer = _hashTypedDataV4(
keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))
).recover(signature);
return _nonces[req.from] == req.nonce && signer == req.from;
}
| function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) {
address signer = _hashTypedDataV4(
keccak256(abi.encode(_TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)))
).recover(signature);
return _nonces[req.from] == req.nonce && signer == req.from;
}
| 20,855 |
891 | // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. | FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
| FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
| 17,629 |
498 | // Set of predictions | function startPredictions(uint256[][] memory info, string[][] memory name) public onlyOwner {
//Info list of [Id, time, bonus time], name list of [event name, option names(3)]
require(info.length == name.length, "Not same length");
for (uint i = 0; i < info.length; i++){
startPrediction(info[i][0], name[i][0], name[i][1], name[i][2], name[i][3], info[i][1], info[i][2]);
}
}
| function startPredictions(uint256[][] memory info, string[][] memory name) public onlyOwner {
//Info list of [Id, time, bonus time], name list of [event name, option names(3)]
require(info.length == name.length, "Not same length");
for (uint i = 0; i < info.length; i++){
startPrediction(info[i][0], name[i][0], name[i][1], name[i][2], name[i][3], info[i][1], info[i][2]);
}
}
| 23,944 |
59 | // TODO Delete the hash(es) being invalidated? | nInvalidatedHashes += 1;
| nInvalidatedHashes += 1;
| 4,492 |
52 | // An address authorized to call the creditCardMint function. | address creditCardMintAddress;
| address creditCardMintAddress;
| 21,238 |
72 | // Use this when reporting a known error from the price oracle or a non-upgradeable collaborator Using Oracle in name because we already inherit a `fail` function from ErrorReporter.sol via Exponential.sol / | function failOracle(
address asset,
| function failOracle(
address asset,
| 10,418 |
17 | // Allows GeoJam Dev Team to change the Project ID this contract is linked with. _projectId New Project ID to link with. Meant to be used in case an error is made when initializing contract. / | function updateProjectId(uint256 _projectId) external onlyOwner {
projectId = _projectId;
}
| function updateProjectId(uint256 _projectId) external onlyOwner {
projectId = _projectId;
}
| 13,709 |
0 | // PROOF UTILITY TOKEN (PRF)TOKEN INFOPRF TOKEN MARKETINGPRF TOKEN MECHANICS / | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
event Swap(address indexed account, uint256 amount);
event Swaped(address indexed account, uint256 amount);
}
| interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
event Swap(address indexed account, uint256 amount);
event Swaped(address indexed account, uint256 amount);
}
| 46,164 |
601 | // Skips on-going collateral auction. See 2./Has to be performed before global debt is fixed/vault Address of the Vault/auctionId Id of the collateral auction the skip | function skipAuction(address vault, uint256 auctionId) external override {
if (debt != 0) revert Tenebrae__skipAuction_debtNotZero();
(address _collateralAuction, , , ) = limes.vaults(vault);
ICollateralAuction collateralAuction = ICollateralAuction(_collateralAuction);
(, uint256 rate, , ) = codex.vaults(vault);
(, uint256 debt_, uint256 collateralToSell, , uint256 tokenId, address user, , ) = collateralAuction.auctions(
auctionId
);
codex.createUnbackedDebt(address(aer), address(aer), debt_);
collateralAuction.cancelAuction(auctionId);
uint256 normalDebt = wdiv(debt_, rate);
if (!(int256(collateralToSell) >= 0 && int256(normalDebt) >= 0)) revert Tenebrae__skipAuction_overflow();
codex.confiscateCollateralAndDebt(
vault,
tokenId,
user,
address(this),
address(aer),
int256(collateralToSell),
int256(normalDebt)
);
emit SkipAuction(auctionId, vault, tokenId, user, debt_, collateralToSell, normalDebt);
}
| function skipAuction(address vault, uint256 auctionId) external override {
if (debt != 0) revert Tenebrae__skipAuction_debtNotZero();
(address _collateralAuction, , , ) = limes.vaults(vault);
ICollateralAuction collateralAuction = ICollateralAuction(_collateralAuction);
(, uint256 rate, , ) = codex.vaults(vault);
(, uint256 debt_, uint256 collateralToSell, , uint256 tokenId, address user, , ) = collateralAuction.auctions(
auctionId
);
codex.createUnbackedDebt(address(aer), address(aer), debt_);
collateralAuction.cancelAuction(auctionId);
uint256 normalDebt = wdiv(debt_, rate);
if (!(int256(collateralToSell) >= 0 && int256(normalDebt) >= 0)) revert Tenebrae__skipAuction_overflow();
codex.confiscateCollateralAndDebt(
vault,
tokenId,
user,
address(this),
address(aer),
int256(collateralToSell),
int256(normalDebt)
);
emit SkipAuction(auctionId, vault, tokenId, user, debt_, collateralToSell, normalDebt);
}
| 62,337 |
121 | // Modify the allowance. | _approve(owner, spender, newAllowance);
success = true;
| _approve(owner, spender, newAllowance);
success = true;
| 67,209 |
45 | // See {IPool-activate}. / | function activate(address account, uint256 validatorIndex) external override {
uint256 activatedAmount = _activateAmount(
account,
validatorIndex,
activatedValidators.mul(pendingValidatorsLimit.add(1e4))
);
stakedEthToken.mint(account, activatedAmount);
}
| function activate(address account, uint256 validatorIndex) external override {
uint256 activatedAmount = _activateAmount(
account,
validatorIndex,
activatedValidators.mul(pendingValidatorsLimit.add(1e4))
);
stakedEthToken.mint(account, activatedAmount);
}
| 67,421 |
37 | // ERC2771Context overrides | function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) {
return ERC2771Context._msgSender();
}
| function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) {
return ERC2771Context._msgSender();
}
| 5,141 |
56 | // Claim all bought HQX for all approved addresses / | function claimAll() onlyOwner whenNotPaused {
for (uint32 i = 0; i < receiversCount; i++) {
address receiver = tokenReceivers[i];
if (approved[receiver] && tokens[receiver] > 0) {
claimFor(receiver);
}
}
}
| function claimAll() onlyOwner whenNotPaused {
for (uint32 i = 0; i < receiversCount; i++) {
address receiver = tokenReceivers[i];
if (approved[receiver] && tokens[receiver] > 0) {
claimFor(receiver);
}
}
}
| 44,971 |
10 | // Sets the maxNonVotingPeriod Admin function to set maxNonVotingPeriod newPeriod_ The new maxNonVotingPeriod (in sec). Must be greater than 90 days and lower than 2 years. RESTRICTION: Admin only. / | function setMaxNonVotingPeriod(uint256 newPeriod_) external;
| function setMaxNonVotingPeriod(uint256 newPeriod_) external;
| 40,900 |
214 | // See {IGovernor-castVoteBySig}. / | function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
| function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
| 1,665 |
112 | // Decrease the amount of tokens that an owner has allowed to a spender.spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by. / | function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
| function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
| 1,614 |
107 | // Executes deposit operation with delegatecall. _amount: amount to be deposited _provider: address of provider to be used / | function _deposit(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
| function _deposit(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
| 39,548 |
5 | // ========== RESTRICTED FUNCTIONS - OWNER ========== / | function setKeeper(address newKeeper) external onlyOwner {
keeper = newKeeper;
}
| function setKeeper(address newKeeper) external onlyOwner {
keeper = newKeeper;
}
| 23,236 |
2 | // Mints liquidity from V3 Pool _tickLower Lower tick _tickUpper Upper tick _amount0 Amount of token0 _amount1 Amount of token1 _payer Address which is adding the liquidityreturn amount0 Amount of token0 deployed to the poolreturn amount1 Amount of token1 deployed to the pool / | function mintLiquidity(
int24 _tickLower,
int24 _tickUpper,
uint256 _amount0,
uint256 _amount1,
address _payer
| function mintLiquidity(
int24 _tickLower,
int24 _tickUpper,
uint256 _amount0,
uint256 _amount1,
address _payer
| 35,621 |
14 | // TimedCrowdsale Crowdsale accepting contributions only within a time frame. / | contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 private _closingTime;
/**
* Event for crowdsale extending
* @param newClosingTime new closing time
* @param prevClosingTime old closing time
*/
event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime);
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "TimedCrowdsale: not open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor (uint256 openingTime, uint256 closingTime) public {
// solhint-disable-next-line not-rely-on-time
require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time");
// solhint-disable-next-line max-line-length
require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time");
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns (uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns (uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view {
super._preValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Extend crowdsale.
* @param newClosingTime Crowdsale closing time
*/
function _extendTime(uint256 newClosingTime) internal {
require(!hasClosed(), "TimedCrowdsale: already closed");
// solhint-disable-next-line max-line-length
require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time");
emit TimedCrowdsaleExtended(_closingTime, newClosingTime);
_closingTime = newClosingTime;
}
}
| contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 private _closingTime;
/**
* Event for crowdsale extending
* @param newClosingTime new closing time
* @param prevClosingTime old closing time
*/
event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime);
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "TimedCrowdsale: not open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor (uint256 openingTime, uint256 closingTime) public {
// solhint-disable-next-line not-rely-on-time
require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time");
// solhint-disable-next-line max-line-length
require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time");
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns (uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns (uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period.
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view {
super._preValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Extend crowdsale.
* @param newClosingTime Crowdsale closing time
*/
function _extendTime(uint256 newClosingTime) internal {
require(!hasClosed(), "TimedCrowdsale: already closed");
// solhint-disable-next-line max-line-length
require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time");
emit TimedCrowdsaleExtended(_closingTime, newClosingTime);
_closingTime = newClosingTime;
}
}
| 3,797 |
97 | // Create group/ Can be called only by contract owner//_groupName group name/_priority group priority// return code | function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) {
require(_groupName != bytes32(0));
if (isGroupExists(_groupName)) {
return USER_MANAGER_GROUP_ALREADY_EXIST;
}
uint _groupsCount = groupsCount.add(1);
groupName2index[_groupName] = _groupsCount;
index2groupName[_groupsCount] = _groupName;
groupName2group[_groupName] = Group(_groupName, _priority, 0);
groupsCount = _groupsCount;
GroupCreated(_groupName);
return OK;
}
| function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) {
require(_groupName != bytes32(0));
if (isGroupExists(_groupName)) {
return USER_MANAGER_GROUP_ALREADY_EXIST;
}
uint _groupsCount = groupsCount.add(1);
groupName2index[_groupName] = _groupsCount;
index2groupName[_groupsCount] = _groupName;
groupName2group[_groupName] = Group(_groupName, _priority, 0);
groupsCount = _groupsCount;
GroupCreated(_groupName);
return OK;
}
| 2,714 |
2 | // Allows someone to deposit into the yield source without receiving any shares.The deposited token will be the same as token()/ This allows anyone to distribute tokens among the share holders. | function sponsor(uint256 amount) external;
| function sponsor(uint256 amount) external;
| 5,983 |
8 | // get user counter | function getIncrement() public view returns(uint) {
return counter[msg.sender];
}
| function getIncrement() public view returns(uint) {
return counter[msg.sender];
}
| 23,148 |
97 | // Execute the call | CallLib.execute(call, start_gas, msg.sender, getOverhead(), getExtraGas());
| CallLib.execute(call, start_gas, msg.sender, getOverhead(), getExtraGas());
| 16,917 |
32 | // Assigns a new address to act as the COO. Only available to the current COO or CEO./_newCOO The address of the new COO | function setCOO(address _newCOO) external {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
require(_newCOO != address(0));
cooAddress = _newCOO;
}
| function setCOO(address _newCOO) external {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
require(_newCOO != address(0));
cooAddress = _newCOO;
}
| 63,110 |
35 | // reset daily Lotto | balDailyLotto=0;
dailyLottoPlayers.length=0;
| balDailyLotto=0;
dailyLottoPlayers.length=0;
| 23,295 |
34 | // Version of signature should be 27 or 28, but 0 and 1 are also possible versions | if (v < 27) {
v += 27;
}
| if (v < 27) {
v += 27;
}
| 22,519 |
169 | // ensure account have escrow migration pending | require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0");
require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending");
| require(totalEscrowedAccountBalance[addressToMigrate] > 0, "Address escrow balance is 0");
require(totalBalancePendingMigration[addressToMigrate] > 0, "No escrow migration pending");
| 40,562 |
18 | // Set the converter for liquidation _converter The new converter / | function setConverter(address _converter) external onlyGovernor {
require(_converter != address(0), "empty converter");
converter = IConverter(_converter);
require(converter.source() == address(collateral), "mismatch source token");
require(converter.destination() == address(underlying), "mismatch destination token");
}
| function setConverter(address _converter) external onlyGovernor {
require(_converter != address(0), "empty converter");
converter = IConverter(_converter);
require(converter.source() == address(collateral), "mismatch source token");
require(converter.destination() == address(underlying), "mismatch destination token");
}
| 21,862 |
67 | // Define if fee calculation must be skipped for a given trade. By default (false) fee must not be skipped. | mapping(address => mapping(address => bool)) public mustSkipFee;
| mapping(address => mapping(address => bool)) public mustSkipFee;
| 22,665 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.