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
|
|---|---|---|---|---|
63
|
// Implements the ICOEngineInterface.return False if the ico is not started, true if the ico is started and running, true if the ico is completed. /
|
function started() public view returns(bool) {
if (block.timestamp >= start) {
return true;
} else {
return false;
}
}
|
function started() public view returns(bool) {
if (block.timestamp >= start) {
return true;
} else {
return false;
}
}
| 5,071
|
154
|
// What gets called in a permit
|
function _approve( address owner, address spender, uint256 value ) internal override virtual {
_allowedValue[owner][spender] = value;
emit Approval( owner, spender, value );
}
|
function _approve( address owner, address spender, uint256 value ) internal override virtual {
_allowedValue[owner][spender] = value;
emit Approval( owner, spender, value );
}
| 35,226
|
11
|
// Get a withdraw-recommendation. _balance The balance of the token-contract.return The address of the wallet permitted to withdraw ETH into the token-contract.return The amount that should be withdrawn in order for the balance to reach `mid` ETH. /
|
function getWithdrawParams(uint256 _balance) external view returns (address, uint256);
|
function getWithdrawParams(uint256 _balance) external view returns (address, uint256);
| 11,243
|
154
|
// unstake requests/
|
function setProcessedUnstakeRequest(uint256 _pool, uint256 _req) internal {
unstakeRequests[_pool][_req].processed = true;
}
|
function setProcessedUnstakeRequest(uint256 _pool, uint256 _req) internal {
unstakeRequests[_pool][_req].processed = true;
}
| 37,611
|
33
|
// If Tellor is broken, both oracles are untrusted, and return last good price
|
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.bothOraclesUntrusted);
return lastGoodPrice;
}
|
if (_tellorIsBroken(tellorResponse)) {
_changeStatus(Status.bothOraclesUntrusted);
return lastGoodPrice;
}
| 9,389
|
103
|
// Returns the TRB value of the token with 5 decimals of percision
|
function getTokenValue() external view returns (uint256) {
if (stakedAt != 0) {
return (stakeAmount + feesCollected).mul(100000).div(totalSupply());
} else {
return 100000;
}
}
|
function getTokenValue() external view returns (uint256) {
if (stakedAt != 0) {
return (stakeAmount + feesCollected).mul(100000).div(totalSupply());
} else {
return 100000;
}
}
| 57,626
|
188
|
// TERRA INFINITE MECHANICS/
|
function mintAndroids(uint numberOfTokens) external payable {
require(
allowMintAndroids ||
(allowMintForWhiteListed && isWhiteListed(msg.sender)), "The Terra Infinite sale is not active at that time");
require(numberOfTokens <= MAX_TOKEN_PURCHASE, "Exceeded max token purchase");
require((androidTotalSupply + numberOfTokens) <= maxAndroids, "Purchase would exceed max supply of tokens");
require(tokenPrice * numberOfTokens <= msg.value, "Ether value sent is not correct");
for (uint i = androidTotalSupply + 1; i <= androidTotalSupply + numberOfTokens; i++) {
_safeMint(msg.sender, i);
}
androidTotalSupply += numberOfTokens;
}
|
function mintAndroids(uint numberOfTokens) external payable {
require(
allowMintAndroids ||
(allowMintForWhiteListed && isWhiteListed(msg.sender)), "The Terra Infinite sale is not active at that time");
require(numberOfTokens <= MAX_TOKEN_PURCHASE, "Exceeded max token purchase");
require((androidTotalSupply + numberOfTokens) <= maxAndroids, "Purchase would exceed max supply of tokens");
require(tokenPrice * numberOfTokens <= msg.value, "Ether value sent is not correct");
for (uint i = androidTotalSupply + 1; i <= androidTotalSupply + numberOfTokens; i++) {
_safeMint(msg.sender, i);
}
androidTotalSupply += numberOfTokens;
}
| 21,397
|
2
|
// limits on rebalancing from the farmer, trying to negate errant rebalances
|
uint256 public rebalanceUpLimit = 100; // maximum of a 1.0% gain per rebalance
uint256 public rebalanceUpWaitTime = 23 hours;
uint256 public lastRebalanceUpTime;
|
uint256 public rebalanceUpLimit = 100; // maximum of a 1.0% gain per rebalance
uint256 public rebalanceUpWaitTime = 23 hours;
uint256 public lastRebalanceUpTime;
| 24,150
|
0
|
// Stores data for individual token locks used by transferAndLock. Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) /
|
struct Lock {
uint256 value;
uint64 expiration;
uint32 periodLength;
uint16 periods;
bool staking;
}
|
struct Lock {
uint256 value;
uint64 expiration;
uint32 periodLength;
uint16 periods;
bool staking;
}
| 11,226
|
70
|
// Unstake the juror if he lost due to inactivity.
|
if (!disputeKit.isVoteActive(_disputeID, _round, i)) {
uint96[] memory courtIDs = getJurorCourtIDs(account);
for (uint256 j = 0; j < courtIDs.length; j++) {
setStakeForAccount(account, courtIDs[j], 0, 0);
}
|
if (!disputeKit.isVoteActive(_disputeID, _round, i)) {
uint96[] memory courtIDs = getJurorCourtIDs(account);
for (uint256 j = 0; j < courtIDs.length; j++) {
setStakeForAccount(account, courtIDs[j], 0, 0);
}
| 20,574
|
22
|
// The official record of all proposals ever proposed
|
mapping (uint256 => Proposal) public proposals;
|
mapping (uint256 => Proposal) public proposals;
| 29,867
|
8
|
// Sets the TTL for the specified node. node The node to update. ttl The TTL in seconds. /
|
function setTTL(bytes32 node, uint64 ttl) public virtual override authorised(node) {
emit NewTTL(node, ttl);
records[node].ttl = ttl;
}
|
function setTTL(bytes32 node, uint64 ttl) public virtual override authorised(node) {
emit NewTTL(node, ttl);
records[node].ttl = ttl;
}
| 33,905
|
6
|
// claim offer using EIP712 and EIP1271 signature verification scheme/buyer address paying for the offer/seller address of the seller/token token used for payment/purchase buyAmount, maxTokenAmount/auctionData offerId, startingPrice, endingPrice, startedAt, duration, packs/ids ids of the Assets being sold/amounts amounts of Assets per pack/signature signature of seller
|
function claimSellerOfferViaEIP1271(
address buyer,
address payable seller,
address token,
uint256[] calldata purchase, // buyAmount, maxTokenAmount
uint256[] calldata auctionData,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata signature
|
function claimSellerOfferViaEIP1271(
address buyer,
address payable seller,
address token,
uint256[] calldata purchase, // buyAmount, maxTokenAmount
uint256[] calldata auctionData,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata signature
| 21,318
|
5
|
// copy contents of old array
|
for(uint i; i < arrayLength; i++) {
biggerArray[i] = facets_[facetIndex].functionSelectors[i];
}
|
for(uint i; i < arrayLength; i++) {
biggerArray[i] = facets_[facetIndex].functionSelectors[i];
}
| 24,324
|
175
|
// Update the given pool's DexyToken allocation point and deposit fee. Can only be called by the owner.
|
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 1000, "set: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
}
|
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 1000, "set: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
}
| 9,580
|
34
|
// Update number colaterals
|
numberCollaterals.increment();
emit CollateralEvent(collateralId, collaterals[collateralId],_UID);
|
numberCollaterals.increment();
emit CollateralEvent(collateralId, collaterals[collateralId],_UID);
| 40,419
|
69
|
// This will make the mint transaction apper in EtherScan.io We can remove this after there is a standardized minting event
|
Transfer(0, receiver, amount);
|
Transfer(0, receiver, amount);
| 2,538
|
54
|
// emit DebugUint("rollUnder", rollUnder);
|
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
|
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
| 21,133
|
42
|
// Approval implementation owner The address of the account which owns tokens spender The address of the account which may transfer tokens amount The number of tokens that are approved (2^256-1 means infinite) /
|
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "Yak::_approve: approve from the zero address");
require(spender != address(0), "Yak::_approve: approve to the zero address");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
|
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "Yak::_approve: approve from the zero address");
require(spender != address(0), "Yak::_approve: approve to the zero address");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 2,275
|
86
|
// Allows the owner to revoke the vesting. Tokens already vestedremain in the contract, the rest are returned to the owner. token ERC20 token which is being vested /
|
function revoke(IERC20 token) public onlyOwner {
require(_revocable);
require(!_revoked[address(token)]);
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(address(token));
}
|
function revoke(IERC20 token) public onlyOwner {
require(_revocable);
require(!_revoked[address(token)]);
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(address(token));
}
| 17,022
|
154
|
// Change the percent going to stakers for WETH --------------------
|
function startChangeStakersPercent(uint256 _percent) external onlyGovernance {
require(_percent <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 6;
_timelock_data_1 = _percent;
}
|
function startChangeStakersPercent(uint256 _percent) external onlyGovernance {
require(_percent <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 6;
_timelock_data_1 = _percent;
}
| 3,056
|
12
|
// deposit/stake
|
function stake(address asset, uint256 amount, uint256 poolId) public {
PoolInfo storage pool = poolInfo[poolId];
pool.balance = pool.balance.add(amount);
emit Stake(msg.sender, amount, block.timestamp);
}
|
function stake(address asset, uint256 amount, uint256 poolId) public {
PoolInfo storage pool = poolInfo[poolId];
pool.balance = pool.balance.add(amount);
emit Stake(msg.sender, amount, block.timestamp);
}
| 7,107
|
51
|
// Calculates the utilization rate for the given asset _supply The total supply for the given asset _demand The total demand for the given asset /
|
function utilizationRate(uint256 _supply, uint256 _demand)
public
pure
returns (uint256)
|
function utilizationRate(uint256 _supply, uint256 _demand)
public
pure
returns (uint256)
| 30,027
|
57
|
// Income should go here. /
|
function deposit() payable {
onDeposit(msg.sender, msg.value);
lifetimeDeposits += msg.value;
deposits[msg.sender].push(Deposit({ amount: msg.value, block: now }));
}
|
function deposit() payable {
onDeposit(msg.sender, msg.value);
lifetimeDeposits += msg.value;
deposits[msg.sender].push(Deposit({ amount: msg.value, block: now }));
}
| 34,673
|
8
|
// EVENTS/
|
event setBaseURIEvent(string indexed baseURI);
event setOwnersExplicitEvent(uint256 indexed quantity);
event WithdrawAllEvent(address indexed to, uint256 amount);
event ReceivedEther(address indexed sender, uint256 indexed amount);
constructor(
address _openseaProxyRegistryAddress
|
event setBaseURIEvent(string indexed baseURI);
event setOwnersExplicitEvent(uint256 indexed quantity);
event WithdrawAllEvent(address indexed to, uint256 amount);
event ReceivedEther(address indexed sender, uint256 indexed amount);
constructor(
address _openseaProxyRegistryAddress
| 41,878
|
52
|
// Convert any assets if needed
|
_conversionHelper(converstionDetails);
|
_conversionHelper(converstionDetails);
| 31,454
|
112
|
// _fromToken will be either fromToken or toToken of the previous path
|
address _fromToken = i > 0 ? path[i - 1].to : fromToken;
address _toToken = path[i].to;
uint256 _fromAmount = i > 0 ? Utils.tokenBalance(_fromToken, address(this)) : fromAmount;
if (i > 0 && _fromToken == Utils.ethAddress()) {
_fromAmount = _fromAmount.sub(path[i].totalNetworkFee);
}
|
address _fromToken = i > 0 ? path[i - 1].to : fromToken;
address _toToken = path[i].to;
uint256 _fromAmount = i > 0 ? Utils.tokenBalance(_fromToken, address(this)) : fromAmount;
if (i > 0 && _fromToken == Utils.ethAddress()) {
_fromAmount = _fromAmount.sub(path[i].totalNetworkFee);
}
| 12,080
|
53
|
// Used in memory in `nextTradePair` to duck the stack limit
|
struct MaxSurplusDeficit {
CollateralStatus surplusStatus; // starts SOUND
uint192 surplus; // {UoA}
uint192 deficit; // {UoA}
}
|
struct MaxSurplusDeficit {
CollateralStatus surplusStatus; // starts SOUND
uint192 surplus; // {UoA}
uint192 deficit; // {UoA}
}
| 40,242
|
22
|
// internal
|
function payFee(
address to,
uint256 amount
|
function payFee(
address to,
uint256 amount
| 17,563
|
37
|
// The block at which voting ends: votes must be cast prior to this block
|
uint256 endBlock;
|
uint256 endBlock;
| 24,404
|
117
|
// Perform an ERC20 token transferFrom. Designed to be called by transferFrom functionspossessing the optionalProxy or optionalProxy modifiers. /
|
function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data)
internal
returns (bool)
|
function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data)
internal
returns (bool)
| 22,663
|
73
|
// validate signature elements
|
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
VOTE_HASH,
signer,
proposal,
|
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
VOTE_HASH,
signer,
proposal,
| 19,384
|
39
|
// Burns away the oTokens to redeem the asset collateral/Operation to burn away the oTOkens in redemption of the asset collateral/_amount Amount of calls to burn
|
function burnOptions(uint256 _amount) external onlyManager nonReentrant() whenNotPaused() {
if(!_withdrawalWindowCheck(false))
revert WithdrawalWindowActive();
if(_amount > IERC20(oToken).balanceOf(address(this)))
revert Invalid();
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](2);
uint256 normalizedAmount = _normalize(_amount, 8, 18);
actions[0] = Actions.ActionArgs(
Actions.ActionType.BurnShortOption,
address(this),
address(this),
oToken,
currentVaultId,
_amount,
0,
""
);
actions[1] = Actions.ActionArgs(
Actions.ActionType.WithdrawCollateral,
address(this),
address(this),
asset,
currentVaultId,
normalizedAmount,
0,
""
);
IController controller = IController(addressBook.getController());
controller.operate(actions);
collateralAmount -= normalizedAmount;
if(collateralAmount == 0 && IERC20(oToken).balanceOf(address(this)) == 0) {
// Withdrawal window reopens
withdrawalWindowExpires = block.timestamp + withdrawalWindowLength;
oToken = address(0);
emit WithdrawalWindowActivated(withdrawalWindowExpires);
}
emit OptionsBurned(_amount);
}
|
function burnOptions(uint256 _amount) external onlyManager nonReentrant() whenNotPaused() {
if(!_withdrawalWindowCheck(false))
revert WithdrawalWindowActive();
if(_amount > IERC20(oToken).balanceOf(address(this)))
revert Invalid();
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](2);
uint256 normalizedAmount = _normalize(_amount, 8, 18);
actions[0] = Actions.ActionArgs(
Actions.ActionType.BurnShortOption,
address(this),
address(this),
oToken,
currentVaultId,
_amount,
0,
""
);
actions[1] = Actions.ActionArgs(
Actions.ActionType.WithdrawCollateral,
address(this),
address(this),
asset,
currentVaultId,
normalizedAmount,
0,
""
);
IController controller = IController(addressBook.getController());
controller.operate(actions);
collateralAmount -= normalizedAmount;
if(collateralAmount == 0 && IERC20(oToken).balanceOf(address(this)) == 0) {
// Withdrawal window reopens
withdrawalWindowExpires = block.timestamp + withdrawalWindowLength;
oToken = address(0);
emit WithdrawalWindowActivated(withdrawalWindowExpires);
}
emit OptionsBurned(_amount);
}
| 7,477
|
9
|
// return x / y + ((x % y == 0) ? 0 : 1);
|
require(y > 0);
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
|
require(y > 0);
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
| 22,473
|
115
|
// -----------------------------------------------------------------------/ State updates/ -----------------------------------------------------------------------
|
emergencyExitStatusOfVault[vault] = EmergencyExitStatus({
activated: true,
pytPriceInUnderlying: pytPriceInUnderlying
});
|
emergencyExitStatusOfVault[vault] = EmergencyExitStatus({
activated: true,
pytPriceInUnderlying: pytPriceInUnderlying
});
| 4,037
|
0
|
// Storage for slot to check user mints/target contract -> tokenId -> minter user -> numberMinted/No gap or stroage interface since this is used within non-upgradeable contracts
|
mapping(address => mapping(uint256 => mapping(address => uint256))) internal mintedPerAddress;
function getMintedPerWallet(address tokenContract, uint256 tokenId, address wallet) external view returns (uint256) {
return mintedPerAddress[tokenContract][tokenId][wallet];
}
|
mapping(address => mapping(uint256 => mapping(address => uint256))) internal mintedPerAddress;
function getMintedPerWallet(address tokenContract, uint256 tokenId, address wallet) external view returns (uint256) {
return mintedPerAddress[tokenContract][tokenId][wallet];
}
| 27,095
|
4
|
// Interface to the digital media store external contract that isresponsible for storing the common digital media and collection data.This allows for new token contracts to be deployed and continue to referencethe digital media and collection data. /
|
abstract contract ApprovedCreatorRegistryInterface {
function getVersion() virtual public pure returns (uint);
function typeOfContract() virtual public pure returns (string calldata);
function isOperatorApprovedForCustodialAccount(
address _operator,
address _custodialAddress) virtual public view returns (bool);
}
|
abstract contract ApprovedCreatorRegistryInterface {
function getVersion() virtual public pure returns (uint);
function typeOfContract() virtual public pure returns (string calldata);
function isOperatorApprovedForCustodialAccount(
address _operator,
address _custodialAddress) virtual public view returns (bool);
}
| 54,240
|
1
|
// transfer ETH from this contract to recipient
|
function ethThisTransferTo(
address recipient,
uint256 amount
)external;
|
function ethThisTransferTo(
address recipient,
uint256 amount
)external;
| 54,929
|
147
|
// Grants `role` to `account`.
|
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "Not admin");
_grantRole(role, account);
}
|
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "Not admin");
_grantRole(role, account);
}
| 25,433
|
4
|
// Used by Voter to allow batched reward claims
|
function getRewardForOwner(uint tokenId, address[] memory tokens)
external
override
|
function getRewardForOwner(uint tokenId, address[] memory tokens)
external
override
| 28,742
|
19
|
// Method: _buyFor, privatePayable the sends equivilent tokens calculated based on the rate to the _receiver set by msg.sender. Parameters:- `address _receiver` -> non zero address of the receiver of the tokens.- `uint256 _msgValue` -> non zero amount of ETH in WEI the sender sent.Returns:The total amount of tokens the _receiver has. /
|
function _buyFor(address _receiver, uint256 _msgValue) private returns(uint256) {
require(_msgValue > 0, "Error! Invalid or Insufficient Amount.");
require(self != address(0), "Error! Uninitialized self.");
uint256 tokenAmount = _msgValue.div(rate);
uint256 tokenAllowance = token.allowance(holder, self);
require(tokenAmount > 0 && tokenAmount <= tokenAllowance, "Insufficient Liquidity");
withdrawETHToOwner(_msgValue);
require(token.transferFrom(holder, _receiver, tokenAmount), "Oops... Could not complete Transaction. Please try again later.");
return token.balanceOf(_receiver);
}
|
function _buyFor(address _receiver, uint256 _msgValue) private returns(uint256) {
require(_msgValue > 0, "Error! Invalid or Insufficient Amount.");
require(self != address(0), "Error! Uninitialized self.");
uint256 tokenAmount = _msgValue.div(rate);
uint256 tokenAllowance = token.allowance(holder, self);
require(tokenAmount > 0 && tokenAmount <= tokenAllowance, "Insufficient Liquidity");
withdrawETHToOwner(_msgValue);
require(token.transferFrom(holder, _receiver, tokenAmount), "Oops... Could not complete Transaction. Please try again later.");
return token.balanceOf(_receiver);
}
| 32,810
|
138
|
// Update the message sender's account. This will assure that any credit that was earned is not overridden.
|
_poke(msg.sender);
uint256 shares = _yieldTokens[yieldToken].totalShares - _accounts[msg.sender].balances[yieldToken];
_yieldTokens[yieldToken].accruedWeight += amount * FIXED_POINT_SCALAR / shares;
_accounts[msg.sender].lastAccruedWeights[yieldToken] = _yieldTokens[yieldToken].accruedWeight;
TokenUtils.safeBurnFrom(debtToken, msg.sender, amount);
emit Donate(msg.sender, yieldToken, amount);
|
_poke(msg.sender);
uint256 shares = _yieldTokens[yieldToken].totalShares - _accounts[msg.sender].balances[yieldToken];
_yieldTokens[yieldToken].accruedWeight += amount * FIXED_POINT_SCALAR / shares;
_accounts[msg.sender].lastAccruedWeights[yieldToken] = _yieldTokens[yieldToken].accruedWeight;
TokenUtils.safeBurnFrom(debtToken, msg.sender, amount);
emit Donate(msg.sender, yieldToken, amount);
| 68,978
|
4
|
// Define the state machine for leasing
|
enum LeaseState {Created, Signed, Occupied, Terminated}
// Lease as the state variable
Lease public lease;
// Keep a record of all payments and account balance
struct Deposit
// التأمين
{
uint sequence;
uint amount;
}
|
enum LeaseState {Created, Signed, Occupied, Terminated}
// Lease as the state variable
Lease public lease;
// Keep a record of all payments and account balance
struct Deposit
// التأمين
{
uint sequence;
uint amount;
}
| 31,789
|
336
|
// ensure the caller owns the egg they want to hatch
|
require(_owns(msg.sender, _fishId));
_hatchFish(_fishId, _geneSet1, _geneSet2);
|
require(_owns(msg.sender, _fishId));
_hatchFish(_fishId, _geneSet1, _geneSet2);
| 37,072
|
37
|
// TODO conversion? safe math? prevent over withdrawals
|
assert(int(left.withdrawal) <= int(left.deposit) + left.credit);
|
assert(int(left.withdrawal) <= int(left.deposit) + left.credit);
| 9,361
|
71
|
// solhint-disable func-order // Balancer Labs Highly opinionated token implementation/
|
contract PCToken is IERC20 {
using BalancerSafeMath for uint;
// State variables
string public constant NAME = "Spook Smart Pool";
uint8 public constant DECIMALS = 18;
// No leading underscore per naming convention (non-private)
// Cannot call totalSupply (name conflict)
// solhint-disable-next-line private-vars-leading-underscore
uint internal varTotalSupply;
mapping(address => uint) private _balance;
mapping(address => mapping(address => uint)) private _allowance;
string private _symbol;
string private _name;
// Event declarations
// See definitions above; must be redeclared to be emitted from this contract
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
// Function declarations
/**
* @notice Base token constructor
* @param tokenSymbol - the token symbol
*/
constructor (string memory tokenSymbol, string memory tokenName) public {
_symbol = tokenSymbol;
_name = tokenName;
}
// External functions
/**
* @notice Getter for allowance: amount spender will be allowed to spend on behalf of owner
* @param owner - owner of the tokens
* @param spender - entity allowed to spend the tokens
* @return uint - remaining amount spender is allowed to transfer
*/
function allowance(address owner, address spender) external view override returns (uint) {
return _allowance[owner][spender];
}
/**
* @notice Getter for current account balance
* @param account - address we're checking the balance of
* @return uint - token balance in the account
*/
function balanceOf(address account) external view override returns (uint) {
return _balance[account];
}
/**
* @notice Approve owner (sender) to spend a certain amount
* @dev emits an Approval event
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
* @return bool - result of the approval (will always be true if it doesn't revert)
*/
function approve(address spender, uint amount) external override returns (bool) {
/* In addition to the increase/decreaseApproval functions, could
avoid the "approval race condition" by only allowing calls to approve
when the current approval amount is 0
require(_allowance[msg.sender][spender] == 0, "ERR_RACE_CONDITION");
Some token contracts (e.g., KNC), already revert if you call approve
on a non-zero allocation. To deal with these, we use the SafeApprove library
and safeApprove function when adding tokens to the pool.
*/
_allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Increase the amount the spender is allowed to spend on behalf of the owner (sender)
* @dev emits an Approval event
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
* @return bool - result of the approval (will always be true if it doesn't revert)
*/
function increaseApproval(address spender, uint amount) external returns (bool) {
_allowance[msg.sender][spender] = BalancerSafeMath.badd(_allowance[msg.sender][spender], amount);
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
/**
* @notice Decrease the amount the spender is allowed to spend on behalf of the owner (sender)
* @dev emits an Approval event
* @dev If you try to decrease it below the current limit, it's just set to zero (not an error)
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
* @return bool - result of the approval (will always be true if it doesn't revert)
*/
function decreaseApproval(address spender, uint amount) external returns (bool) {
uint oldValue = _allowance[msg.sender][spender];
// Gas optimization - if amount == oldValue (or is larger), set to zero immediately
if (amount >= oldValue) {
_allowance[msg.sender][spender] = 0;
} else {
_allowance[msg.sender][spender] = BalancerSafeMath.bsub(oldValue, amount);
}
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
/**
* @notice Transfer the given amount from sender (caller) to recipient
* @dev _move emits a Transfer event if successful
* @param recipient - entity receiving the tokens
* @param amount - number of tokens being transferred
* @return bool - result of the transfer (will always be true if it doesn't revert)
*/
function transfer(address recipient, uint amount) external override returns (bool) {
require(recipient != address(0), "ERR_ZERO_ADDRESS");
_move(msg.sender, recipient, amount);
return true;
}
/**
* @notice Transfer the given amount from sender to recipient
* @dev _move emits a Transfer event if successful; may also emit an Approval event
* @param sender - entity sending the tokens (must be caller or allowed to spend on behalf of caller)
* @param recipient - recipient of the tokens
* @param amount - number of tokens being transferred
* @return bool - result of the transfer (will always be true if it doesn't revert)
*/
function transferFrom(address sender, address recipient, uint amount) external override returns (bool) {
require(recipient != address(0), "ERR_ZERO_ADDRESS");
require(msg.sender == sender || amount <= _allowance[sender][msg.sender], "ERR_PCTOKEN_BAD_CALLER");
_move(sender, recipient, amount);
// memoize for gas optimization
uint oldAllowance = _allowance[sender][msg.sender];
// If the sender is not the caller, adjust the allowance by the amount transferred
if (msg.sender != sender && oldAllowance != uint(-1)) {
_allowance[sender][msg.sender] = BalancerSafeMath.bsub(oldAllowance, amount);
emit Approval(msg.sender, recipient, _allowance[sender][msg.sender]);
}
return true;
}
// public functions
/**
* @notice Getter for the total supply
* @dev declared external for gas optimization
* @return uint - total number of tokens in existence
*/
function totalSupply() external view override returns (uint) {
return varTotalSupply;
}
// Public functions
/**
* @dev Returns the name of the token.
* We allow the user to set this name (as well as the symbol).
* Alternatives are 1) A fixed string (original design)
* 2) A fixed string plus the user-defined symbol
* return string(abi.encodePacked(NAME, "-", _symbol));
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external pure returns (uint8) {
return DECIMALS;
}
// internal functions
// Mint an amount of new tokens, and add them to the balance (and total supply)
// Emit a transfer amount from the null address to this contract
function _mint(uint amount) internal virtual {
_balance[address(this)] = BalancerSafeMath.badd(_balance[address(this)], amount);
varTotalSupply = BalancerSafeMath.badd(varTotalSupply, amount);
emit Transfer(address(0), address(this), amount);
}
// Burn an amount of new tokens, and subtract them from the balance (and total supply)
// Emit a transfer amount from this contract to the null address
function _burn(uint amount) internal virtual {
// Can't burn more than we have
// Remove require for gas optimization - bsub will revert on underflow
// require(_balance[address(this)] >= amount, "ERR_INSUFFICIENT_BAL");
_balance[address(this)] = BalancerSafeMath.bsub(_balance[address(this)], amount);
varTotalSupply = BalancerSafeMath.bsub(varTotalSupply, amount);
emit Transfer(address(this), address(0), amount);
}
// Transfer tokens from sender to recipient
// Adjust balances, and emit a Transfer event
function _move(address sender, address recipient, uint amount) internal virtual {
// Can't send more than sender has
// Remove require for gas optimization - bsub will revert on underflow
// require(_balance[sender] >= amount, "ERR_INSUFFICIENT_BAL");
_balance[sender] = BalancerSafeMath.bsub(_balance[sender], amount);
_balance[recipient] = BalancerSafeMath.badd(_balance[recipient], amount);
emit Transfer(sender, recipient, amount);
}
// Transfer from this contract to recipient
// Emits a transfer event if successful
function _push(address recipient, uint amount) internal {
_move(address(this), recipient, amount);
}
// Transfer from recipient to this contract
// Emits a transfer event if successful
function _pull(address sender, uint amount) internal {
_move(sender, address(this), amount);
}
}
|
contract PCToken is IERC20 {
using BalancerSafeMath for uint;
// State variables
string public constant NAME = "Spook Smart Pool";
uint8 public constant DECIMALS = 18;
// No leading underscore per naming convention (non-private)
// Cannot call totalSupply (name conflict)
// solhint-disable-next-line private-vars-leading-underscore
uint internal varTotalSupply;
mapping(address => uint) private _balance;
mapping(address => mapping(address => uint)) private _allowance;
string private _symbol;
string private _name;
// Event declarations
// See definitions above; must be redeclared to be emitted from this contract
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
// Function declarations
/**
* @notice Base token constructor
* @param tokenSymbol - the token symbol
*/
constructor (string memory tokenSymbol, string memory tokenName) public {
_symbol = tokenSymbol;
_name = tokenName;
}
// External functions
/**
* @notice Getter for allowance: amount spender will be allowed to spend on behalf of owner
* @param owner - owner of the tokens
* @param spender - entity allowed to spend the tokens
* @return uint - remaining amount spender is allowed to transfer
*/
function allowance(address owner, address spender) external view override returns (uint) {
return _allowance[owner][spender];
}
/**
* @notice Getter for current account balance
* @param account - address we're checking the balance of
* @return uint - token balance in the account
*/
function balanceOf(address account) external view override returns (uint) {
return _balance[account];
}
/**
* @notice Approve owner (sender) to spend a certain amount
* @dev emits an Approval event
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
* @return bool - result of the approval (will always be true if it doesn't revert)
*/
function approve(address spender, uint amount) external override returns (bool) {
/* In addition to the increase/decreaseApproval functions, could
avoid the "approval race condition" by only allowing calls to approve
when the current approval amount is 0
require(_allowance[msg.sender][spender] == 0, "ERR_RACE_CONDITION");
Some token contracts (e.g., KNC), already revert if you call approve
on a non-zero allocation. To deal with these, we use the SafeApprove library
and safeApprove function when adding tokens to the pool.
*/
_allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Increase the amount the spender is allowed to spend on behalf of the owner (sender)
* @dev emits an Approval event
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
* @return bool - result of the approval (will always be true if it doesn't revert)
*/
function increaseApproval(address spender, uint amount) external returns (bool) {
_allowance[msg.sender][spender] = BalancerSafeMath.badd(_allowance[msg.sender][spender], amount);
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
/**
* @notice Decrease the amount the spender is allowed to spend on behalf of the owner (sender)
* @dev emits an Approval event
* @dev If you try to decrease it below the current limit, it's just set to zero (not an error)
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
* @return bool - result of the approval (will always be true if it doesn't revert)
*/
function decreaseApproval(address spender, uint amount) external returns (bool) {
uint oldValue = _allowance[msg.sender][spender];
// Gas optimization - if amount == oldValue (or is larger), set to zero immediately
if (amount >= oldValue) {
_allowance[msg.sender][spender] = 0;
} else {
_allowance[msg.sender][spender] = BalancerSafeMath.bsub(oldValue, amount);
}
emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);
return true;
}
/**
* @notice Transfer the given amount from sender (caller) to recipient
* @dev _move emits a Transfer event if successful
* @param recipient - entity receiving the tokens
* @param amount - number of tokens being transferred
* @return bool - result of the transfer (will always be true if it doesn't revert)
*/
function transfer(address recipient, uint amount) external override returns (bool) {
require(recipient != address(0), "ERR_ZERO_ADDRESS");
_move(msg.sender, recipient, amount);
return true;
}
/**
* @notice Transfer the given amount from sender to recipient
* @dev _move emits a Transfer event if successful; may also emit an Approval event
* @param sender - entity sending the tokens (must be caller or allowed to spend on behalf of caller)
* @param recipient - recipient of the tokens
* @param amount - number of tokens being transferred
* @return bool - result of the transfer (will always be true if it doesn't revert)
*/
function transferFrom(address sender, address recipient, uint amount) external override returns (bool) {
require(recipient != address(0), "ERR_ZERO_ADDRESS");
require(msg.sender == sender || amount <= _allowance[sender][msg.sender], "ERR_PCTOKEN_BAD_CALLER");
_move(sender, recipient, amount);
// memoize for gas optimization
uint oldAllowance = _allowance[sender][msg.sender];
// If the sender is not the caller, adjust the allowance by the amount transferred
if (msg.sender != sender && oldAllowance != uint(-1)) {
_allowance[sender][msg.sender] = BalancerSafeMath.bsub(oldAllowance, amount);
emit Approval(msg.sender, recipient, _allowance[sender][msg.sender]);
}
return true;
}
// public functions
/**
* @notice Getter for the total supply
* @dev declared external for gas optimization
* @return uint - total number of tokens in existence
*/
function totalSupply() external view override returns (uint) {
return varTotalSupply;
}
// Public functions
/**
* @dev Returns the name of the token.
* We allow the user to set this name (as well as the symbol).
* Alternatives are 1) A fixed string (original design)
* 2) A fixed string plus the user-defined symbol
* return string(abi.encodePacked(NAME, "-", _symbol));
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external pure returns (uint8) {
return DECIMALS;
}
// internal functions
// Mint an amount of new tokens, and add them to the balance (and total supply)
// Emit a transfer amount from the null address to this contract
function _mint(uint amount) internal virtual {
_balance[address(this)] = BalancerSafeMath.badd(_balance[address(this)], amount);
varTotalSupply = BalancerSafeMath.badd(varTotalSupply, amount);
emit Transfer(address(0), address(this), amount);
}
// Burn an amount of new tokens, and subtract them from the balance (and total supply)
// Emit a transfer amount from this contract to the null address
function _burn(uint amount) internal virtual {
// Can't burn more than we have
// Remove require for gas optimization - bsub will revert on underflow
// require(_balance[address(this)] >= amount, "ERR_INSUFFICIENT_BAL");
_balance[address(this)] = BalancerSafeMath.bsub(_balance[address(this)], amount);
varTotalSupply = BalancerSafeMath.bsub(varTotalSupply, amount);
emit Transfer(address(this), address(0), amount);
}
// Transfer tokens from sender to recipient
// Adjust balances, and emit a Transfer event
function _move(address sender, address recipient, uint amount) internal virtual {
// Can't send more than sender has
// Remove require for gas optimization - bsub will revert on underflow
// require(_balance[sender] >= amount, "ERR_INSUFFICIENT_BAL");
_balance[sender] = BalancerSafeMath.bsub(_balance[sender], amount);
_balance[recipient] = BalancerSafeMath.badd(_balance[recipient], amount);
emit Transfer(sender, recipient, amount);
}
// Transfer from this contract to recipient
// Emits a transfer event if successful
function _push(address recipient, uint amount) internal {
_move(address(this), recipient, amount);
}
// Transfer from recipient to this contract
// Emits a transfer event if successful
function _pull(address sender, uint amount) internal {
_move(sender, address(this), amount);
}
}
| 24,635
|
19
|
// else enable refunds
|
vault.enableRefunds();
|
vault.enableRefunds();
| 49,468
|
1
|
// A processed deposit event.
|
event DepositEvent(
bytes pubkey,
bytes withdrawal_credentials,
bytes amount,
bytes signature,
bytes index
);
|
event DepositEvent(
bytes pubkey,
bytes withdrawal_credentials,
bytes amount,
bytes signature,
bytes index
);
| 18,127
|
196
|
// dont overmint
|
require(amount <= TOKEN_LIMIT-numTokens,"Not enough Birbs left to mint");
|
require(amount <= TOKEN_LIMIT-numTokens,"Not enough Birbs left to mint");
| 62,246
|
175
|
// Because this is removing the token from the pool, the in-memory denorm value is irrelevant, as it is only used to calculate the new spot price, but the spot price calc will throw if it is passed 0 for the denorm.
|
_unbind(token);
|
_unbind(token);
| 12,434
|
32
|
// par is a ray, pip returns a wad
|
tag[ilk] = wdiv(spot.par(), uint(pip.read()));
|
tag[ilk] = wdiv(spot.par(), uint(pip.read()));
| 40,390
|
161
|
// Call addPaid on model
|
paid = _safePay(id, debt.model, available);
require(paid <= available, "Paid can't exceed available");
|
paid = _safePay(id, debt.model, available);
require(paid <= available, "Paid can't exceed available");
| 44,100
|
11
|
// events ---
|
event Created(bytes32 _tradeHash);
event SellerCancelDisabled(bytes32 _tradeHash);
event SellerRequestedCancel(bytes32 _tradeHash);
event CancelledBySeller(bytes32 _tradeHash);
event CancelledByBuyer(bytes32 _tradeHash);
event Released(bytes32 _tradeHash);
event DisputeResolved(bytes32 _tradeHash);
|
event Created(bytes32 _tradeHash);
event SellerCancelDisabled(bytes32 _tradeHash);
event SellerRequestedCancel(bytes32 _tradeHash);
event CancelledBySeller(bytes32 _tradeHash);
event CancelledByBuyer(bytes32 _tradeHash);
event Released(bytes32 _tradeHash);
event DisputeResolved(bytes32 _tradeHash);
| 2,270
|
129
|
// reduce the netPosted (in storage) to value after excess settlement funds deducted
|
receipt.netPosted = requiredAmountPosted.toUint232();
|
receipt.netPosted = requiredAmountPosted.toUint232();
| 37,821
|
101
|
// Convenience method to get account balances for given tokens./_trader Account to check balances for./_assetAddresses Array of token addresses./ return Account balances for each token.
|
function getExternalBalances(address _trader, address[] memory _assetAddresses)
public
view
returns (uint256[] memory)
|
function getExternalBalances(address _trader, address[] memory _assetAddresses)
public
view
returns (uint256[] memory)
| 52,631
|
10
|
// Proxy Implements delegation of calls to other contracts, with properforwarding of return values and bubbling of failures.It defines a fallback function that delegates all calls to the addressreturned by the abstract _implementation() internal function. /
|
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback () payable external {
_fallback();
}
receive () payable external {}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
|
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback () payable external {
_fallback();
}
receive () payable external {}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
| 2,039
|
1
|
// DEFINE CONSTANTS //DEFINE STRUCTURES // Admin Struct handles the admin mapping of address as well as the id to which they are /
|
struct Admin {
bool authorized;
uint id;
}
|
struct Admin {
bool authorized;
uint id;
}
| 16,704
|
12
|
// PLAYER DATA
|
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => RSdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => RSdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
|
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => RSdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => RSdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
| 28,177
|
68
|
// Loop until an address that matches the provided one is found.
|
bool found = false;
address target;
uint256 nonce = 0;
while (nonce < 10) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
|
bool found = false;
address target;
uint256 nonce = 0;
while (nonce < 10) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
| 30,013
|
762
|
// Gets the vote id of a given claim of a given Claim Assessor. /
|
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
|
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
| 28,855
|
23
|
// uint _sqrt = wmul(wmul(_x1, _y1), wmul(_x2, _y2)); _sqrt = sqrt(_sqrt); arbNum = sub(_sqrt, a); arbNum = arbNum / b;
|
}
|
}
| 17,521
|
15
|
// The token being sold
|
MintableToken public token;
|
MintableToken public token;
| 840
|
61
|
// Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}./
|
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
|
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
| 18,741
|
85
|
// Equals to bytes4(keccak256("onERC721Received(address,uint256,bytes)"))
|
bytes4 ERC721_RECEIVED = bytes4(0xf0b9e5ba);
require(
IERC721Receiver(to).onERC721Received(
assetId, holder, userData
) == ERC721_RECEIVED
);
|
bytes4 ERC721_RECEIVED = bytes4(0xf0b9e5ba);
require(
IERC721Receiver(to).onERC721Received(
assetId, holder, userData
) == ERC721_RECEIVED
);
| 8,123
|
92
|
// Called to get the current pool shares of a user/userAddress User address/ return Current pool shares of the user
|
function userShares(address userAddress)
public
view
override
returns (uint256)
|
function userShares(address userAddress)
public
view
override
returns (uint256)
| 48,978
|
5
|
// We read and store the value's index to prevent multiple reads from the same storage slot
|
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
|
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
| 8,100
|
123
|
// Developer team coverage
|
percentDevteam = _percentDevteam;
|
percentDevteam = _percentDevteam;
| 54,057
|
20
|
// Error codes that describe all possible failure reasons reported in the `TransactionRelayed` event `status` field.OK The transaction was successfully relayed and execution successful - never included in the event.RelayedCallFailed The transaction was relayed, but the relayed call failed.RejectedByPreRelayed The transaction was not relayed due to preRelatedCall reverting.RejectedByForwarder The transaction was not relayed due to forwarder check (signature,nonce).PostRelayedFailed The transaction was relayed and reverted due to postRelatedCall reverting.PaymasterBalanceChanged The transaction was relayed and reverted due to the paymaster balance change. /
|
enum RelayCallStatus {
address to,
address relayWorker,
bytes4 selector,
uint256 innerGasUsed,
bytes reason
);
address indexed relayManager,
address indexed relayWorker,
bytes32 indexed relayRequestID,
address from,
address to,
address paymaster,
bytes4 selector,
RelayCallStatus status,
uint256 charge
);
OK,
RelayedCallFailed,
RejectedByPreRelayed,
RejectedByForwarder,
RejectedByRecipientRevert,
PostRelayedFailed,
PaymasterBalanceChanged
}
|
enum RelayCallStatus {
address to,
address relayWorker,
bytes4 selector,
uint256 innerGasUsed,
bytes reason
);
address indexed relayManager,
address indexed relayWorker,
bytes32 indexed relayRequestID,
address from,
address to,
address paymaster,
bytes4 selector,
RelayCallStatus status,
uint256 charge
);
OK,
RelayedCallFailed,
RejectedByPreRelayed,
RejectedByForwarder,
RejectedByRecipientRevert,
PostRelayedFailed,
PaymasterBalanceChanged
}
| 11,189
|
25
|
// Expiration timestamp for migrated domains.
|
uint public transferPeriodEnds;
|
uint public transferPeriodEnds;
| 33,810
|
30
|
// Transfers the NFT to the owner/tokenId The id of the erc721
|
function retrieveNFT(uint256 tokenId) external {
// must be the owner of the NFT
require(msg.sender == deposits[tokenId].owner, "Not the owner");
// remove information related to tokenId
delete deposits[tokenId];
// transfer ownership to original owner
INonfungiblePositionManager(nonfungiblePositionManager)
.safeTransferFrom(address(this), msg.sender, tokenId);
}
|
function retrieveNFT(uint256 tokenId) external {
// must be the owner of the NFT
require(msg.sender == deposits[tokenId].owner, "Not the owner");
// remove information related to tokenId
delete deposits[tokenId];
// transfer ownership to original owner
INonfungiblePositionManager(nonfungiblePositionManager)
.safeTransferFrom(address(this), msg.sender, tokenId);
}
| 57,039
|
31
|
// lambo delivery service
|
withdraw();
|
withdraw();
| 2,134
|
74
|
// Update all values
|
_claimAndLock(msg.sender);
UserInfo storage user = users[msg.sender];
if (user.depositAmount == 0) {
revert SasWecoin__NoBalanceToWithdraw();
}
|
_claimAndLock(msg.sender);
UserInfo storage user = users[msg.sender];
if (user.depositAmount == 0) {
revert SasWecoin__NoBalanceToWithdraw();
}
| 10,613
|
42
|
// Set the additional logic handlers _priceHandlerAddr The price handler _refundHandlerAddr The refund handler /
|
// function setHandlers (address _priceHandlerAddr, address _refundHandlerAddr, address _missionEventsHandlerAddr ) external onlyAdmin {
function setHandlers (address _priceHandlerAddr, address _refundHandlerAddr ) external onlyAdmin {
// Set the handler
priceHandler = PriceHandler(_priceHandlerAddr);
refundHandler = RefundHandler(_refundHandlerAddr);
// missionEventsHandler = MissionEventsHandler(_missionEventsHandlerAddr);
}
/**
* @dev Mints new tokens for pre-purchased bottles
* @param bottles The number of tokens to mint.
*
* This function allows users to mint new tokens by sending the
* required amount. It ensures that the daily minting limit
* is not exceeded and refunds any excess funds sent by the user.
*/
function mintNFT(uint16 bottles) public payable nonReentrant whenNotPaused {
uint256 today = block.timestamp / 1 days;
if (today > lastMintedDay) {
supplyMintedToday = 0;
lastMintedDay = today;
}
require(supplyMintedToday < supplyPerDay, "Maximum number of daily pre-sales reached");
require(bottles <= (supplyPerDay - supplyMintedToday), "Daily supply not enough for requested mint");
uint256 currentPrice = priceHandler.price();
uint256 totalPrice = currentPrice * bottles;
require(msg.value >= totalPrice, "Funds sent is less than the price of token");
// Refund any excess sent
int256 refundAmount = int256(msg.value) - int256(totalPrice);
if (refundAmount > 0) {
payable(msg.sender).transfer(uint256(refundAmount));
}
for (uint256 i = 0; i < bottles; i++) {
uint256 tokenId = uint256(supplyUsed).add(1); //
require(supply > 0, "Maximum number of pre-sales reached");
// tokens are 1 based not zero based with overrun check
// tokenId = tokenId > initialSupply ? initialSupply : tokenId;
_safeMint(msg.sender, tokenId);
emit TokenMinted(msg.sender, currentPrice, tokenId, tokenURI(tokenId));
// Increment SupplyUsed. Note we can use tokenId as it is 1 based
supplyUsed = uint16(tokenId);
// Decrement the overall supply. under run check
if (supply > 0) {
supply = uint16(supply.sub(1));
}
// Increment the daily supply. Overrun check
uint16 _supplyMintedToday = uint16(supplyMintedToday.add(1));
supplyMintedToday = _supplyMintedToday > supplyPerDay ? supplyPerDay : _supplyMintedToday;
refundHandler.addMinterForRefund(tokenId, msg.sender, owner());
}
payable(owner()).transfer(totalPrice);
}
event TokenMinted(address indexed to, uint256 paymentReceived, uint256 tokenId, string tokenURI);
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, '/nft/', tokenId.toString())) : "";
}
/**
* @dev returns storefront metadata
*/
function contractURI() public view returns (string memory) {
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, '/metadata')) : "";
}
/**
* @dev Update Metadata - DEVONLY should be replaced by ENS but we probably still need to emit the event
* @param _baseURI new base URI for metadata change
*/
function updateMetadata( string memory _baseURI ) external onlyAdmin {
baseURI = _baseURI;
if ( supplyUsed != 0 ) {
emit BatchMetadataUpdate(0, supplyUsed - 1);
}
}
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
// Refunding
/**
* @dev Prepares refunds for all token minters based on their token balance. Passing msg.value funds the contract.
* This function calculates the refund amount per token and stores the total refund amount for each minter in a mapping.
* It requires the contract to have sufficient balance to cover all refunds.
*/
function prepareRefunds() public payable onlyAdmin {
require(msg.value > 0, "Incorrect funding amount");
refundHandler.prepareRefunds(address(this).balance, msg.sender);
}
/**
* @dev Sends the specified number of refunds to the corresponding minters.
* This function transfers the refund amount to each minter, burns their NFT, and emits a RefundProcessed event.
* It should be called after prepareRefunds() to actually send the refunds.
* @param numRefunds The number of refunds to send.
*/
function sendRefund(uint16 numRefunds) external onlyAdmin {
refundHandler.sendRefunds(numRefunds, msg.sender);
}
// Security Functions
function ensureAdmin( address _caller ) external view {
require(hasRole(ADMIN_ROLE, _caller), "Caller is not owner or admin");
}
/**
* @dev Pause the contract
*/
function pause() public onlyAdmin {
_pause();
}
/**
* @dev Unpause the contract
*/
function unpause() public onlyAdmin {
_unpause();
}
/**
* @dev Transfers ownership of the contract to a new address. Can only be called by the current owner.
* @param newOwner Address of the new owner.
*/
function transferOwnership(address newOwner) public override onlyOwner {
require(newOwner != address(0), "New owner cannot be the zero address");
// Call the original transferOwnership function from Ownable
super.transferOwnership(newOwner);
// Transfer additional ADMIN_ROLE to the new owner
grantRole(ADMIN_ROLE, newOwner);
revokeRole(ADMIN_ROLE, msg.sender);
}
/**
* @dev override pause to emit paused event
*/
function _pause() internal virtual override {
super._pause();
}
/**
* @dev override unpause to emit unpaused event
*/
function _unpause() internal virtual override {
super._unpause();
}
/**
* @dev Grants the ADMIN_ROLE to the specified account. Can only be called by the contract owner.
* Emits an AdminRoleGranted event upon successful assignment.
* @param account The address of the account to be granted the ADMIN_ROLE.
*/
function grantAdminRole(address account) external onlyOwner {
grantRole(ADMIN_ROLE, account);
emit AdminRoleGranted(account);
}
event AdminRoleGranted(address account);
/**
* @dev Revokes the ADMIN_ROLE from the specified account. Can only be called by the contract owner.
* Emits an AdminRoleRevoked event upon successful removal.
* @param account The address of the account to have the ADMIN_ROLE revoked.
*/
function revokeAdminRole(address account) public onlyOwner {
revokeRole(ADMIN_ROLE, account);
emit AdminRoleRevoked(account);
}
event AdminRoleRevoked(address account);
/**
* @dev Prepares refunds for all token minters based on their token balance. Passing msg.value funds the contract.
* This function calculates the refund amount per token and stores the total refund amount for each minter in a mapping.
* It requires the contract to have sufficient balance to cover all refunds.
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
emit AdminRoleRenounced(role, account);
}
event AdminRoleRenounced(bytes32 indexed role, address indexed account);
// // Launch & Recovery Events management
//
// /**
// * @dev Sets a new launch event date as a Unix timestamp. Can only be called by the owner or an admin.
// * The new launch event date must be greater than the current block timestamp and the recovery event date.
// * @param _launchDate The new launch event date as a Unix timestamp.
// */
// function setLaunchDate(uint256 _launchDate) external onlyAdmin {
// missionEventsHandler.setLaunchDate(_launchDate, msg.sender);
// emit LaunchDateSet(_launchDate);
// }
// event LaunchDateSet(uint256 launchDate);
//
// /**
// * @dev Sets a new recovery event date as a Unix timestamp. Can only be called by the owner or an admin.
// * The new recovery event date must be greater than the current block timestamp and the launch event date.
// * @param _recoveryDate The new recovery event date as a Unix timestamp.
// */
// function setRecoveryDate(uint256 _recoveryDate) external onlyAdmin {
// missionEventsHandler.setRecoveryDate(_recoveryDate, msg.sender);
// emit RecoveryDateSet(_recoveryDate);
// }
// event RecoveryDateSet(uint256 recoveryDate);
//
// /**
// * @dev Returns the launch event date as a Unix timestamp.
// * @return The launch date.
// */
// function launchDate() external view returns (uint256) {
// return missionEventsHandler.launchDate();
// }
//
// /**
// * @dev Returns the recovery event date as a Unix timestamp.
// * @return The recovery date.
// */
// function recoveryDate() external view returns (uint256) {
// return missionEventsHandler.recoveryDate();
// }
// Pricing
/**
* @dev Sets a new price for minting a token in USD. The USD price should be 8 decimal places
* @param _usdPrice The new price in usdPrice.
*/
function setPrice(uint256 _usdPrice) external onlyAdmin {
priceHandler.setPrice(_usdPrice, msg.sender);
emit PriceUpdated(_usdPrice);
}
event PriceUpdated(uint256 newPrice);
/**
* @dev Sets the feed for the price conversion in getPrice()
* @param _priceFeedAddress The address of the price feed oracle
*/
function setPriceFeed( address _priceFeedAddress ) external onlyAdmin {
priceHandler.setPriceFeed(_priceFeedAddress, msg.sender);
}
/**
* @dev Returns the current price for minting a token in MATIC.
* @return The current price in Matic.
*/
function price() external view returns (uint256) {
return priceHandler.price();
}
/**
* @dev Returns the current price for minting a token in USD.
* @return The current price in USD.
*/
function priceInUSD() external view returns (uint256) {
return priceHandler.priceInUSD();
}
}
|
// function setHandlers (address _priceHandlerAddr, address _refundHandlerAddr, address _missionEventsHandlerAddr ) external onlyAdmin {
function setHandlers (address _priceHandlerAddr, address _refundHandlerAddr ) external onlyAdmin {
// Set the handler
priceHandler = PriceHandler(_priceHandlerAddr);
refundHandler = RefundHandler(_refundHandlerAddr);
// missionEventsHandler = MissionEventsHandler(_missionEventsHandlerAddr);
}
/**
* @dev Mints new tokens for pre-purchased bottles
* @param bottles The number of tokens to mint.
*
* This function allows users to mint new tokens by sending the
* required amount. It ensures that the daily minting limit
* is not exceeded and refunds any excess funds sent by the user.
*/
function mintNFT(uint16 bottles) public payable nonReentrant whenNotPaused {
uint256 today = block.timestamp / 1 days;
if (today > lastMintedDay) {
supplyMintedToday = 0;
lastMintedDay = today;
}
require(supplyMintedToday < supplyPerDay, "Maximum number of daily pre-sales reached");
require(bottles <= (supplyPerDay - supplyMintedToday), "Daily supply not enough for requested mint");
uint256 currentPrice = priceHandler.price();
uint256 totalPrice = currentPrice * bottles;
require(msg.value >= totalPrice, "Funds sent is less than the price of token");
// Refund any excess sent
int256 refundAmount = int256(msg.value) - int256(totalPrice);
if (refundAmount > 0) {
payable(msg.sender).transfer(uint256(refundAmount));
}
for (uint256 i = 0; i < bottles; i++) {
uint256 tokenId = uint256(supplyUsed).add(1); //
require(supply > 0, "Maximum number of pre-sales reached");
// tokens are 1 based not zero based with overrun check
// tokenId = tokenId > initialSupply ? initialSupply : tokenId;
_safeMint(msg.sender, tokenId);
emit TokenMinted(msg.sender, currentPrice, tokenId, tokenURI(tokenId));
// Increment SupplyUsed. Note we can use tokenId as it is 1 based
supplyUsed = uint16(tokenId);
// Decrement the overall supply. under run check
if (supply > 0) {
supply = uint16(supply.sub(1));
}
// Increment the daily supply. Overrun check
uint16 _supplyMintedToday = uint16(supplyMintedToday.add(1));
supplyMintedToday = _supplyMintedToday > supplyPerDay ? supplyPerDay : _supplyMintedToday;
refundHandler.addMinterForRefund(tokenId, msg.sender, owner());
}
payable(owner()).transfer(totalPrice);
}
event TokenMinted(address indexed to, uint256 paymentReceived, uint256 tokenId, string tokenURI);
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, '/nft/', tokenId.toString())) : "";
}
/**
* @dev returns storefront metadata
*/
function contractURI() public view returns (string memory) {
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, '/metadata')) : "";
}
/**
* @dev Update Metadata - DEVONLY should be replaced by ENS but we probably still need to emit the event
* @param _baseURI new base URI for metadata change
*/
function updateMetadata( string memory _baseURI ) external onlyAdmin {
baseURI = _baseURI;
if ( supplyUsed != 0 ) {
emit BatchMetadataUpdate(0, supplyUsed - 1);
}
}
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
// Refunding
/**
* @dev Prepares refunds for all token minters based on their token balance. Passing msg.value funds the contract.
* This function calculates the refund amount per token and stores the total refund amount for each minter in a mapping.
* It requires the contract to have sufficient balance to cover all refunds.
*/
function prepareRefunds() public payable onlyAdmin {
require(msg.value > 0, "Incorrect funding amount");
refundHandler.prepareRefunds(address(this).balance, msg.sender);
}
/**
* @dev Sends the specified number of refunds to the corresponding minters.
* This function transfers the refund amount to each minter, burns their NFT, and emits a RefundProcessed event.
* It should be called after prepareRefunds() to actually send the refunds.
* @param numRefunds The number of refunds to send.
*/
function sendRefund(uint16 numRefunds) external onlyAdmin {
refundHandler.sendRefunds(numRefunds, msg.sender);
}
// Security Functions
function ensureAdmin( address _caller ) external view {
require(hasRole(ADMIN_ROLE, _caller), "Caller is not owner or admin");
}
/**
* @dev Pause the contract
*/
function pause() public onlyAdmin {
_pause();
}
/**
* @dev Unpause the contract
*/
function unpause() public onlyAdmin {
_unpause();
}
/**
* @dev Transfers ownership of the contract to a new address. Can only be called by the current owner.
* @param newOwner Address of the new owner.
*/
function transferOwnership(address newOwner) public override onlyOwner {
require(newOwner != address(0), "New owner cannot be the zero address");
// Call the original transferOwnership function from Ownable
super.transferOwnership(newOwner);
// Transfer additional ADMIN_ROLE to the new owner
grantRole(ADMIN_ROLE, newOwner);
revokeRole(ADMIN_ROLE, msg.sender);
}
/**
* @dev override pause to emit paused event
*/
function _pause() internal virtual override {
super._pause();
}
/**
* @dev override unpause to emit unpaused event
*/
function _unpause() internal virtual override {
super._unpause();
}
/**
* @dev Grants the ADMIN_ROLE to the specified account. Can only be called by the contract owner.
* Emits an AdminRoleGranted event upon successful assignment.
* @param account The address of the account to be granted the ADMIN_ROLE.
*/
function grantAdminRole(address account) external onlyOwner {
grantRole(ADMIN_ROLE, account);
emit AdminRoleGranted(account);
}
event AdminRoleGranted(address account);
/**
* @dev Revokes the ADMIN_ROLE from the specified account. Can only be called by the contract owner.
* Emits an AdminRoleRevoked event upon successful removal.
* @param account The address of the account to have the ADMIN_ROLE revoked.
*/
function revokeAdminRole(address account) public onlyOwner {
revokeRole(ADMIN_ROLE, account);
emit AdminRoleRevoked(account);
}
event AdminRoleRevoked(address account);
/**
* @dev Prepares refunds for all token minters based on their token balance. Passing msg.value funds the contract.
* This function calculates the refund amount per token and stores the total refund amount for each minter in a mapping.
* It requires the contract to have sufficient balance to cover all refunds.
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
emit AdminRoleRenounced(role, account);
}
event AdminRoleRenounced(bytes32 indexed role, address indexed account);
// // Launch & Recovery Events management
//
// /**
// * @dev Sets a new launch event date as a Unix timestamp. Can only be called by the owner or an admin.
// * The new launch event date must be greater than the current block timestamp and the recovery event date.
// * @param _launchDate The new launch event date as a Unix timestamp.
// */
// function setLaunchDate(uint256 _launchDate) external onlyAdmin {
// missionEventsHandler.setLaunchDate(_launchDate, msg.sender);
// emit LaunchDateSet(_launchDate);
// }
// event LaunchDateSet(uint256 launchDate);
//
// /**
// * @dev Sets a new recovery event date as a Unix timestamp. Can only be called by the owner or an admin.
// * The new recovery event date must be greater than the current block timestamp and the launch event date.
// * @param _recoveryDate The new recovery event date as a Unix timestamp.
// */
// function setRecoveryDate(uint256 _recoveryDate) external onlyAdmin {
// missionEventsHandler.setRecoveryDate(_recoveryDate, msg.sender);
// emit RecoveryDateSet(_recoveryDate);
// }
// event RecoveryDateSet(uint256 recoveryDate);
//
// /**
// * @dev Returns the launch event date as a Unix timestamp.
// * @return The launch date.
// */
// function launchDate() external view returns (uint256) {
// return missionEventsHandler.launchDate();
// }
//
// /**
// * @dev Returns the recovery event date as a Unix timestamp.
// * @return The recovery date.
// */
// function recoveryDate() external view returns (uint256) {
// return missionEventsHandler.recoveryDate();
// }
// Pricing
/**
* @dev Sets a new price for minting a token in USD. The USD price should be 8 decimal places
* @param _usdPrice The new price in usdPrice.
*/
function setPrice(uint256 _usdPrice) external onlyAdmin {
priceHandler.setPrice(_usdPrice, msg.sender);
emit PriceUpdated(_usdPrice);
}
event PriceUpdated(uint256 newPrice);
/**
* @dev Sets the feed for the price conversion in getPrice()
* @param _priceFeedAddress The address of the price feed oracle
*/
function setPriceFeed( address _priceFeedAddress ) external onlyAdmin {
priceHandler.setPriceFeed(_priceFeedAddress, msg.sender);
}
/**
* @dev Returns the current price for minting a token in MATIC.
* @return The current price in Matic.
*/
function price() external view returns (uint256) {
return priceHandler.price();
}
/**
* @dev Returns the current price for minting a token in USD.
* @return The current price in USD.
*/
function priceInUSD() external view returns (uint256) {
return priceHandler.priceInUSD();
}
}
| 29,420
|
0
|
// Addresses that can unlock
|
address[] public ADMIN_ADDRESS;
mapping(uint256 => bool) public aiUnlocked; // Token ID => unlocked
event Unlock(uint256[] tokenIds);
|
address[] public ADMIN_ADDRESS;
mapping(uint256 => bool) public aiUnlocked; // Token ID => unlocked
event Unlock(uint256[] tokenIds);
| 29,185
|
322
|
// redeemTokens = redeemAmountIn 1e18 / exchangeRate. must be more than 0a rounding error means we need another small addition
|
if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){
deleveragedAmount = deleveragedAmount -10;
cToken.redeemUnderlying(deleveragedAmount);
|
if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){
deleveragedAmount = deleveragedAmount -10;
cToken.redeemUnderlying(deleveragedAmount);
| 30,716
|
270
|
// Set max supply, cost per category and size.
|
function setRate(uint256 _size, uint256 _cost, uint256 _total, string memory _rarity) public onlyOwner {
rates[_size][_rarity].cost = _cost;
rates[_size][_rarity].total = _total;
rates[_size][_rarity].valid = true;
}
|
function setRate(uint256 _size, uint256 _cost, uint256 _total, string memory _rarity) public onlyOwner {
rates[_size][_rarity].cost = _cost;
rates[_size][_rarity].total = _total;
rates[_size][_rarity].valid = true;
}
| 39,024
|
247
|
// transfer funds to token owner
|
(bool success, ) = payable(msg.sender).call{ value: totalPayout }("");
|
(bool success, ) = payable(msg.sender).call{ value: totalPayout }("");
| 48,764
|
6
|
// IERC165
|
function supportsInterface(bytes4 interfaceId) public view virtual override( IERC165, WaifuHouseDAOCore ) returns( bool ){
return
interfaceId == type(IERC721Enumerable).interfaceId ||
interfaceId == type(IERC721).interfaceId ||
super.supportsInterface(interfaceId);
}
|
function supportsInterface(bytes4 interfaceId) public view virtual override( IERC165, WaifuHouseDAOCore ) returns( bool ){
return
interfaceId == type(IERC721Enumerable).interfaceId ||
interfaceId == type(IERC721).interfaceId ||
super.supportsInterface(interfaceId);
}
| 103
|
55
|
// Map of users address and their configuration data (userAddress => userConfiguration)
|
mapping(address => UserConfigurationMap) _usersConfig;
|
mapping(address => UserConfigurationMap) _usersConfig;
| 22,780
|
88
|
// return Number of transactions, both enabled and disabled, in transactions list. /
|
function transactionsSize()
external
view
returns (uint256)
|
function transactionsSize()
external
view
returns (uint256)
| 3,311
|
1
|
// Methods
|
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
|
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| 4,380
|
32
|
// function to handle ERC20 bridging to receipent via NativeOptimism-Bridge This method is payable because the caller is doing token transfer and briding operation token address of token being bridged receiverAddress address of receiver of bridged tokens customBridgeAddress OptimismBridge that Performs the logic for deposits by informing the L2 Deposited Tokencontract of the deposit and calling a handler to lock the L1 funds. (e.g. transferFrom) l2Gas Gas limit required to complete the deposit on L2. optimismData extra data needed for optimism bridge amount amount being bridged interfaceId interfaceId to be set offchain which is used to select one of the 3
|
function bridgeERC20To(
address token,
address receiverAddress,
address customBridgeAddress,
uint32 l2Gas,
OptimismERC20Data calldata optimismData,
uint256 amount,
uint256 interfaceId,
address l2Token,
bytes calldata data
|
function bridgeERC20To(
address token,
address receiverAddress,
address customBridgeAddress,
uint32 l2Gas,
OptimismERC20Data calldata optimismData,
uint256 amount,
uint256 interfaceId,
address l2Token,
bytes calldata data
| 3,361
|
195
|
// function _doSafePowahUpdatedAcceptanceCheck(address _owner,uint256 _id,uint256 _oldPowah,uint256 _newPowah)private
|
// {
// if (_owner.isContract() && _owner.supportsERC165()) {
// if (
// IERC165(_owner).supportsInterface(
// IStarUpdateListener(0).onPowahUpdated.selector
// )
// ) {
// IStarUpdateListener(_owner).onPowahUpdated(_id, _oldPowah, _newPowah);
// }
// }
// }
|
// {
// if (_owner.isContract() && _owner.supportsERC165()) {
// if (
// IERC165(_owner).supportsInterface(
// IStarUpdateListener(0).onPowahUpdated.selector
// )
// ) {
// IStarUpdateListener(_owner).onPowahUpdated(_id, _oldPowah, _newPowah);
// }
// }
// }
| 42,130
|
9
|
// check to see if artist exists, if not then add it
|
if(!artist_exists[_artist]) {
artist.push(_artist);
artist_exists[_artist] = true;
genreToArtists[_genre].push(_artist);
}
|
if(!artist_exists[_artist]) {
artist.push(_artist);
artist_exists[_artist] = true;
genreToArtists[_genre].push(_artist);
}
| 27,416
|
54
|
// We use a single lock for the whole contract. /
|
bool private reentrancy_lock = false;
|
bool private reentrancy_lock = false;
| 25,848
|
1
|
// V1 - V5: OK
|
address public owner;
|
address public owner;
| 13,144
|
172
|
// _amount The total settlement proceeds of a trade or claimreturn The amount of fees the market creator will receive /
|
function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256) {
return feeDivisor == 0 ? 0 : _amount / feeDivisor;
}
|
function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256) {
return feeDivisor == 0 ? 0 : _amount / feeDivisor;
}
| 31,622
|
28
|
// Do not allow approval if amount exceeds locked amount
|
unapprovbal=balanceOf[msg.sender].sub(_value,"ERC20: Allowance exceeds balance of approver");
require(unapprovbal>=LockedTokens[msg.sender],"ERC20: Approval amount exceeds locked amount ");
_allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
|
unapprovbal=balanceOf[msg.sender].sub(_value,"ERC20: Allowance exceeds balance of approver");
require(unapprovbal>=LockedTokens[msg.sender],"ERC20: Approval amount exceeds locked amount ");
_allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
| 4,469
|
9
|
// Define a struct 'Item' with the following fields:
|
struct Item {
uint sku; // Stock Keeping Unit (SKU)
uint upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer
address ownerID; // Metamask-Ethereum address of the current owner as the product moves through 8 stages
address originFarmerID; // Metamask-Ethereum address of the Farmer
string originFarmName; // Farmer Name
string originFarmInformation; // Farmer Information
string originFarmLatitude; // Farm Latitude
string originFarmLongitude; // Farm Longitude
uint productID; // Product ID potentially a combination of upc + sku
string productNotes; // Product Notes
uint productPrice; // Product Price
State itemState; // Product State as represented in the enum above
address distributorID; // Metamask-Ethereum address of the Distributor
address retailerID; // Metamask-Ethereum address of the Retailer
address payable consumerID; // Metamask-Ethereum address of the Consumer
}
|
struct Item {
uint sku; // Stock Keeping Unit (SKU)
uint upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer
address ownerID; // Metamask-Ethereum address of the current owner as the product moves through 8 stages
address originFarmerID; // Metamask-Ethereum address of the Farmer
string originFarmName; // Farmer Name
string originFarmInformation; // Farmer Information
string originFarmLatitude; // Farm Latitude
string originFarmLongitude; // Farm Longitude
uint productID; // Product ID potentially a combination of upc + sku
string productNotes; // Product Notes
uint productPrice; // Product Price
State itemState; // Product State as represented in the enum above
address distributorID; // Metamask-Ethereum address of the Distributor
address retailerID; // Metamask-Ethereum address of the Retailer
address payable consumerID; // Metamask-Ethereum address of the Consumer
}
| 39,948
|
6
|
// Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 QuicForDev;
uint256 QuicForFarmer;
uint256 QuicForLP;
uint256 QuicForCom;
uint256 QuicForFounders;
(QuicForDev, QuicForFarmer, QuicForLP, QuicForCom, QuicForFounders) = getPoolReward(pool.lastRewardBlock, block.number, pool.allocPoint);
Quic.mint(address(this), QuicForFarmer);
pool.accQuicPerShare = pool.accQuicPerShare.add(QuicForFarmer.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
if (QuicForDev > 0) {
Quic.mint(address(devaddr), QuicForDev);
//Dev fund has xx% locked during the starting bonus period. After which locked funds drip out linearly each block over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
Quic.lock(address(devaddr), QuicForDev.mul(75).div(100));
}
}
if (QuicForLP > 0) {
Quic.mint(liquidityaddr, QuicForLP);
//LP + Partnership fund has only xx% locked over time as most of it is needed early on for incentives and listings. The locked amount will drip out linearly each block after the bonus period.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
Quic.lock(address(liquidityaddr), QuicForLP.mul(45).div(100));
}
}
if (QuicForCom > 0) {
Quic.mint(comfundaddr, QuicForCom);
//Community Fund has xx% locked during bonus period and then drips out linearly over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
Quic.lock(address(comfundaddr), QuicForCom.mul(85).div(100));
}
}
if (QuicForFounders > 0) {
Quic.mint(founderaddr, QuicForFounders);
//The Founders reward has xx% of their funds locked during the bonus period which then drip out linearly per block over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
Quic.lock(address(founderaddr), QuicForFounders.mul(95).div(100));
}
}
}
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 QuicForDev;
uint256 QuicForFarmer;
uint256 QuicForLP;
uint256 QuicForCom;
uint256 QuicForFounders;
(QuicForDev, QuicForFarmer, QuicForLP, QuicForCom, QuicForFounders) = getPoolReward(pool.lastRewardBlock, block.number, pool.allocPoint);
Quic.mint(address(this), QuicForFarmer);
pool.accQuicPerShare = pool.accQuicPerShare.add(QuicForFarmer.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
if (QuicForDev > 0) {
Quic.mint(address(devaddr), QuicForDev);
//Dev fund has xx% locked during the starting bonus period. After which locked funds drip out linearly each block over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
Quic.lock(address(devaddr), QuicForDev.mul(75).div(100));
}
}
if (QuicForLP > 0) {
Quic.mint(liquidityaddr, QuicForLP);
//LP + Partnership fund has only xx% locked over time as most of it is needed early on for incentives and listings. The locked amount will drip out linearly each block after the bonus period.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
Quic.lock(address(liquidityaddr), QuicForLP.mul(45).div(100));
}
}
if (QuicForCom > 0) {
Quic.mint(comfundaddr, QuicForCom);
//Community Fund has xx% locked during bonus period and then drips out linearly over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
Quic.lock(address(comfundaddr), QuicForCom.mul(85).div(100));
}
}
if (QuicForFounders > 0) {
Quic.mint(founderaddr, QuicForFounders);
//The Founders reward has xx% of their funds locked during the bonus period which then drip out linearly per block over 3 years.
if (block.number <= FINISH_BONUS_AT_BLOCK) {
Quic.lock(address(founderaddr), QuicForFounders.mul(95).div(100));
}
}
}
| 4,052
|
121
|
// Flat fee for NFT<->NFT trades (represented in wei of ETHER) Default to 0.001 ETH
|
uint256 public flatFee = 1000000000000000;
|
uint256 public flatFee = 1000000000000000;
| 39,760
|
137
|
// get the current status for the proposal. /
|
function getStatus(bytes32 proposeId)
external
view
override
returns (
uint128 appliedMinimumVote,
uint128 currentApprovalVoteSum,
uint128 currentDenialVoteSum,
uint32 prevoteDeadline,
uint32 mainvoteDeadline,
|
function getStatus(bytes32 proposeId)
external
view
override
returns (
uint128 appliedMinimumVote,
uint128 currentApprovalVoteSum,
uint128 currentDenialVoteSum,
uint32 prevoteDeadline,
uint32 mainvoteDeadline,
| 2,125
|
10
|
// set reward multiplier for users who staked in LM staking contract based on NFT locked by users
|
function _setLMStakingRewardMultiplier() internal {
uint256 _multiplier;
if (_nftStakerTokens[_msgSender()].contains(SILVER_NFT_ID)) {
_multiplier = SILVER_NFT_BOOST;
} else if (_nftStakerTokens[_msgSender()].contains(BRONZE_NFT_ID)) {
_multiplier = BRONZE_NFT_BOOST;
}
liquidityMiningStakingETH.setRewardMultiplier(_msgSender(), _multiplier);
// liquidityMiningStakingUSDT.setRewardMultiplier(_msgSender(), _multiplier);
}
|
function _setLMStakingRewardMultiplier() internal {
uint256 _multiplier;
if (_nftStakerTokens[_msgSender()].contains(SILVER_NFT_ID)) {
_multiplier = SILVER_NFT_BOOST;
} else if (_nftStakerTokens[_msgSender()].contains(BRONZE_NFT_ID)) {
_multiplier = BRONZE_NFT_BOOST;
}
liquidityMiningStakingETH.setRewardMultiplier(_msgSender(), _multiplier);
// liquidityMiningStakingUSDT.setRewardMultiplier(_msgSender(), _multiplier);
}
| 59,746
|
5
|
// No calls to zero address allows us to check that minion submitted the proposal without getting the proposal struct from parent moloch
|
require(actionTo != address(0), "invalid actionTo");
uint256 proposalId = moloch.submitProposal(
address(this),
0,
0,
0,
molochDepositToken,
0,
molochDepositToken,
|
require(actionTo != address(0), "invalid actionTo");
uint256 proposalId = moloch.submitProposal(
address(this),
0,
0,
0,
molochDepositToken,
0,
molochDepositToken,
| 34,937
|
5
|
// Emitted when `claim` is called on the origin domain recipient - Address on origin chain to send claimed funds to total - Total amount claimed transferIds - TransferIds to claim /
|
event Claimed(address indexed recipient, uint256 total, bytes32[] transferIds);
|
event Claimed(address indexed recipient, uint256 total, bytes32[] transferIds);
| 11,905
|
36
|
// mint the amount
|
totalSupply += amount;
|
totalSupply += amount;
| 4,308
|
172
|
// Uniswap exchange protocol references
|
IUniswap private uniswapFactory = IUniswap(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);
address public uniswapExchange;
constructor(
string memory name,
string memory symbol,
string memory _stamp,
uint8 decimals,
address _fundsToken,
address[] memory ownership,
|
IUniswap private uniswapFactory = IUniswap(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);
address public uniswapExchange;
constructor(
string memory name,
string memory symbol,
string memory _stamp,
uint8 decimals,
address _fundsToken,
address[] memory ownership,
| 41,384
|
101
|
// make the swap
|
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
|
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
| 4,414
|
17
|
// Pause the contract
|
function pause() public onlyOwner {
require(
msg.sender == owner,
"Only the contract owner can call this function"
);
require(!investmentContractData.paused, "Contract is already paused"); // Check if the contract is already paused
investmentContractData.paused = true;
}
|
function pause() public onlyOwner {
require(
msg.sender == owner,
"Only the contract owner can call this function"
);
require(!investmentContractData.paused, "Contract is already paused"); // Check if the contract is already paused
investmentContractData.paused = true;
}
| 21,875
|
10
|
// internal function to switch to new month. records for new month the current monthlyReputationDistribution /
|
function _updateMonth() internal {
uint256 month = block.timestamp / 30 days;
if (month != currentMonth) {
//update new month
currentMonth = month;
months[currentMonth]
.monthlyDistribution = monthlyReputationDistribution;
}
}
|
function _updateMonth() internal {
uint256 month = block.timestamp / 30 days;
if (month != currentMonth) {
//update new month
currentMonth = month;
months[currentMonth]
.monthlyDistribution = monthlyReputationDistribution;
}
}
| 31,974
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.