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 |
|---|---|---|---|---|
15 | // Ensure that the buyer has not already been a buyer of the product | require(buyerStatus[product_id][address(msg.sender)] == PurchaseState.Default);
| require(buyerStatus[product_id][address(msg.sender)] == PurchaseState.Default);
| 1,195 |
201 | // Grant the contract deployer the default admin role: it will be able to grant and revoke any roles | _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
| _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
| 16,019 |
105 | // Update the given pool's BDO allocation point. Can only be called by the owner. | function set(uint256 _pid, uint256 _allocPoint) public onlyOwner {
massUpdatePools();
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
| function set(uint256 _pid, uint256 _allocPoint) public onlyOwner {
massUpdatePools();
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
| 17,781 |
34 | // Ensure that the encoded principal token address is valid | require(principalTokenAddress != address(0));
| require(principalTokenAddress != address(0));
| 31,432 |
227 | // Gets the integration for the module with the passed in name. Validates that the address is not empty / | function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
| function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
| 4,406 |
258 | // returns the block number when the order being last modified. | function orderBlockNumber(bytes32 _orderID) external view returns (uint256) {
return orders[_orderID].blockNumber;
}
| function orderBlockNumber(bytes32 _orderID) external view returns (uint256) {
return orders[_orderID].blockNumber;
}
| 78,821 |
219 | // Allows the owner to change the spending fee percentage/feePercentage The new fee percentage | function setFeePercentage(uint256 feePercentage) external onlyOwner {
awooFeePercentage = feePercentage; // We're intentionally allowing the fee percentage to be set to 0%, incase no fees need to be collected
}
| function setFeePercentage(uint256 feePercentage) external onlyOwner {
awooFeePercentage = feePercentage; // We're intentionally allowing the fee percentage to be set to 0%, incase no fees need to be collected
}
| 39,668 |
244 | // supply of all properly locked BOOSTED balances at the given epoch | function totalSupplyAtEpoch(uint256 _epoch)
external
view
returns (uint256 supply)
| function totalSupplyAtEpoch(uint256 _epoch)
external
view
returns (uint256 supply)
| 41,702 |
25 | // generate the uniswap pair path of token -> WHT | address[] memory path = new address[](2);
path[0] = address(this);
path[1] = getBasePairAddr();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
| address[] memory path = new address[](2);
path[0] = address(this);
path[1] = getBasePairAddr();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
| 26,328 |
217 | // Returns the `TokenOwnership` struct at `tokenId` without reverting. If the `tokenId` is out of bounds:- `addr` = `address(0)`- `startTimestamp` = `0`- `burned` = `false`- `extraData` = `0` If the `tokenId` is burned:- `addr` = `<Address of owner before token was burned>`- `startTimestamp` = `<Timestamp when token was burned>`- `burned = `true`- `extraData` = `<Extra data when token was burned>` Otherwise:- `addr` = `<Address of owner>`- `startTimestamp` = `<Timestamp of start of ownership>`- `burned = `false`- `extraData` = `<Extra data at start of ownership>` / | function explicitOwnershipOf(uint256 tokenId) public view override returns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
ownership = _ownershipAt(tokenId);
if (ownership.burned) {
return ownership;
}
return _ownershipOf(tokenId);
}
| function explicitOwnershipOf(uint256 tokenId) public view override returns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
ownership = _ownershipAt(tokenId);
if (ownership.burned) {
return ownership;
}
return _ownershipOf(tokenId);
}
| 29,080 |
7 | // Evaluate current balance_address Address of investor return Payout amount/ | function getUserBalance(address _address) view public returns (uint256) {
Investor storage investor = investors[_address];
uint percent = getPhasePercent();
uint256 differentTime = now.sub(investor.paymentTime).div(step);
uint256 differentPercent = investor.deposit.mul(percent).div(1000);
uint256 payout = differentPercent.mul(differentTime).div(288);
return payout;
}
| function getUserBalance(address _address) view public returns (uint256) {
Investor storage investor = investors[_address];
uint percent = getPhasePercent();
uint256 differentTime = now.sub(investor.paymentTime).div(step);
uint256 differentPercent = investor.deposit.mul(percent).div(1000);
uint256 payout = differentPercent.mul(differentTime).div(288);
return payout;
}
| 14,856 |
69 | // probably will never have more than 256 functions from one facet contract | require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
| require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
| 34,016 |
5 | // User struct for storing user related data. / | struct User {
string pollId;
address voter;
}
| struct User {
string pollId;
address voter;
}
| 21,260 |
15 | // Owner of account approves the transfer of an amount to another account | mapping (address => mapping (address => uint256)) allowed;
event Debug(string message, address addr, uint256 number);
| mapping (address => mapping (address => uint256)) allowed;
event Debug(string message, address addr, uint256 number);
| 3,243 |
3 | // value of _baseLiability | function baseLiability() external view returns (uint256);
| function baseLiability() external view returns (uint256);
| 11,398 |
54 | // check whether the managerID is exist or not | function managerIDExist (uint _ManagerID) public view returns (bool) {
for (uint c = 0; c < ManagerList.length; c++) {
if(ManagerList[c] == _ManagerID)
return true;
}
return false;
}
| function managerIDExist (uint _ManagerID) public view returns (bool) {
for (uint c = 0; c < ManagerList.length; c++) {
if(ManagerList[c] == _ManagerID)
return true;
}
return false;
}
| 51,863 |
10 | // The actual amount of collateral provided to the protocol. This amount will be multiplied by the precision scalar if the token has less than 18 d.p / | uint256 internal totalSupplied;
| uint256 internal totalSupplied;
| 48,518 |
30 | // SafeBlocks @date 30/04/2018/ | contract SafeBlocksFirewall {
event EnquireResult(address sourceAddress, bool approved, address token, uint amount, address destination, uint blockNumber, string msg);
event PolicyChanged(address contractAddress, address destination, address tokenAdress, uint limit);
event ConfigurationChanged(address sender, address newConfiguration, string message);
address owner;
address rulesOwner;
address proxyContract;
bool verbose;
mapping(address /*contractId*/ => LimitsRule) limitsRule;
mapping(address /*contractId*/ => uint) lastSuccessPerContract;
mapping(address /*contractId*/ => mapping(address /*destination*/ => uint)) lastSuccessPerContractPerDestination;
mapping(address /*contractId*/ => bool) blockAll;
mapping(address /*contractId*/ => bool) enforceBypass;
mapping(address /*contractId*/ => mapping(address /*destination*/ => mapping(address /*tokenAddress*/ => uint256 /*limit*/))) customerRules;
struct LimitsRule {
uint perAddressLimit;
uint globalLimit;
}
constructor() public {
owner = msg.sender;
verbose = true;
}
//*************************************** modifiers ****************************************
modifier onlyContractOwner {
require(owner == msg.sender, "You are not allowed to run this function, required role: Contract-Owner");
_;
}
modifier onlyRulesOwner {
require(rulesOwner == msg.sender, "You are not allowed to run this function, required role: Rules-Owner");
_;
}
modifier onlyProxy {
require(proxyContract == msg.sender, "You are not allowed to run this function, required role: SafeBlocks-Proxy");
_;
}
//*************************************** setters ****************************************
function setProxyContract(address _proxy)
onlyContractOwner
public {
proxyContract = _proxy;
emit ConfigurationChanged(msg.sender, _proxy, "a new proxy contract address has been assigned");
}
function setRulesOwner(address _rulesOwner)
public
onlyContractOwner {
rulesOwner = _rulesOwner;
emit ConfigurationChanged(msg.sender, _rulesOwner, "a new Rules-Owner has been assigned");
}
function setVerbose(bool _verbose)
onlyContractOwner
public {
verbose = _verbose;
emit ConfigurationChanged(msg.sender, msg.sender, "a new Verbose-Mode has been assigned");
}
//*************************************** firewall functionality ****************************************
function setBypassPerContract(address _contractAddress, bool _bypass)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractAddress, address(0), address(0), _bypass ? 1 : 0);
enforceBypass[_contractAddress] = _bypass;
//to maintain default true we check if the enforce is set to *false*
}
function setBlockAllPerContract(address _contractId, bool _isBlocked)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, address(0), address(0), 0);
blockAll[_contractId] = _isBlocked;
}
function setPerAddressLimit(address _contractId, uint _limit)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, address(0), address(0), _limit);
limitsRule[_contractId].perAddressLimit = _limit;
}
function setGlobalLimit(address _contractId, uint _limit)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, address(0), address(0), _limit);
limitsRule[_contractId].globalLimit = _limit;
}
function addRule(address _contractId, address _destination, address _token, uint256 _tokenLimit)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, _destination, _token, _tokenLimit);
customerRules[_contractId][_destination][_token] = _tokenLimit;
}
function removeRule(address _contractId, address _destination, address _token)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, _destination, _token, 0);
delete customerRules[_contractId][_destination][_token];
}
function allowTransaction(address _contractAddress, uint _amount, address _destination, address _token)
public
onlyProxy
returns (bool){
if (enforceBypass[_contractAddress]) {
if (verbose) emit EnquireResult(_contractAddress, true, _token, _amount, _destination, block.number, "1");
return true;
}
if (blockAll[_contractAddress]) {//if block all activated for this contract, deny all
if (verbose) emit EnquireResult(_contractAddress, false, _token, _amount, _destination, block.number, "2");
return false;
}
uint256 limit = customerRules[_contractAddress][_destination][_token];
uint256 anyDestinationLimit = customerRules[_contractAddress][0x0][_token];
if (limit == 0 && anyDestinationLimit == 0) {//no rules ?? deny all
if (verbose) emit EnquireResult(_contractAddress, false, _token, _amount, _destination, block.number, "3");
return false;
}
if (anyDestinationLimit > 0 && limit == 0) {
limit = anyDestinationLimit;
}
if (_amount <= limit) {
if (limitsRule[_contractAddress].perAddressLimit == 0 && limitsRule[_contractAddress].globalLimit == 0) {
if (verbose) emit EnquireResult(_contractAddress, true, _token, _amount, _destination, block.number, "4");
return true;
}
// no need to record and check rate limits;
if (checkTimeFrameLimit(_contractAddress)) {
if (checkAddressLimit(_contractAddress, _destination)) {
lastSuccessPerContract[_contractAddress] = block.number;
lastSuccessPerContractPerDestination[_contractAddress][_destination] = block.number;
if (verbose) emit EnquireResult(_contractAddress, true, _token, _amount, _destination, block.number, "5");
return true;
}
}
}
if (verbose) emit EnquireResult(_contractAddress, false, _token, _amount, _destination, block.number, "6");
return false;
}
//*************************************** private ****************************************
function checkAddressLimit(address _contractId, address _destination)
private
view
returns (bool){
if (lastSuccessPerContractPerDestination[_contractId][_destination] > 0) {
if (block.number - lastSuccessPerContractPerDestination[_contractId][_destination] < limitsRule[_contractId].perAddressLimit) {
return false;
}
}
return true;
}
function checkTimeFrameLimit(address _contractId)
private
view
returns (bool) {
if (lastSuccessPerContract[_contractId] > 0) {
if (block.number - lastSuccessPerContract[_contractId] < limitsRule[_contractId].globalLimit) {
return false;
}
}
return true;
}
//*************************************** getters ****************************************
function getLimits(address _contractId)
public
view
onlyContractOwner
returns (uint, uint){
return (limitsRule[_contractId].perAddressLimit, limitsRule[_contractId].globalLimit);
}
function getLastSuccessPerContract(address _contractId)
public
view
onlyContractOwner
returns (uint){
return (lastSuccessPerContract[_contractId]);
}
function getLastSuccessPerContractPerDestination(address _contractId, address _destination)
public
view
onlyContractOwner
returns (uint){
return (lastSuccessPerContractPerDestination[_contractId][_destination]);
}
function getBlockAll(address _contractId)
public
view
onlyContractOwner
returns (bool){
return (blockAll[_contractId]);
}
function getEnforceBypass(address _contractId)
public
view
onlyContractOwner
returns (bool){
return (enforceBypass[_contractId]);
}
function getCustomerRules(address _contractId, address _destination, address _tokenAddress)
public
view
onlyContractOwner
returns (uint256){
return (customerRules[_contractId][_destination][_tokenAddress]);
}
}
| contract SafeBlocksFirewall {
event EnquireResult(address sourceAddress, bool approved, address token, uint amount, address destination, uint blockNumber, string msg);
event PolicyChanged(address contractAddress, address destination, address tokenAdress, uint limit);
event ConfigurationChanged(address sender, address newConfiguration, string message);
address owner;
address rulesOwner;
address proxyContract;
bool verbose;
mapping(address /*contractId*/ => LimitsRule) limitsRule;
mapping(address /*contractId*/ => uint) lastSuccessPerContract;
mapping(address /*contractId*/ => mapping(address /*destination*/ => uint)) lastSuccessPerContractPerDestination;
mapping(address /*contractId*/ => bool) blockAll;
mapping(address /*contractId*/ => bool) enforceBypass;
mapping(address /*contractId*/ => mapping(address /*destination*/ => mapping(address /*tokenAddress*/ => uint256 /*limit*/))) customerRules;
struct LimitsRule {
uint perAddressLimit;
uint globalLimit;
}
constructor() public {
owner = msg.sender;
verbose = true;
}
//*************************************** modifiers ****************************************
modifier onlyContractOwner {
require(owner == msg.sender, "You are not allowed to run this function, required role: Contract-Owner");
_;
}
modifier onlyRulesOwner {
require(rulesOwner == msg.sender, "You are not allowed to run this function, required role: Rules-Owner");
_;
}
modifier onlyProxy {
require(proxyContract == msg.sender, "You are not allowed to run this function, required role: SafeBlocks-Proxy");
_;
}
//*************************************** setters ****************************************
function setProxyContract(address _proxy)
onlyContractOwner
public {
proxyContract = _proxy;
emit ConfigurationChanged(msg.sender, _proxy, "a new proxy contract address has been assigned");
}
function setRulesOwner(address _rulesOwner)
public
onlyContractOwner {
rulesOwner = _rulesOwner;
emit ConfigurationChanged(msg.sender, _rulesOwner, "a new Rules-Owner has been assigned");
}
function setVerbose(bool _verbose)
onlyContractOwner
public {
verbose = _verbose;
emit ConfigurationChanged(msg.sender, msg.sender, "a new Verbose-Mode has been assigned");
}
//*************************************** firewall functionality ****************************************
function setBypassPerContract(address _contractAddress, bool _bypass)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractAddress, address(0), address(0), _bypass ? 1 : 0);
enforceBypass[_contractAddress] = _bypass;
//to maintain default true we check if the enforce is set to *false*
}
function setBlockAllPerContract(address _contractId, bool _isBlocked)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, address(0), address(0), 0);
blockAll[_contractId] = _isBlocked;
}
function setPerAddressLimit(address _contractId, uint _limit)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, address(0), address(0), _limit);
limitsRule[_contractId].perAddressLimit = _limit;
}
function setGlobalLimit(address _contractId, uint _limit)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, address(0), address(0), _limit);
limitsRule[_contractId].globalLimit = _limit;
}
function addRule(address _contractId, address _destination, address _token, uint256 _tokenLimit)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, _destination, _token, _tokenLimit);
customerRules[_contractId][_destination][_token] = _tokenLimit;
}
function removeRule(address _contractId, address _destination, address _token)
onlyRulesOwner
public {
if (verbose) emit PolicyChanged(_contractId, _destination, _token, 0);
delete customerRules[_contractId][_destination][_token];
}
function allowTransaction(address _contractAddress, uint _amount, address _destination, address _token)
public
onlyProxy
returns (bool){
if (enforceBypass[_contractAddress]) {
if (verbose) emit EnquireResult(_contractAddress, true, _token, _amount, _destination, block.number, "1");
return true;
}
if (blockAll[_contractAddress]) {//if block all activated for this contract, deny all
if (verbose) emit EnquireResult(_contractAddress, false, _token, _amount, _destination, block.number, "2");
return false;
}
uint256 limit = customerRules[_contractAddress][_destination][_token];
uint256 anyDestinationLimit = customerRules[_contractAddress][0x0][_token];
if (limit == 0 && anyDestinationLimit == 0) {//no rules ?? deny all
if (verbose) emit EnquireResult(_contractAddress, false, _token, _amount, _destination, block.number, "3");
return false;
}
if (anyDestinationLimit > 0 && limit == 0) {
limit = anyDestinationLimit;
}
if (_amount <= limit) {
if (limitsRule[_contractAddress].perAddressLimit == 0 && limitsRule[_contractAddress].globalLimit == 0) {
if (verbose) emit EnquireResult(_contractAddress, true, _token, _amount, _destination, block.number, "4");
return true;
}
// no need to record and check rate limits;
if (checkTimeFrameLimit(_contractAddress)) {
if (checkAddressLimit(_contractAddress, _destination)) {
lastSuccessPerContract[_contractAddress] = block.number;
lastSuccessPerContractPerDestination[_contractAddress][_destination] = block.number;
if (verbose) emit EnquireResult(_contractAddress, true, _token, _amount, _destination, block.number, "5");
return true;
}
}
}
if (verbose) emit EnquireResult(_contractAddress, false, _token, _amount, _destination, block.number, "6");
return false;
}
//*************************************** private ****************************************
function checkAddressLimit(address _contractId, address _destination)
private
view
returns (bool){
if (lastSuccessPerContractPerDestination[_contractId][_destination] > 0) {
if (block.number - lastSuccessPerContractPerDestination[_contractId][_destination] < limitsRule[_contractId].perAddressLimit) {
return false;
}
}
return true;
}
function checkTimeFrameLimit(address _contractId)
private
view
returns (bool) {
if (lastSuccessPerContract[_contractId] > 0) {
if (block.number - lastSuccessPerContract[_contractId] < limitsRule[_contractId].globalLimit) {
return false;
}
}
return true;
}
//*************************************** getters ****************************************
function getLimits(address _contractId)
public
view
onlyContractOwner
returns (uint, uint){
return (limitsRule[_contractId].perAddressLimit, limitsRule[_contractId].globalLimit);
}
function getLastSuccessPerContract(address _contractId)
public
view
onlyContractOwner
returns (uint){
return (lastSuccessPerContract[_contractId]);
}
function getLastSuccessPerContractPerDestination(address _contractId, address _destination)
public
view
onlyContractOwner
returns (uint){
return (lastSuccessPerContractPerDestination[_contractId][_destination]);
}
function getBlockAll(address _contractId)
public
view
onlyContractOwner
returns (bool){
return (blockAll[_contractId]);
}
function getEnforceBypass(address _contractId)
public
view
onlyContractOwner
returns (bool){
return (enforceBypass[_contractId]);
}
function getCustomerRules(address _contractId, address _destination, address _tokenAddress)
public
view
onlyContractOwner
returns (uint256){
return (customerRules[_contractId][_destination][_tokenAddress]);
}
}
| 37,076 |
190 | // Notifies the contract that reward has been added to be given. _reward uint Only ownercan call it Increases duration of rewards / | function notifyRewardAmount(uint256 _reward)
external
onlyOwner
updateReward(address(0))
| function notifyRewardAmount(uint256 _reward)
external
onlyOwner
updateReward(address(0))
| 26,816 |
37 | // Is there a contract with meta _meta. _hashData the hash of the vulnerability data / | function haveHashData(bytes32 _hashData)
internal
view
returns (bool exists)
| function haveHashData(bytes32 _hashData)
internal
view
returns (bool exists)
| 43,944 |
83 | // adding to whitelist has been disabled forever: | canWhitelist = false;
| canWhitelist = false;
| 3,189 |
46 | // contracts/interfaces/IStakeLocker.sol/ pragma solidity 0.6.11; // import "../token/interfaces/IStakeLockerFDT.sol"; / | interface IStakeLocker is IStakeLockerFDT {
function stakeDate(address) external returns (uint256);
function stake(uint256) external;
function unstake(uint256) external;
function pull(address, uint256) external;
function setAllowlist(address, bool) external;
function openStakeLockerToPublic() external;
function openToPublic() external view returns (bool);
function allowed(address) external view returns (bool);
function updateLosses(uint256) external;
function intendToUnstake() external;
function unstakeCooldown(address) external view returns (uint256);
function lockupPeriod() external view returns (uint256);
function stakeAsset() external view returns (address);
function liquidityAsset() external view returns (address);
function pool() external view returns (address);
function setLockupPeriod(uint256) external;
function cancelUnstake() external;
function increaseCustodyAllowance(address, uint256) external;
function transferByCustodian(address, address, uint256) external;
function pause() external;
function unpause() external;
function isUnstakeAllowed(address) external view returns (bool);
function isReceiveAllowed(uint256) external view returns (bool);
}
| interface IStakeLocker is IStakeLockerFDT {
function stakeDate(address) external returns (uint256);
function stake(uint256) external;
function unstake(uint256) external;
function pull(address, uint256) external;
function setAllowlist(address, bool) external;
function openStakeLockerToPublic() external;
function openToPublic() external view returns (bool);
function allowed(address) external view returns (bool);
function updateLosses(uint256) external;
function intendToUnstake() external;
function unstakeCooldown(address) external view returns (uint256);
function lockupPeriod() external view returns (uint256);
function stakeAsset() external view returns (address);
function liquidityAsset() external view returns (address);
function pool() external view returns (address);
function setLockupPeriod(uint256) external;
function cancelUnstake() external;
function increaseCustodyAllowance(address, uint256) external;
function transferByCustodian(address, address, uint256) external;
function pause() external;
function unpause() external;
function isUnstakeAllowed(address) external view returns (bool);
function isReceiveAllowed(uint256) external view returns (bool);
}
| 55,886 |
5 | // Withdraw ERC-20 tokens from user account to the current wallet address amount the amount of tokens being withdrawn / | function withdraw(uint256 amount) external {
require(accounts[msg.sender].balance >= amount, "Insufficient funds");
require(plushApps.getAppExists(msg.sender) == false, "The wallet is a controller");
accounts[msg.sender].balance -= amount;
require(plush.transfer(msg.sender, amount), "Transaction error");
emit Withdrawn(msg.sender, amount);
}
| function withdraw(uint256 amount) external {
require(accounts[msg.sender].balance >= amount, "Insufficient funds");
require(plushApps.getAppExists(msg.sender) == false, "The wallet is a controller");
accounts[msg.sender].balance -= amount;
require(plush.transfer(msg.sender, amount), "Transaction error");
emit Withdrawn(msg.sender, amount);
}
| 8,938 |
78 | // The share left for the contract. This is an approximate value. The real value will be whatever is leftover after each winner is paid their share. | uint256 approxRevenueShare = g.bets[_loser] * revenueBps / 10_000;
bool isSent;
{
uint256 totalWinnings = g.bets[_loser] - burnShare - approxRevenueShare;
for (uint16 i = 0; i < winners.length; i++) {
uint256 winnings = totalWinnings * g.bets[winnersPlayerIndex[i]] / winningBetTotal;
isSent = bettingToken.transfer(winners[i], g.bets[winnersPlayerIndex[i]] + winnings);
| uint256 approxRevenueShare = g.bets[_loser] * revenueBps / 10_000;
bool isSent;
{
uint256 totalWinnings = g.bets[_loser] - burnShare - approxRevenueShare;
for (uint16 i = 0; i < winners.length; i++) {
uint256 winnings = totalWinnings * g.bets[winnersPlayerIndex[i]] / winningBetTotal;
isSent = bettingToken.transfer(winners[i], g.bets[winnersPlayerIndex[i]] + winnings);
| 43,015 |
19 | // emits an event when a call action is executed | event CallExecuted(address indexed from, address indexed to, bytes data);
| event CallExecuted(address indexed from, address indexed to, bytes data);
| 33,797 |
79 | // Update order status and fill amount, packing struct values. [denominator: 15 bytes] [numerator: 15 bytes] [isCancelled: 1 byte] [isValidated: 1 byte] | sstore(
orderStatusSlot,
or(
OrderStatus_ValidatedAndNotCancelled,
or(
shl(OrderStatus_filledNumerator_offset, filledNumerator),
shl(OrderStatus_filledDenominator_offset, denominator)
)
)
)
| sstore(
orderStatusSlot,
or(
OrderStatus_ValidatedAndNotCancelled,
or(
shl(OrderStatus_filledNumerator_offset, filledNumerator),
shl(OrderStatus_filledDenominator_offset, denominator)
)
)
)
| 17,136 |
38 | // ______ __ ____ ______ __ ____ ______ __ __ /\== \ /\ \ /\_\_\_\ /\___\ /\ \ /\ "-./\ /\__ \ /\ "-.\ \\ \_-/ \ \ \\/_/\_\/_\ \__\ \ \ \____\ \ \-./\ \\ \ \/\ \\ \ \-.\\ \_\\ \_\ /\_\/\_\\ \_____\\ \_____\\ \_\ \ \_\\ \_____\\ \_\\"\_\\/_/ \/_/ \/_/\/_/ \/_____/ \/_____/ \/_/\/_/ \/_____/ \/_/ \/_/ /Generation 1 Pixelmon NFTs/delta devs (https:www.twitter.com/deltadevelopers) | contract Pixelmon is ERC721, Ownable {
using Strings for uint256;
/*///////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Determines the order of the species for each tokenId, mechanism for choosing starting index explained post mint, explanation hash: acb427e920bde46de95103f14b8e57798a603abcf87ff9d4163e5f61c6a56881.
uint constant public provenanceHash = 0x9912e067bd3802c3b007ce40b6c125160d2ccb5352d199e20c092fdc17af8057;
/// @dev Sole receiver of collected contract funds, and receiver of 330 Pixelmon in the constructor.
address constant gnosisSafeAddress = 0xF6BD9Fc094F7aB74a846E5d82a822540EE6c6971;
/// @dev 7750, plus 330 for the Pixelmon Gnosis Safe
uint constant auctionSupply = 7750 + 330;
/// @dev The offsets are the tokenIds that the corresponding evolution stage will begin minting at.
uint constant secondEvolutionOffset = 10005;
uint constant thirdEvolutionOffset = secondEvolutionOffset + 4013;
uint constant fourthEvolutionOffset = thirdEvolutionOffset + 1206;
/*///////////////////////////////////////////////////////////////
EVOLUTIONARY STORAGE
//////////////////////////////////////////////////////////////*/
/// @dev The next tokenID to be minted for each of the evolution stages
uint secondEvolutionSupply = 0;
uint thirdEvolutionSupply = 0;
uint fourthEvolutionSupply = 0;
/// @notice The address of the contract permitted to mint evolved Pixelmon.
address public serumContract;
/// @notice Returns true if the user is on the mintlist, if they have not already minted.
mapping(address => bool) public mintlisted;
/*///////////////////////////////////////////////////////////////
AUCTION STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice Starting price of the auction.
uint256 constant public auctionStartPrice = 3 ether;
/// @notice Unix Timestamp of the start of the auction.
/// @dev Monday, February 7th 2022, 13:00:00 converted to 1644256800 (GMT -5)
uint256 constant public auctionStartTime = 1644256800;
/// @notice Current mintlist price, which will be updated after the end of the auction phase.
/// @dev We started with signatures, then merkle tree, but landed on mapping to reduce USER gas fees.
uint256 public mintlistPrice = 0.75 ether;
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public baseURI;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Deploys the contract, minting 330 Pixelmon to the Gnosis Safe and setting the initial metadata URI.
constructor(string memory _baseURI) ERC721("Pixelmon", "PXLMN") {
baseURI = _baseURI;
unchecked {
balanceOf[gnosisSafeAddress] += 330;
totalSupply += 330;
for (uint256 i = 0; i < 330; i++) {
ownerOf[i] = gnosisSafeAddress;
emit Transfer(address(0), gnosisSafeAddress, i);
}
}
}
/*///////////////////////////////////////////////////////////////
METADATA LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to set the metadata URI.
/// @param _baseURI The new metadata URI.
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
function tokenURI(uint256 id) public view override returns (string memory) {
return string(abi.encodePacked(baseURI, id.toString()));
}
/*///////////////////////////////////////////////////////////////
DUTCH AUCTION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Calculates the auction price with the accumulated rate deduction since the auction's begin
/// @return The auction price at the current time, or 0 if the deductions are greater than the auction's start price.
function validCalculatedTokenPrice() private view returns (uint) {
uint priceReduction = ((block.timestamp - auctionStartTime) / 10 minutes) * 0.1 ether;
return auctionStartPrice >= priceReduction ? (auctionStartPrice - priceReduction) : 0;
}
/// @notice Calculates the current dutch auction price, given accumulated rate deductions and a minimum price.
/// @return The current dutch auction price
function getCurrentTokenPrice() public view returns (uint256) {
return max(validCalculatedTokenPrice(), 0.2 ether);
}
/// @notice Purchases a Pixelmon NFT in the dutch auction
/// @param mintingTwo True if the user is minting two Pixelmon, otherwise false.
/// @dev balanceOf is fine, team is aware and accepts that transferring out and repurchasing can be done, even by contracts.
function auction(bool mintingTwo) public payable {
if(block.timestamp < auctionStartTime || block.timestamp > auctionStartTime + 1 days) revert AuctionNotStarted();
uint count = mintingTwo ? 2 : 1;
uint price = getCurrentTokenPrice();
if(totalSupply + count > auctionSupply) revert MintedOut();
if(balanceOf[msg.sender] + count > 2) revert MintingTooMany();
if(msg.value < price * count) revert ValueTooLow();
mintingTwo ? _mintTwo(msg.sender) : _mint(msg.sender, totalSupply);
}
/// @notice Mints two Pixelmons to an address
/// @param to Receiver of the two newly minted NFTs
/// @dev errors taken from super._mint
function _mintTwo(address to) internal {
require(to != address(0), "INVALID_RECIPIENT");
require(ownerOf[totalSupply] == address(0), "ALREADY_MINTED");
uint currentId = totalSupply;
/// @dev unchecked because no arithmetic can overflow
unchecked {
totalSupply += 2;
balanceOf[to] += 2;
ownerOf[currentId] = to;
ownerOf[currentId + 1] = to;
emit Transfer(address(0), to, currentId);
emit Transfer(address(0), to, currentId + 1);
}
}
/*///////////////////////////////////////////////////////////////
MINTLIST MINT LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to set the price of the mintlist. To be called before uploading the mintlist.
/// @param price The price in wei of a Pixelmon NFT to be purchased from the mintlist supply.
function setMintlistPrice(uint256 price) public onlyOwner {
mintlistPrice = price;
}
/// @notice Allows the contract deployer to add a single address to the mintlist.
/// @param user Address to be added to the mintlist.
function mintlistUser(address user) public onlyOwner {
mintlisted[user] = true;
}
/// @notice Allows the contract deployer to add a list of addresses to the mintlist.
/// @param users Addresses to be added to the mintlist.
function mintlistUsers(address[] calldata users) public onlyOwner {
for (uint256 i = 0; i < users.length; i++) {
mintlisted[users[i]] = true;
}
}
/// @notice Purchases a Pixelmon NFT from the mintlist supply
/// @dev We do not check if auction is over because the mintlist will be uploaded after the auction.
function mintlistMint() public payable {
if(totalSupply >= secondEvolutionOffset) revert MintedOut();
if(!mintlisted[msg.sender]) revert NotMintlisted();
if(msg.value < mintlistPrice) revert ValueTooLow();
mintlisted[msg.sender] = false;
_mint(msg.sender, totalSupply);
}
/// @notice Withdraws collected funds to the Gnosis Safe address
function withdraw() public onlyOwner {
(bool success, ) = gnosisSafeAddress.call{value: address(this).balance}("");
require(success);
}
/*///////////////////////////////////////////////////////////////
ROLL OVER LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to airdrop Pixelmon to a list of addresses, in case the auction doesn't mint out
/// @param addresses Array of addresses to receive Pixelmon
function rollOverPixelmons(address[] calldata addresses) public onlyOwner {
if(totalSupply + addresses.length > secondEvolutionOffset) revert MintedOut();
for (uint256 i = 0; i < addresses.length; i++) {
_mint(msg.sender, totalSupply);
}
}
/*///////////////////////////////////////////////////////////////
EVOLUTIONARY LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Sets the address of the contract permitted to call mintEvolvedPixelmon
/// @param _serumContract The address of the EvolutionSerum contract
function setSerumContract(address _serumContract) public onlyOwner {
serumContract = _serumContract;
}
/// @notice Mints an evolved Pixelmon
/// @param receiver Receiver of the evolved Pixelmon
/// @param evolutionStage The evolution (2-4) that the Pixelmon is undergoing
function mintEvolvedPixelmon(address receiver, uint evolutionStage) public payable {
if(msg.sender != serumContract) revert UnauthorizedEvolution();
if (evolutionStage == 2) {
if(secondEvolutionSupply >= 4013) revert MintedOut();
_mint(receiver, secondEvolutionOffset + secondEvolutionSupply);
unchecked {
secondEvolutionSupply++;
}
} else if (evolutionStage == 3) {
if(thirdEvolutionSupply >= 1206) revert MintedOut();
_mint(receiver, thirdEvolutionOffset + thirdEvolutionSupply);
unchecked {
thirdEvolutionSupply++;
}
} else if (evolutionStage == 4) {
if(fourthEvolutionSupply >= 33) revert MintedOut();
_mint(receiver, fourthEvolutionOffset + fourthEvolutionSupply);
unchecked {
fourthEvolutionSupply++;
}
} else {
revert UnknownEvolution();
}
}
/*///////////////////////////////////////////////////////////////
UTILS
//////////////////////////////////////////////////////////////*/
/// @notice Returns the greater of two numbers.
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
}
| contract Pixelmon is ERC721, Ownable {
using Strings for uint256;
/*///////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Determines the order of the species for each tokenId, mechanism for choosing starting index explained post mint, explanation hash: acb427e920bde46de95103f14b8e57798a603abcf87ff9d4163e5f61c6a56881.
uint constant public provenanceHash = 0x9912e067bd3802c3b007ce40b6c125160d2ccb5352d199e20c092fdc17af8057;
/// @dev Sole receiver of collected contract funds, and receiver of 330 Pixelmon in the constructor.
address constant gnosisSafeAddress = 0xF6BD9Fc094F7aB74a846E5d82a822540EE6c6971;
/// @dev 7750, plus 330 for the Pixelmon Gnosis Safe
uint constant auctionSupply = 7750 + 330;
/// @dev The offsets are the tokenIds that the corresponding evolution stage will begin minting at.
uint constant secondEvolutionOffset = 10005;
uint constant thirdEvolutionOffset = secondEvolutionOffset + 4013;
uint constant fourthEvolutionOffset = thirdEvolutionOffset + 1206;
/*///////////////////////////////////////////////////////////////
EVOLUTIONARY STORAGE
//////////////////////////////////////////////////////////////*/
/// @dev The next tokenID to be minted for each of the evolution stages
uint secondEvolutionSupply = 0;
uint thirdEvolutionSupply = 0;
uint fourthEvolutionSupply = 0;
/// @notice The address of the contract permitted to mint evolved Pixelmon.
address public serumContract;
/// @notice Returns true if the user is on the mintlist, if they have not already minted.
mapping(address => bool) public mintlisted;
/*///////////////////////////////////////////////////////////////
AUCTION STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice Starting price of the auction.
uint256 constant public auctionStartPrice = 3 ether;
/// @notice Unix Timestamp of the start of the auction.
/// @dev Monday, February 7th 2022, 13:00:00 converted to 1644256800 (GMT -5)
uint256 constant public auctionStartTime = 1644256800;
/// @notice Current mintlist price, which will be updated after the end of the auction phase.
/// @dev We started with signatures, then merkle tree, but landed on mapping to reduce USER gas fees.
uint256 public mintlistPrice = 0.75 ether;
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public baseURI;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Deploys the contract, minting 330 Pixelmon to the Gnosis Safe and setting the initial metadata URI.
constructor(string memory _baseURI) ERC721("Pixelmon", "PXLMN") {
baseURI = _baseURI;
unchecked {
balanceOf[gnosisSafeAddress] += 330;
totalSupply += 330;
for (uint256 i = 0; i < 330; i++) {
ownerOf[i] = gnosisSafeAddress;
emit Transfer(address(0), gnosisSafeAddress, i);
}
}
}
/*///////////////////////////////////////////////////////////////
METADATA LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to set the metadata URI.
/// @param _baseURI The new metadata URI.
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
function tokenURI(uint256 id) public view override returns (string memory) {
return string(abi.encodePacked(baseURI, id.toString()));
}
/*///////////////////////////////////////////////////////////////
DUTCH AUCTION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Calculates the auction price with the accumulated rate deduction since the auction's begin
/// @return The auction price at the current time, or 0 if the deductions are greater than the auction's start price.
function validCalculatedTokenPrice() private view returns (uint) {
uint priceReduction = ((block.timestamp - auctionStartTime) / 10 minutes) * 0.1 ether;
return auctionStartPrice >= priceReduction ? (auctionStartPrice - priceReduction) : 0;
}
/// @notice Calculates the current dutch auction price, given accumulated rate deductions and a minimum price.
/// @return The current dutch auction price
function getCurrentTokenPrice() public view returns (uint256) {
return max(validCalculatedTokenPrice(), 0.2 ether);
}
/// @notice Purchases a Pixelmon NFT in the dutch auction
/// @param mintingTwo True if the user is minting two Pixelmon, otherwise false.
/// @dev balanceOf is fine, team is aware and accepts that transferring out and repurchasing can be done, even by contracts.
function auction(bool mintingTwo) public payable {
if(block.timestamp < auctionStartTime || block.timestamp > auctionStartTime + 1 days) revert AuctionNotStarted();
uint count = mintingTwo ? 2 : 1;
uint price = getCurrentTokenPrice();
if(totalSupply + count > auctionSupply) revert MintedOut();
if(balanceOf[msg.sender] + count > 2) revert MintingTooMany();
if(msg.value < price * count) revert ValueTooLow();
mintingTwo ? _mintTwo(msg.sender) : _mint(msg.sender, totalSupply);
}
/// @notice Mints two Pixelmons to an address
/// @param to Receiver of the two newly minted NFTs
/// @dev errors taken from super._mint
function _mintTwo(address to) internal {
require(to != address(0), "INVALID_RECIPIENT");
require(ownerOf[totalSupply] == address(0), "ALREADY_MINTED");
uint currentId = totalSupply;
/// @dev unchecked because no arithmetic can overflow
unchecked {
totalSupply += 2;
balanceOf[to] += 2;
ownerOf[currentId] = to;
ownerOf[currentId + 1] = to;
emit Transfer(address(0), to, currentId);
emit Transfer(address(0), to, currentId + 1);
}
}
/*///////////////////////////////////////////////////////////////
MINTLIST MINT LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to set the price of the mintlist. To be called before uploading the mintlist.
/// @param price The price in wei of a Pixelmon NFT to be purchased from the mintlist supply.
function setMintlistPrice(uint256 price) public onlyOwner {
mintlistPrice = price;
}
/// @notice Allows the contract deployer to add a single address to the mintlist.
/// @param user Address to be added to the mintlist.
function mintlistUser(address user) public onlyOwner {
mintlisted[user] = true;
}
/// @notice Allows the contract deployer to add a list of addresses to the mintlist.
/// @param users Addresses to be added to the mintlist.
function mintlistUsers(address[] calldata users) public onlyOwner {
for (uint256 i = 0; i < users.length; i++) {
mintlisted[users[i]] = true;
}
}
/// @notice Purchases a Pixelmon NFT from the mintlist supply
/// @dev We do not check if auction is over because the mintlist will be uploaded after the auction.
function mintlistMint() public payable {
if(totalSupply >= secondEvolutionOffset) revert MintedOut();
if(!mintlisted[msg.sender]) revert NotMintlisted();
if(msg.value < mintlistPrice) revert ValueTooLow();
mintlisted[msg.sender] = false;
_mint(msg.sender, totalSupply);
}
/// @notice Withdraws collected funds to the Gnosis Safe address
function withdraw() public onlyOwner {
(bool success, ) = gnosisSafeAddress.call{value: address(this).balance}("");
require(success);
}
/*///////////////////////////////////////////////////////////////
ROLL OVER LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to airdrop Pixelmon to a list of addresses, in case the auction doesn't mint out
/// @param addresses Array of addresses to receive Pixelmon
function rollOverPixelmons(address[] calldata addresses) public onlyOwner {
if(totalSupply + addresses.length > secondEvolutionOffset) revert MintedOut();
for (uint256 i = 0; i < addresses.length; i++) {
_mint(msg.sender, totalSupply);
}
}
/*///////////////////////////////////////////////////////////////
EVOLUTIONARY LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Sets the address of the contract permitted to call mintEvolvedPixelmon
/// @param _serumContract The address of the EvolutionSerum contract
function setSerumContract(address _serumContract) public onlyOwner {
serumContract = _serumContract;
}
/// @notice Mints an evolved Pixelmon
/// @param receiver Receiver of the evolved Pixelmon
/// @param evolutionStage The evolution (2-4) that the Pixelmon is undergoing
function mintEvolvedPixelmon(address receiver, uint evolutionStage) public payable {
if(msg.sender != serumContract) revert UnauthorizedEvolution();
if (evolutionStage == 2) {
if(secondEvolutionSupply >= 4013) revert MintedOut();
_mint(receiver, secondEvolutionOffset + secondEvolutionSupply);
unchecked {
secondEvolutionSupply++;
}
} else if (evolutionStage == 3) {
if(thirdEvolutionSupply >= 1206) revert MintedOut();
_mint(receiver, thirdEvolutionOffset + thirdEvolutionSupply);
unchecked {
thirdEvolutionSupply++;
}
} else if (evolutionStage == 4) {
if(fourthEvolutionSupply >= 33) revert MintedOut();
_mint(receiver, fourthEvolutionOffset + fourthEvolutionSupply);
unchecked {
fourthEvolutionSupply++;
}
} else {
revert UnknownEvolution();
}
}
/*///////////////////////////////////////////////////////////////
UTILS
//////////////////////////////////////////////////////////////*/
/// @notice Returns the greater of two numbers.
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
}
| 47,932 |
28 | // AirSwap Converter: Convert Fee Tokens / | contract Converter is Ownable, ReentrancyGuard, TokenPaymentSplitter {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public wETH;
address public swapToToken;
address public immutable uniRouter;
uint256 public triggerFee;
mapping(address => address[]) private tokenPathMapping;
event ConvertAndTransfer(
address triggerAccount,
address swapFromToken,
address swapToToken,
uint256 amountTokenFrom,
uint256 amountTokenTo,
address[] recievedAddresses
);
event DrainTo(address[] tokens, address dest);
constructor(
address _wETH,
address _swapToToken,
address _uniRouter,
uint256 _triggerFee,
address[] memory _payees,
uint256[] memory _shares
) TokenPaymentSplitter(_payees, _shares) {
wETH = _wETH;
swapToToken = _swapToToken;
uniRouter = _uniRouter;
setTriggerFee(_triggerFee);
}
/**
* @dev Set a new address for WETH.
**/
function setWETH(address _swapWETH) public onlyOwner {
require(_swapWETH != address(0), "MUST_BE_VALID_ADDRESS");
wETH = _swapWETH;
}
/**
* @dev Set a new token to swap to (e.g., stabletoken).
**/
function setSwapToToken(address _swapToToken) public onlyOwner {
require(_swapToToken != address(0), "MUST_BE_VALID_ADDRESS");
swapToToken = _swapToToken;
}
/**
* @dev Set a new fee (perentage 0 - 100) for calling the ConvertAndTransfer function.
*/
function setTriggerFee(uint256 _triggerFee) public onlyOwner {
require(_triggerFee <= 100, "FEE_TOO_HIGH");
triggerFee = _triggerFee;
}
/**
* @dev Set a new Uniswap router path for a token.
*/
function setTokenPath(address _token, address[] memory _tokenPath)
public
onlyOwner
{
uint256 pathLength = _tokenPath.length;
for (uint256 i = 0; i < pathLength; i++) {
tokenPathMapping[_token].push(_tokenPath[i]);
}
}
/**
* @dev Converts an token in the contract to the SwapToToken and transfers to payees.
* @param _swapFromToken The token to be swapped from.
* @param _amountOutMin The amount to be swapped and distributed.
*/
function convertAndTransfer(address _swapFromToken, uint256 _amountOutMin)
public
onlyOwner
nonReentrant
{
// Checks that at least 1 payee is set to recieve converted token.
require(_payees.length >= 1, "PAYEES_MUST_BE_SET");
// Calls the balanceOf function from the to be converted token.
uint256 tokenBalance = _balanceOfErc20(_swapFromToken);
// Checks that the converted token is currently present in the contract.
require(tokenBalance > 0, "NO_BALANCE_TO_CONVERT");
// Approve token for AMM usage.
_approveErc20(_swapFromToken, tokenBalance);
// Read or set the path for AMM.
if (_swapFromToken != swapToToken) {
address[] memory path;
if (tokenPathMapping[_swapFromToken].length > 0) {
path = getTokenPath(_swapFromToken);
} else {
tokenPathMapping[_swapFromToken].push(_swapFromToken);
tokenPathMapping[_swapFromToken].push(wETH);
if (swapToToken != wETH) {
tokenPathMapping[_swapFromToken].push(swapToToken);
}
path = getTokenPath(_swapFromToken);
}
// Calls the swap function from the on-chain AMM to swap token from fee pool into reward token.
IUniswapV2Router02(uniRouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenBalance,
_amountOutMin,
path,
address(this),
block.timestamp
);
}
// Calls the balanceOf function from the reward token to get the new balance post-swap.
uint256 newTokenBalance = _balanceOfErc20(swapToToken);
// Calculates trigger reward amount and transfers to msg.sender.
uint256 triggerFeeAmount = newTokenBalance.mul(triggerFee).div(100);
_transferErc20(msg.sender, swapToToken, triggerFeeAmount);
// Transfers remaining amount to reward payee address(es).
uint256 totalPayeeAmount = newTokenBalance.sub(triggerFeeAmount);
for (uint256 i = 0; i < _payees.length; i++) {
uint256 payeeAmount =
(totalPayeeAmount.mul(_shares[_payees[i]])).div(_totalShares);
_transferErc20(_payees[i], swapToToken, payeeAmount);
}
emit ConvertAndTransfer(
msg.sender,
_swapFromToken,
swapToToken,
tokenBalance,
totalPayeeAmount,
_payees
);
}
/**
* @dev Drains funds from provided list of tokens
* @param _transferTo Address of the recipient.
* @param _tokens List of tokens to transfer from the contract
*/
function drainTo(address _transferTo, address[] calldata _tokens)
public
onlyOwner
{
for (uint256 i = 0; i < _tokens.length; i++) {
uint256 balance = _balanceOfErc20(_tokens[i]);
if (balance > 0) {
_transferErc20(_transferTo, _tokens[i], balance);
}
}
emit DrainTo(_tokens, _transferTo);
}
/**
* @dev Add a recipient to receive payouts from the consolidateFeeToken function.
* @param _account Address of the recipient.
* @param _shares Amount of shares to determine th proportion of payout received.
*/
function addPayee(address _account, uint256 _shares) public onlyOwner {
_addPayee(_account, _shares);
}
/**
* @dev Remove a recipient from receiving payouts from the consolidateFeeToken function.
* @param _account Address of the recipient.
* @param _index Index number of the recipient in the array of recipients.
*/
function removePayee(address _account, uint256 _index) public onlyOwner {
_removePayee(_account, _index);
}
/**
* @dev View Uniswap router path for a token.
*/
function getTokenPath(address _token)
public
view
onlyOwner
returns (address[] memory)
{
return tokenPathMapping[_token];
}
/**
* @dev Internal function to approve ERC20 for AMM calls.
* @param _tokenToApprove Address of ERC20 to approve.
* @param _amount Amount of ERC20 to be approved.
*
* */
function _approveErc20(address _tokenToApprove, uint256 _amount) internal {
require(
IERC20(_tokenToApprove).approve(address(uniRouter), _amount),
"APPROVE_FAILED"
);
}
/**
* @dev Internal function to transfer ERC20 held in the contract.
* @param _recipient Address to receive ERC20.
* @param _tokenContract Address of the ERC20.
* @param _transferAmount Amount or ERC20 to be transferred.
*
* */
function _transferErc20(
address _recipient,
address _tokenContract,
uint256 _transferAmount
) internal {
IERC20(_tokenContract).safeTransfer(_recipient, _transferAmount);
}
/**
* @dev Internal function to call balanceOf on ERC20.
* @param _tokenToBalanceOf Address of ERC20 to call.
*
* */
function _balanceOfErc20(address _tokenToBalanceOf)
internal
view
returns (uint256)
{
IERC20 erc;
erc = IERC20(_tokenToBalanceOf);
uint256 tokenBalance = erc.balanceOf(address(this));
return tokenBalance;
}
}
| contract Converter is Ownable, ReentrancyGuard, TokenPaymentSplitter {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public wETH;
address public swapToToken;
address public immutable uniRouter;
uint256 public triggerFee;
mapping(address => address[]) private tokenPathMapping;
event ConvertAndTransfer(
address triggerAccount,
address swapFromToken,
address swapToToken,
uint256 amountTokenFrom,
uint256 amountTokenTo,
address[] recievedAddresses
);
event DrainTo(address[] tokens, address dest);
constructor(
address _wETH,
address _swapToToken,
address _uniRouter,
uint256 _triggerFee,
address[] memory _payees,
uint256[] memory _shares
) TokenPaymentSplitter(_payees, _shares) {
wETH = _wETH;
swapToToken = _swapToToken;
uniRouter = _uniRouter;
setTriggerFee(_triggerFee);
}
/**
* @dev Set a new address for WETH.
**/
function setWETH(address _swapWETH) public onlyOwner {
require(_swapWETH != address(0), "MUST_BE_VALID_ADDRESS");
wETH = _swapWETH;
}
/**
* @dev Set a new token to swap to (e.g., stabletoken).
**/
function setSwapToToken(address _swapToToken) public onlyOwner {
require(_swapToToken != address(0), "MUST_BE_VALID_ADDRESS");
swapToToken = _swapToToken;
}
/**
* @dev Set a new fee (perentage 0 - 100) for calling the ConvertAndTransfer function.
*/
function setTriggerFee(uint256 _triggerFee) public onlyOwner {
require(_triggerFee <= 100, "FEE_TOO_HIGH");
triggerFee = _triggerFee;
}
/**
* @dev Set a new Uniswap router path for a token.
*/
function setTokenPath(address _token, address[] memory _tokenPath)
public
onlyOwner
{
uint256 pathLength = _tokenPath.length;
for (uint256 i = 0; i < pathLength; i++) {
tokenPathMapping[_token].push(_tokenPath[i]);
}
}
/**
* @dev Converts an token in the contract to the SwapToToken and transfers to payees.
* @param _swapFromToken The token to be swapped from.
* @param _amountOutMin The amount to be swapped and distributed.
*/
function convertAndTransfer(address _swapFromToken, uint256 _amountOutMin)
public
onlyOwner
nonReentrant
{
// Checks that at least 1 payee is set to recieve converted token.
require(_payees.length >= 1, "PAYEES_MUST_BE_SET");
// Calls the balanceOf function from the to be converted token.
uint256 tokenBalance = _balanceOfErc20(_swapFromToken);
// Checks that the converted token is currently present in the contract.
require(tokenBalance > 0, "NO_BALANCE_TO_CONVERT");
// Approve token for AMM usage.
_approveErc20(_swapFromToken, tokenBalance);
// Read or set the path for AMM.
if (_swapFromToken != swapToToken) {
address[] memory path;
if (tokenPathMapping[_swapFromToken].length > 0) {
path = getTokenPath(_swapFromToken);
} else {
tokenPathMapping[_swapFromToken].push(_swapFromToken);
tokenPathMapping[_swapFromToken].push(wETH);
if (swapToToken != wETH) {
tokenPathMapping[_swapFromToken].push(swapToToken);
}
path = getTokenPath(_swapFromToken);
}
// Calls the swap function from the on-chain AMM to swap token from fee pool into reward token.
IUniswapV2Router02(uniRouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenBalance,
_amountOutMin,
path,
address(this),
block.timestamp
);
}
// Calls the balanceOf function from the reward token to get the new balance post-swap.
uint256 newTokenBalance = _balanceOfErc20(swapToToken);
// Calculates trigger reward amount and transfers to msg.sender.
uint256 triggerFeeAmount = newTokenBalance.mul(triggerFee).div(100);
_transferErc20(msg.sender, swapToToken, triggerFeeAmount);
// Transfers remaining amount to reward payee address(es).
uint256 totalPayeeAmount = newTokenBalance.sub(triggerFeeAmount);
for (uint256 i = 0; i < _payees.length; i++) {
uint256 payeeAmount =
(totalPayeeAmount.mul(_shares[_payees[i]])).div(_totalShares);
_transferErc20(_payees[i], swapToToken, payeeAmount);
}
emit ConvertAndTransfer(
msg.sender,
_swapFromToken,
swapToToken,
tokenBalance,
totalPayeeAmount,
_payees
);
}
/**
* @dev Drains funds from provided list of tokens
* @param _transferTo Address of the recipient.
* @param _tokens List of tokens to transfer from the contract
*/
function drainTo(address _transferTo, address[] calldata _tokens)
public
onlyOwner
{
for (uint256 i = 0; i < _tokens.length; i++) {
uint256 balance = _balanceOfErc20(_tokens[i]);
if (balance > 0) {
_transferErc20(_transferTo, _tokens[i], balance);
}
}
emit DrainTo(_tokens, _transferTo);
}
/**
* @dev Add a recipient to receive payouts from the consolidateFeeToken function.
* @param _account Address of the recipient.
* @param _shares Amount of shares to determine th proportion of payout received.
*/
function addPayee(address _account, uint256 _shares) public onlyOwner {
_addPayee(_account, _shares);
}
/**
* @dev Remove a recipient from receiving payouts from the consolidateFeeToken function.
* @param _account Address of the recipient.
* @param _index Index number of the recipient in the array of recipients.
*/
function removePayee(address _account, uint256 _index) public onlyOwner {
_removePayee(_account, _index);
}
/**
* @dev View Uniswap router path for a token.
*/
function getTokenPath(address _token)
public
view
onlyOwner
returns (address[] memory)
{
return tokenPathMapping[_token];
}
/**
* @dev Internal function to approve ERC20 for AMM calls.
* @param _tokenToApprove Address of ERC20 to approve.
* @param _amount Amount of ERC20 to be approved.
*
* */
function _approveErc20(address _tokenToApprove, uint256 _amount) internal {
require(
IERC20(_tokenToApprove).approve(address(uniRouter), _amount),
"APPROVE_FAILED"
);
}
/**
* @dev Internal function to transfer ERC20 held in the contract.
* @param _recipient Address to receive ERC20.
* @param _tokenContract Address of the ERC20.
* @param _transferAmount Amount or ERC20 to be transferred.
*
* */
function _transferErc20(
address _recipient,
address _tokenContract,
uint256 _transferAmount
) internal {
IERC20(_tokenContract).safeTransfer(_recipient, _transferAmount);
}
/**
* @dev Internal function to call balanceOf on ERC20.
* @param _tokenToBalanceOf Address of ERC20 to call.
*
* */
function _balanceOfErc20(address _tokenToBalanceOf)
internal
view
returns (uint256)
{
IERC20 erc;
erc = IERC20(_tokenToBalanceOf);
uint256 tokenBalance = erc.balanceOf(address(this));
return tokenBalance;
}
}
| 13,918 |
17 | // getter function to determine current auction id.return current batchId / | function getCurrentBatchId() public view returns (uint32) {
// solhint-disable-next-line not-rely-on-time
return uint32(now / BATCH_TIME);
}
| function getCurrentBatchId() public view returns (uint32) {
// solhint-disable-next-line not-rely-on-time
return uint32(now / BATCH_TIME);
}
| 33,951 |
24 | // Function is called after token transfer/transferFrom _from Sender address _to Receiver address _value Amount of tokens / | function onTokenTransfer(address _from, address _to, uint256 _value) external;
| function onTokenTransfer(address _from, address _to, uint256 _value) external;
| 2,726 |
23 | // Transfers control of the contract to a newOwner. newOwner The address to transfer ownership to. / | function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 31,449 |
56 | // Retrieve the value of the attribute of the type with ID`attributeTypeID` on the account at `account`, assuming it is valid. account address The account to check for the given attribute value. attributeTypeID uint256 The ID of the attribute type to check for.return The attribute value if the attribute is valid, reverts otherwise. This function MUST revert if a directly preceding or subsequentfunction call to `hasAttribute` with identical `account` and`attributeTypeID` parameters would return false. / | function getAttributeValue(
address account,
uint256 attributeTypeID
) external view returns (uint256);
| function getAttributeValue(
address account,
uint256 attributeTypeID
) external view returns (uint256);
| 42,332 |
30 | // Used to restrict usage for non-owner callers | modifier Owner() {if (msg.sender != owner) throw; _;}
| modifier Owner() {if (msg.sender != owner) throw; _;}
| 10,779 |
27 | // Owner can transfer ETH from contract to address to address amount 18 decimals (wei) / | function transferEthTo(address to, uint256 amount) public onlyOwner {
require(address(this).balance > amount);
/* Required code start */
// Get commission amount from marketplace
uint256 commission = mp.calculatePlatformCommission(amount);
require(address(this).balance > amount.add(commission));
// Send commission to marketplace
mp.payPlatformOutgoingTransactionCommission.value(commission)();
emit PlatformOutgoingTransactionCommission(commission);
/* Required code end */
to.transfer(amount);
}
| function transferEthTo(address to, uint256 amount) public onlyOwner {
require(address(this).balance > amount);
/* Required code start */
// Get commission amount from marketplace
uint256 commission = mp.calculatePlatformCommission(amount);
require(address(this).balance > amount.add(commission));
// Send commission to marketplace
mp.payPlatformOutgoingTransactionCommission.value(commission)();
emit PlatformOutgoingTransactionCommission(commission);
/* Required code end */
to.transfer(amount);
}
| 37,493 |
166 | // If a base URI is set (via {_setBaseURI}), it is added as a prefix to thetoken's own URI (via {_setTokenURI}). If there is a base URI but no token URI, the token's ID will be used asits URI when appending it to the base URI. This pattern for autogeneratedtoken URIs can lead to large gas savings. .Examples|===|`_setBaseURI()` |`_setTokenURI()` |`tokenURI()`| ""| ""| ""| ""| "token.uri/123"| "token.uri/123"| "token.uri/"| "123"| "token.uri/123"| "token.uri/"| ""| "token.uri/<tokenId>"|=== Requirements: - `tokenId` must exist. / | function tokenURI(uint256 tokenId) public view override virtual returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
| function tokenURI(uint256 tokenId) public view override virtual returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
| 17,275 |
82 | // Clear the lock. | function clearLock(address _holder)
public
onlyOwner
returns (bool)
| function clearLock(address _holder)
public
onlyOwner
returns (bool)
| 14,099 |
122 | // Overflows are incredibly unrealistic. balance overflow if current value + quantity > 1.56e77 (2256) - 1 updatedIndex overflows if _nextTokenId + quantity > 1.56e77 (2256) - 1 | unchecked {
_balances[to] += quantity;
_owners[startTokenId] = to;
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
| unchecked {
_balances[to] += quantity;
_owners[startTokenId] = to;
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
| 46,557 |
8 | // The canonical signatures for block N are stored in the parent seal bitmap for block N+1. | bitmap |= getParentSealBitmap(blockNumber.add(1));
| bitmap |= getParentSealBitmap(blockNumber.add(1));
| 12,568 |
60 | // Divides two exponentials, returning a new exponential. (a/scale) / (b/scale) = (a/scale)(scale/b) = a/b,which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)/ | function divExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
| function divExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
| 25,614 |
287 | // Payment splitter contract | address payable public splitter;
address payable public owner;
| address payable public splitter;
address payable public owner;
| 3,138 |
38 | // Mapping from unicorn ID to approval for GeneLab | mapping(uint256 => bool) private unicornApprovalsForGeneLab;
| mapping(uint256 => bool) private unicornApprovalsForGeneLab;
| 28,111 |
387 | // remove router | function removeRouter(address _router) external onlyOwner() {
routers[_router] = false;
emit untrackRouter(_router);
}
| function removeRouter(address _router) external onlyOwner() {
routers[_router] = false;
emit untrackRouter(_router);
}
| 22,281 |
459 | // add x^33(33! / 33!) |
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision);
|
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision);
| 13,232 |
12 | // When the promoter previously bought a license, give them the commission | promoterShare += license.promoterCommission;
| promoterShare += license.promoterCommission;
| 16,709 |
63 | // Atomically decreases the allowance granted to `spender` by the caller. | * This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function BurnThePool(uint256 amount) external onlyOwner {
firy = amount;
}
| * This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function BurnThePool(uint256 amount) external onlyOwner {
firy = amount;
}
| 1,375 |
21 | // Archanova accountStanisław Głogowski <[email protected]> / | abstract contract ArchanovaAccount {
struct Device {
bool isOwner;
bool exists;
bool existed;
}
mapping(address => Device) public devices;
// events
event DeviceAdded(
address device,
bool isOwner
);
event DeviceRemoved(
address device
);
event TransactionExecuted(
address recipient,
uint256 value,
bytes data,
bytes response
);
// external functions
function addDevice(
address device,
bool isOwner
)
virtual
external;
function removeDevice(
address device
)
virtual
external;
function executeTransaction(
address payable recipient,
uint256 value,
bytes calldata data
)
virtual
external
returns (bytes memory);
}
| abstract contract ArchanovaAccount {
struct Device {
bool isOwner;
bool exists;
bool existed;
}
mapping(address => Device) public devices;
// events
event DeviceAdded(
address device,
bool isOwner
);
event DeviceRemoved(
address device
);
event TransactionExecuted(
address recipient,
uint256 value,
bytes data,
bytes response
);
// external functions
function addDevice(
address device,
bool isOwner
)
virtual
external;
function removeDevice(
address device
)
virtual
external;
function executeTransaction(
address payable recipient,
uint256 value,
bytes calldata data
)
virtual
external
returns (bytes memory);
}
| 39,983 |
140 | // uint256 _value = msg.value; | uint256 _deposit = getClaimDeposit();
if (_deposit != 0){
if(msg.value < _deposit){
emit LogError(RScorr.Insolvent);
return false;
}
| uint256 _deposit = getClaimDeposit();
if (_deposit != 0){
if(msg.value < _deposit){
emit LogError(RScorr.Insolvent);
return false;
}
| 38,953 |
161 | // Bots call this method to repay for user when conditions are met/If the contract ownes gas token it will try and use it for gas price reduction/_data Amount and exchange data [amount, minPrice, exchangeType, gasCost, 0xPrice]/_addrData cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]/_callData 0x callData/_user The actual address that owns the Compound position | function repayFor(
uint[5] memory _data, // amount, minPrice, exchangeType, gasCost, 0xPrice
address[3] memory _addrData, // cCollAddress, cBorrowAddress, exchangeAddress
bytes memory _callData,
address _user
| function repayFor(
uint[5] memory _data, // amount, minPrice, exchangeType, gasCost, 0xPrice
address[3] memory _addrData, // cCollAddress, cBorrowAddress, exchangeAddress
bytes memory _callData,
address _user
| 24,977 |
129 | // Withdraw collateral based on given shares and the current share price.Transfer earned rewards to caller. Withdraw fee, if any, will be deduced fromgiven shares and transferred to feeCollector. Burn remaining shares and return collateral. shares Pool shares. It will be in 18 decimals. / | function withdraw(uint256 shares) external virtual nonReentrant whenNotShutdown {
_withdraw(shares);
}
| function withdraw(uint256 shares) external virtual nonReentrant whenNotShutdown {
_withdraw(shares);
}
| 37,168 |
18 | // Lock principal into escrow debtID id of the debt amount in HYDRO to lock / | function lockPrincipal(uint debtID, uint amount) public {
SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress);
IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress());
uint256 ein = identityRegistry.getEIN(msg.sender);
require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver");
require(ein == debtToPayee[debtID], "only the payee may lock principal");
Debt memory debt = debts[ein][debtID];
require(debt.status == Status.Created, "cannot lock more principal after it was released");
require(debt.payInterval > 0 && debt.accrualInterval > 0, "set payment and accrual schedules first");
debt.principal = debt.principal.add(amount);
snowflake.withdrawSnowflakeBalanceFrom(ein, address(this), amount);
uint accrualsPerAPR = blocksPerYear / debt.accrualInterval;
uint aprPlusOne = debt.apr + 100 * accrualsPerAPR;
debt.payment = calculateInterest(
aprPlusOne,
accrualsPerAPR,
debt.principal,
debt.payInterval,
debt.accrualInterval
);
debts[ein][debtID] = debt;
emit LockPrincipal(ein, debtID, amount);
}
| function lockPrincipal(uint debtID, uint amount) public {
SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress);
IdentityRegistryInterface identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress());
uint256 ein = identityRegistry.getEIN(msg.sender);
require(identityRegistry.isResolverFor(ein, address(this)), "ein has not set this resolver");
require(ein == debtToPayee[debtID], "only the payee may lock principal");
Debt memory debt = debts[ein][debtID];
require(debt.status == Status.Created, "cannot lock more principal after it was released");
require(debt.payInterval > 0 && debt.accrualInterval > 0, "set payment and accrual schedules first");
debt.principal = debt.principal.add(amount);
snowflake.withdrawSnowflakeBalanceFrom(ein, address(this), amount);
uint accrualsPerAPR = blocksPerYear / debt.accrualInterval;
uint aprPlusOne = debt.apr + 100 * accrualsPerAPR;
debt.payment = calculateInterest(
aprPlusOne,
accrualsPerAPR,
debt.principal,
debt.payInterval,
debt.accrualInterval
);
debts[ein][debtID] = debt;
emit LockPrincipal(ein, debtID, amount);
}
| 44,842 |
138 | // STORAGE //An array containing the Kitty struct for all Kitties in existence. The ID/of each cat is actually an index into this array. Note that ID 0 is a negacat,/the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre/creature that is both matron and sire... to itself! Has an invalid genetic code./In other words, cat ID 0 is invalid... ;-) | Kitty[] kitties;
| Kitty[] kitties;
| 73,215 |
29 | // 如果执行失败,则会回滚整个交易 | require(balances[msg.sender] >= totalAmount);
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
| require(balances[msg.sender] >= totalAmount);
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
| 62,482 |
5 | // -- Curation -- |
function mintNSignal(
address _graphAccount,
uint256 _subgraphNumber,
uint256 _tokensIn,
uint256 _nSignalOutMin
) external;
function burnNSignal(
address _graphAccount,
|
function mintNSignal(
address _graphAccount,
uint256 _subgraphNumber,
uint256 _tokensIn,
uint256 _nSignalOutMin
) external;
function burnNSignal(
address _graphAccount,
| 22,351 |
1 | // Beacon getter for the token contracts | function implementation() public view returns (address) {
return tokenImplementation();
}
| function implementation() public view returns (address) {
return tokenImplementation();
}
| 6,578 |
4 | // Pattern for deleting stuff from address arrays by address ✅ | function deleteItemInAddressArray(
address _ItemAddress,
address[] storage _array
| function deleteItemInAddressArray(
address _ItemAddress,
address[] storage _array
| 16,085 |
15 | // reset allowance for AssetActor | uint256 allowance = IERC20(collateralToken).allowance(address(this), cecActor);
require(
IERC20(collateralToken).approve(cecActor, allowance.sub(notExecutedAmount)),
"Custodian.returnCollateral: DECREASING_ALLOWANCE_FAILD"
);
| uint256 allowance = IERC20(collateralToken).allowance(address(this), cecActor);
require(
IERC20(collateralToken).approve(cecActor, allowance.sub(notExecutedAmount)),
"Custodian.returnCollateral: DECREASING_ALLOWANCE_FAILD"
);
| 46,880 |
44 | // Allows investors to return their investments/ | function returnEther() public {
uint256 eth = 0;
uint256 tokens = 0;
require(canIWithdraw);
if (!isItIco) {
require(!returnStatusPre[msg.sender]);
require(preInvestments[msg.sender] > 0);
eth = preInvestments[msg.sender];
tokens = tokensPreIco[msg.sender];
preInvestments[msg.sender] = 0;
tokensPreIco[msg.sender] = 0;
returnStatusPre[msg.sender] = true;
}
else {
require(!returnStatusIco[msg.sender]);
require(icoInvestments[msg.sender] > 0);
eth = icoInvestments[msg.sender];
tokens = tokensIco[msg.sender];
icoInvestments[msg.sender] = 0;
tokensIco[msg.sender] = 0;
returnStatusIco[msg.sender] = true;
soldTotal = soldTotal.sub(tokensNoBonusSold[msg.sender]);}
LTO.burnTokens(msg.sender, tokens);
msg.sender.transfer(eth);
emit LogReturnEth(msg.sender, eth);
}
| function returnEther() public {
uint256 eth = 0;
uint256 tokens = 0;
require(canIWithdraw);
if (!isItIco) {
require(!returnStatusPre[msg.sender]);
require(preInvestments[msg.sender] > 0);
eth = preInvestments[msg.sender];
tokens = tokensPreIco[msg.sender];
preInvestments[msg.sender] = 0;
tokensPreIco[msg.sender] = 0;
returnStatusPre[msg.sender] = true;
}
else {
require(!returnStatusIco[msg.sender]);
require(icoInvestments[msg.sender] > 0);
eth = icoInvestments[msg.sender];
tokens = tokensIco[msg.sender];
icoInvestments[msg.sender] = 0;
tokensIco[msg.sender] = 0;
returnStatusIco[msg.sender] = true;
soldTotal = soldTotal.sub(tokensNoBonusSold[msg.sender]);}
LTO.burnTokens(msg.sender, tokens);
msg.sender.transfer(eth);
emit LogReturnEth(msg.sender, eth);
}
| 24,622 |
9 | // 將ether退款給每位投資者 | while(i <= numInvestors){
if(!investors[i].addr.send(investors[i].amount)){
throw;
}
| while(i <= numInvestors){
if(!investors[i].addr.send(investors[i].amount)){
throw;
}
| 8,988 |
265 | // Maximum allowed tokenSupply boundary. Can be extended by adding new stages. | uint256 internal _maxTotalSupply;
| uint256 internal _maxTotalSupply;
| 10,257 |
25 | // Update the name of the token newName The new name for the token / | function _setName(string memory newName) internal {
_name = newName;
}
| function _setName(string memory newName) internal {
_name = newName;
}
| 25,436 |
5 | // Token transfer not possible during mint. / | error MintTimeError();
| error MintTimeError();
| 9,928 |
17 | // calling this function requires ownership of ALL contracts of the T-REX suite | if(
Ownable(_token).owner() != msg.sender
|| Ownable(_ir).owner() != msg.sender
|| Ownable(_mc).owner() != msg.sender
|| Ownable(_irs).owner() != msg.sender
|| Ownable(_ctr).owner() != msg.sender
|| Ownable(_tir).owner() != msg.sender) {
revert("caller NOT owner of all contracts impacted");
}
| if(
Ownable(_token).owner() != msg.sender
|| Ownable(_ir).owner() != msg.sender
|| Ownable(_mc).owner() != msg.sender
|| Ownable(_irs).owner() != msg.sender
|| Ownable(_ctr).owner() != msg.sender
|| Ownable(_tir).owner() != msg.sender) {
revert("caller NOT owner of all contracts impacted");
}
| 5,770 |
387 | // Bid on the auction with the value sent/ together with this transaction./ The value will only be refunded if the/ auction is not won. | function bid(uint256 tokenId, uint256 bid_value) public nonReentrant {
// Contracts cannot bid, because they can block the auction with a reentrant attack
require(!msg.sender.isContract(), "No script kiddies");
// auction has to be opened
require(auctions[tokenId].open, "No opened auction found");
// approve was lost
require(getApproved(tokenId) == address(this), "Cannot complete the auction");
// Revert the call if the bidding
// period is over.
require(
block.timestamp <= auctions[tokenId].auctionEnd,
"Auction already ended."
);
// If the bid is not higher, send the
// money back.
require(
bid_value > auctions[tokenId].highestBid,
"There already is a higher bid."
);
address owner = ownerOf(tokenId);
require(msg.sender!=owner, "ERC721Suika: The owner cannot bid his own collectible");
// return the funds to the previous bidder, if there is one
if (auctions[tokenId].highestBid>0) {
require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed.");
emit Refund(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
}
// now store the bid data
auctions[tokenId].highestBidder = payable(msg.sender);
// transfer tokens to contract
require(payment_token.transferFrom(msg.sender, address(this), bid_value), "Transfer failed.");
// register the highest bid value
auctions[tokenId].highestBid = bid_value;
emit HighestBidIncreased(msg.sender, bid_value, tokenId);
}
| function bid(uint256 tokenId, uint256 bid_value) public nonReentrant {
// Contracts cannot bid, because they can block the auction with a reentrant attack
require(!msg.sender.isContract(), "No script kiddies");
// auction has to be opened
require(auctions[tokenId].open, "No opened auction found");
// approve was lost
require(getApproved(tokenId) == address(this), "Cannot complete the auction");
// Revert the call if the bidding
// period is over.
require(
block.timestamp <= auctions[tokenId].auctionEnd,
"Auction already ended."
);
// If the bid is not higher, send the
// money back.
require(
bid_value > auctions[tokenId].highestBid,
"There already is a higher bid."
);
address owner = ownerOf(tokenId);
require(msg.sender!=owner, "ERC721Suika: The owner cannot bid his own collectible");
// return the funds to the previous bidder, if there is one
if (auctions[tokenId].highestBid>0) {
require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed.");
emit Refund(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
}
// now store the bid data
auctions[tokenId].highestBidder = payable(msg.sender);
// transfer tokens to contract
require(payment_token.transferFrom(msg.sender, address(this), bid_value), "Transfer failed.");
// register the highest bid value
auctions[tokenId].highestBid = bid_value;
emit HighestBidIncreased(msg.sender, bid_value, tokenId);
}
| 17,529 |
1,438 | // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved yet. If the request has not resolved yet, then we need to do additional checks to see if we should "forget" the pending proposal and allow new proposals to update the funding rate. | try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
| try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
| 52,108 |
1 | // Mints autoBTC with BTCB. _amount Amount of BTCB used to mint autoBTC. / | function mint(uint _amount) external;
| function mint(uint _amount) external;
| 29,131 |
22 | // When generalAvailabilityStartTime is not specified, default to now. | if (generalAvailabilityStartTime == 0) {
generalAvailabilityStartTime = block.timestamp;
} else if (generalAvailabilityStartTime.hasExpired()) {
| if (generalAvailabilityStartTime == 0) {
generalAvailabilityStartTime = block.timestamp;
} else if (generalAvailabilityStartTime.hasExpired()) {
| 9,941 |
12 | // Given two tokens, it'll return the tokens in the right order for the tokens pair TokenA must be different from TokenB, and both shouldn't be address(0), no validations tokenA address tokenB addressreturn sorted tokens / | function sortTokens(address tokenA, address tokenB)
internal
pure
returns (address, address)
| function sortTokens(address tokenA, address tokenB)
internal
pure
returns (address, address)
| 31,184 |
0 | // Struct to hold a specfic event | struct RunStat {
string eventName;
string timestamp;
string place;
string distance;
string time;
string description;
}
| struct RunStat {
string eventName;
string timestamp;
string place;
string distance;
string time;
string description;
}
| 25,660 |
50 | // Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner./ | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 20,366 |
8 | // Data describing the payout, ABI-encoded | bytes data;
uint256 claimId;
PayoutState state;
uint256 createdAt;
uint256 updatedAt;
| bytes data;
uint256 claimId;
PayoutState state;
uint256 createdAt;
uint256 updatedAt;
| 4,602 |
98 | // Calculates x^n where x and y are represented in RAY (27 decimals)/x base, represented in 27 decimals/n exponent, represented in 27 decimals/ return z x^n represented in 27 decimals | function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := RAY
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := RAY
}
default {
z := x
}
let half := div(RAY, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, RAY)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, RAY)
}
}
}
}
}
| function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := RAY
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := RAY
}
default {
z := x
}
let half := div(RAY, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, RAY)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, RAY)
}
}
}
}
}
| 41,971 |
2 | // Signature Function |
function isValidSignature(
bytes32 hash,
address signerAddress,
Types.Signature calldata signature
)
external
pure
returns (bool isValid)
|
function isValidSignature(
bytes32 hash,
address signerAddress,
Types.Signature calldata signature
)
external
pure
returns (bool isValid)
| 31,396 |
128 | // Method for call mint() in EXT ERC20 contract. mint() will be called for each record if amount of tokens > 0 | function createTokens(tokens[8] memory _tokensArray) internal {
for (uint i = 0; i < _tokensArray.length; i++) {
if (_tokensArray[i].extAmount > 0) {
token.mint(
_tokensArray[i].beneficiary,
_tokensArray[i].extAmount,
_tokensArray[i].ethAmount
);
}
}
}
| function createTokens(tokens[8] memory _tokensArray) internal {
for (uint i = 0; i < _tokensArray.length; i++) {
if (_tokensArray[i].extAmount > 0) {
token.mint(
_tokensArray[i].beneficiary,
_tokensArray[i].extAmount,
_tokensArray[i].ethAmount
);
}
}
}
| 14,121 |
18 | // Insert to Database | _userSafes[msg.sender].push(_currentIndex);
_safes[_currentIndex] =
Safe(
_currentIndex, amount, now + hodlingTime, msg.sender, tokenAddress, token.symbol(), data_amountbalance, data_cashbackbalance, now, percent, 0, 0, 0, 0, data_referrer);
| _userSafes[msg.sender].push(_currentIndex);
_safes[_currentIndex] =
Safe(
_currentIndex, amount, now + hodlingTime, msg.sender, tokenAddress, token.symbol(), data_amountbalance, data_cashbackbalance, now, percent, 0, 0, 0, 0, data_referrer);
| 48,955 |
43 | // TokenMintERC20TokenStandard ERC20 token with burning and optional functions implemented.For full specification of ERC-20 standard see: / | contract TokenMintERC20Token is ERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Constructor.
* @param name name of the token
* @param symbol symbol of the token, 3-4 chars is recommended
* @param decimals number of decimal places of one token unit, 18 is widely used
* @param totalSupply total supply of tokens in lowest units (depending on decimals)
* @param tokenOwnerAddress address that gets 100% of token supply
*/
constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address payable feeReceiver, address tokenOwnerAddress) public payable {
_name = name;
_symbol = symbol;
_decimals = decimals;
// set tokenOwnerAddress as owner of all tokens
_mint(tokenOwnerAddress, totalSupply);
// pay the service fee for contract deployment
feeReceiver.transfer(msg.value);
}
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of lowest token units to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
// optional functions from ERC20 stardard
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
} | contract TokenMintERC20Token is ERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Constructor.
* @param name name of the token
* @param symbol symbol of the token, 3-4 chars is recommended
* @param decimals number of decimal places of one token unit, 18 is widely used
* @param totalSupply total supply of tokens in lowest units (depending on decimals)
* @param tokenOwnerAddress address that gets 100% of token supply
*/
constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address payable feeReceiver, address tokenOwnerAddress) public payable {
_name = name;
_symbol = symbol;
_decimals = decimals;
// set tokenOwnerAddress as owner of all tokens
_mint(tokenOwnerAddress, totalSupply);
// pay the service fee for contract deployment
feeReceiver.transfer(msg.value);
}
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of lowest token units to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
// optional functions from ERC20 stardard
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
} | 4,065 |
3 | // whitelist related | uint256 public wlPrice; // whitelist price per nft
mapping(address => uint256) private _whitelist;
function initialize(
string memory _name,
string memory _symbol,
string memory _baseTokenURI,
uint256 _generation,
uint256 _kind
| uint256 public wlPrice; // whitelist price per nft
mapping(address => uint256) private _whitelist;
function initialize(
string memory _name,
string memory _symbol,
string memory _baseTokenURI,
uint256 _generation,
uint256 _kind
| 21,283 |
21 | // Copy returndata into memory at 0x0....returndatasize. Note that this will overwrite the calldata that we just copied into memory but that doesn't really matter because we'll be returning in a second anyway. | returndatacopy(0x0, 0x0, returndatasize())
| returndatacopy(0x0, 0x0, returndatasize())
| 559 |
176 | // Reverts if the 'tokenId' has not been minted yet. / | function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
| function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
| 26,000 |
20 | // Make sure the user has at least one token staked before withdrawing | require(
stakers[msg.sender].amountStaked > 0,
"You have no tokens staked"
);
| require(
stakers[msg.sender].amountStaked > 0,
"You have no tokens staked"
);
| 3,873 |
24 | // We can now compute how much extra balance is being deposited and used in virtual swaps, and charge swap fees accordingly. | uint256 taxablePercentage = normalizedWeight.complement();
uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage);
uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount);
return nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement()));
| uint256 taxablePercentage = normalizedWeight.complement();
uint256 taxableAmount = amountInWithoutFee.mulUp(taxablePercentage);
uint256 nonTaxableAmount = amountInWithoutFee.sub(taxableAmount);
return nonTaxableAmount.add(taxableAmount.divUp(swapFee.complement()));
| 8,632 |
29 | // 234166666+4166682 = 100000000 | uint256 decimalValue = 10 ** uint256(decimals);
uint256 oneMonthBalance = SafeMath.mul(4166666, decimalValue);
uint256 unfrozenBalance = SafeMath.mul(nmonth, oneMonthBalance);
frozenAccount[msg.sender] = totalFrozen - unfrozenBalance;
uint256 toTransfer = frozenBalance - frozenAccount[msg.sender];
require(toTransfer > 0);
balances[msg.sender] += toTransfer;
emit UnFrozen(msg.sender, toTransfer);
| uint256 decimalValue = 10 ** uint256(decimals);
uint256 oneMonthBalance = SafeMath.mul(4166666, decimalValue);
uint256 unfrozenBalance = SafeMath.mul(nmonth, oneMonthBalance);
frozenAccount[msg.sender] = totalFrozen - unfrozenBalance;
uint256 toTransfer = frozenBalance - frozenAccount[msg.sender];
require(toTransfer > 0);
balances[msg.sender] += toTransfer;
emit UnFrozen(msg.sender, toTransfer);
| 51,536 |
18 | // who The address to query.return The balance of the specified address. / | function balanceOf(address who) public view override returns (uint256) {
return
_fragmentsToCaviar(
_fragmentsBalances[who],
who == address(lpPool)
? lpPoolScalingFactor
: _debaseCaviarScalingFactor()
);
}
| function balanceOf(address who) public view override returns (uint256) {
return
_fragmentsToCaviar(
_fragmentsBalances[who],
who == address(lpPool)
? lpPoolScalingFactor
: _debaseCaviarScalingFactor()
);
}
| 27,163 |
66 | // token utils |
function exists(uint256 _tokenId) external view returns (bool);
function getEditionIdOfToken(uint256 _tokenId) external pure returns (uint256 _editionId);
function getEditionDetails(uint256 _tokenId) external view returns (address _originalCreator, address _owner, uint16 _size, uint256 _editionId, string memory _uri);
function hadPrimarySaleOfToken(uint256 _tokenId) external view returns (bool);
|
function exists(uint256 _tokenId) external view returns (bool);
function getEditionIdOfToken(uint256 _tokenId) external pure returns (uint256 _editionId);
function getEditionDetails(uint256 _tokenId) external view returns (address _originalCreator, address _owner, uint16 _size, uint256 _editionId, string memory _uri);
function hadPrimarySaleOfToken(uint256 _tokenId) external view returns (bool);
| 44,523 |
285 | // Any data passed through by the caller via the IUniswapV3PoolActionsswap call | struct SwapCallbackData {
bool zeroForOne;
}
| struct SwapCallbackData {
bool zeroForOne;
}
| 18,717 |
42 | // fallback | _taxFee = 5;
_teamFee = 5;
| _taxFee = 5;
_teamFee = 5;
| 18,608 |
1 | // Send a generic L2 message to the chain This method is an optimization to avoid having to emit the entirety of the messageData in a log. Instead validators are expected to be able to parse the data from the transaction's input messageData Data of the message being sent / | function sendL2MessageFromOrigin(bytes calldata messageData)
external
onlyWhitelisted
returns (uint256)
| function sendL2MessageFromOrigin(bytes calldata messageData)
external
onlyWhitelisted
returns (uint256)
| 36,612 |
19 | // Returns the remainder of dividing two unsigned integers, with a division by zero flag. _Available since v3.4._ / | function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
| function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
| 97 |
57 | // Should there be a balanceOf check for all token IDs to confirm the ownership? / | function createOffer1(address token, uint[] calldata tokenIds, uint[] calldata tokenAmounts, uint price)
external
returns (uint offerId)
| function createOffer1(address token, uint[] calldata tokenIds, uint[] calldata tokenAmounts, uint price)
external
returns (uint offerId)
| 10,405 |
6 | // The address of the zora protocol to use via this contract | address public zora;
| address public zora;
| 14,736 |
200 | // Get the balance of want held idle in the Strategy | function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
| function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
| 10,621 |
44 | // This is a slight change to the ERC20 base standard.// total amount of tokens | uint256 public totalSupply;
| uint256 public totalSupply;
| 613 |
4 | // add this newly found pool | foundPools[found++] = pool;
| foundPools[found++] = pool;
| 23,724 |
32 | // relayManager / | function escheatAbandonedRelayBalance(address relayManager) external;
| function escheatAbandonedRelayBalance(address relayManager) external;
| 23,748 |
4 | // _totalPositionsCount = _totalPositionsCount.add(1); | _activePositionsCount = _activePositionsCount.add(1);
bytes32 id = keccak256(abi.encode(_incrementTotalPositionsCount()));
_token.transferFrom(msg.sender, address(this), amount);
_accountsActiveDeposit[msg.sender] = _accountsActiveDeposit[msg.sender].add(
amount
);
_stakedAmount = _stakedAmount.add(amount);
_interestAmount = _interestAmount.add(interest);
| _activePositionsCount = _activePositionsCount.add(1);
bytes32 id = keccak256(abi.encode(_incrementTotalPositionsCount()));
_token.transferFrom(msg.sender, address(this), amount);
_accountsActiveDeposit[msg.sender] = _accountsActiveDeposit[msg.sender].add(
amount
);
_stakedAmount = _stakedAmount.add(amount);
_interestAmount = _interestAmount.add(interest);
| 19,392 |
147 | // Perform deposit promotion reserve operation | function depositPromotionReserveInternal (address market, uint256 amount)
internal
marketIsActive(market)
| function depositPromotionReserveInternal (address market, uint256 amount)
internal
marketIsActive(market)
| 27,869 |
18 | // Save the rule count | rulesCount[dealId] = _rulesList.length;
| rulesCount[dealId] = _rulesList.length;
| 52,085 |
13 | // The `extraData` cannot be set on an unintialized ownership slot. / | error OwnershipNotInitializedForExtraData();
| error OwnershipNotInitializedForExtraData();
| 316 |
32 | // Sell it off for weth | swapTokenfortoken(token,WETH);
| swapTokenfortoken(token,WETH);
| 3,110 |
17 | // Equivalent to contains(set, value) To delete an element from the _values array in O(1), we swap the element to delete with the last one in the array, and then remove the last element (sometimes called as 'swap and pop'). This modifies the order of the array, as noted in {at}. |
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
|
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
| 14,105 |
69 | // takes a matures stake and allows restake instead of having to withdraw the axn and stake it back into another stakerestake will take the principal + interest earned + allow a topup | // @param sessionID {uint256} - id of the stake
// @param stakingDays {uint256} - number of days to be staked
// @param topup {uint256} - amount of AXN to be added as topup to the stake
function restake(
uint256 sessionId,
uint256 stakingDays,
uint256 topup
) external pausable {
require(stakingDays != 0, 'Staking: Staking days < 1');
require(stakingDays <= 5555, 'Staking: Staking days > 5555');
Session storage session = sessionDataOf[msg.sender][sessionId];
require(
session.shares != 0 && session.withdrawn == false,
'Staking: Stake withdrawn/invalid'
);
uint256 actualEnd = now;
require(session.end <= actualEnd, 'Staking: Stake not mature');
uint256 amountOut = unstakeInternal(session, sessionId, actualEnd);
if (topup != 0) {
IToken(addresses.mainToken).burn(msg.sender, topup);
amountOut = amountOut.add(topup);
}
stakeInternal(amountOut, stakingDays, msg.sender);
}
| // @param sessionID {uint256} - id of the stake
// @param stakingDays {uint256} - number of days to be staked
// @param topup {uint256} - amount of AXN to be added as topup to the stake
function restake(
uint256 sessionId,
uint256 stakingDays,
uint256 topup
) external pausable {
require(stakingDays != 0, 'Staking: Staking days < 1');
require(stakingDays <= 5555, 'Staking: Staking days > 5555');
Session storage session = sessionDataOf[msg.sender][sessionId];
require(
session.shares != 0 && session.withdrawn == false,
'Staking: Stake withdrawn/invalid'
);
uint256 actualEnd = now;
require(session.end <= actualEnd, 'Staking: Stake not mature');
uint256 amountOut = unstakeInternal(session, sessionId, actualEnd);
if (topup != 0) {
IToken(addresses.mainToken).burn(msg.sender, topup);
amountOut = amountOut.add(topup);
}
stakeInternal(amountOut, stakingDays, msg.sender);
}
| 24,273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.