comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
// --Public read-only functions--
// Internal functions
// Returns true if the gauntlet has expired. Otherwise, false. | function isGauntletExpired(address holder) internal view returns(bool) {
if (gauntletType[holder] != 0) {
if (gauntletType[holder] == 1) {
return (block.timestamp >= gauntletEnd[holder]);
} else if (gauntletType[holder] == 2) {
return (bitx.totalSupply() >= gauntletEnd[holder]);
} else if (gaun... | 0.5.1 |
// Same as usableBalanceOf, except the gauntlet is lifted when it's expired. | function updateUsableBalanceOf(address holder) internal returns(uint256) {
// isGauntletExpired is a _view_ function, with uses STATICCALL in solidity 0.5.0 or later.
// Since STATICCALLs can't modifiy the state, re-entry attacks aren't possible here.
if (isGauntletExpired(holder)) {
if (gauntletType[holde... | 0.5.1 |
// sends ETH to the specified account, using all the ETH BXTG has access to. | function sendETH(address payable to, uint256 amount) internal {
uint256 childTotalBalance = refHandler.totalBalance();
uint256 thisBalance = address(this).balance;
uint256 thisTotalBalance = thisBalance + bitx.myDividends(true);
if (childTotalBalance >= amount) {
// the refHanlder has enough of its own ... | 0.5.1 |
// Take the ETH we've got and distribute it among our token holders. | function distributeDividends(uint256 bonus, address bonuser) internal{
// Prevents "HELP I WAS THE LAST PERSON WHO SOLD AND I CAN'T WITHDRAW MY ETH WHAT DO????" (dividing by 0 results in a crash)
if (totalSupply > 0) {
uint256 tb = totalBalance();
uint256 delta = tb - lastTotalBalance;
if (delta > 0) ... | 0.5.1 |
// Clear out someone's dividends. | function clearDividends(address accountHolder) internal returns(uint256, uint256) {
uint256 payout = dividendsOf(accountHolder, false);
uint256 bonusPayout = bonuses[accountHolder];
payouts[accountHolder] += int256(payout * ROUNDING_MAGNITUDE);
bonuses[accountHolder] = 0;
// External apps can now get... | 0.5.1 |
// Withdraw 100% of someone's dividends | function withdrawDividends(address payable accountHolder) internal {
distributeDividends(0, NULL_ADDRESS); // Just in case BITX-only transactions happened.
uint256 payout;
uint256 bonusPayout;
(payout, bonusPayout) = clearDividends(accountHolder);
emit onWithdraw(accountHolder, payout, bonusPayout, false... | 0.5.1 |
/**
* Settle the pool, the winners are selected randomly and fee is transfer to the manager.
*/ | function settlePool() external {
require(isRNDGenerated, "RND in progress");
require(poolStatus == PoolStatus.INPROGRESS, "pool in progress");
// generate winnerIndexes until the numOfWinners reach
uint256 newRandom = randomResult;
uint256 offset = 0;
while(winner... | 0.6.10 |
/**
* The winners of the pool can call this function to transfer their winnings
* from the pool contract to their own address.
*/ | function collectRewards() external {
require(poolStatus == PoolStatus.CLOSED, "not settled");
for (uint256 i = 0; i < poolConfig.participantLimit; i = i.add(1)) {
address player = participants[i];
if (winnerIndexes.contains(i)) {
// if winner
... | 0.6.10 |
/**
* adds DeezNuts NFT to the CasinoEmployees (staking)
* @param account the address of the staker
* @param tokenIds the IDs of the Sheep and Wolves to stake
*/ | function addManyToCasino(address account, uint16[] calldata tokenIds, bytes32[][] calldata employmentProof) external whenNotPaused nonReentrant {
require(account == _msgSender(), "Rechek sender of transaction");
require(tokenIds.length > 0, "No tokens sent");
for (uint i = 0; i < tokenIds.length; i++) {
... | 0.8.7 |
/**
* adds a single Sheep to the Barn
* @param account the address of the staker
* @param tokenId the ID of the Sheep to add to the Barn
*/ | function _addTokenToCasino(address account, uint16 tokenId, bytes32[] calldata proofOfEmployment) internal whenNotPaused _updateEarnings {
uint72 tokenDailyRate = getDailyRateForToken(tokenId, proofOfEmployment);
casinoEmployees[tokenId] = Stake({
owner: account,
tokenId: uint16(tokenId),
valu... | 0.8.7 |
/**
* realize $NUTS earnings for a single Nut
* @param tokenId the ID of the Sheep to claim earnings from
* @param unstake whether or not to unstake the Sheep
* @return owed - the amount of $NUTS earned
*/ | function _claimNutFromCasino(uint16 tokenId, bool unstake) internal returns (uint128 owed) {
Stake memory stake = casinoEmployees[tokenId];
require(stake.owner == _msgSender(), "Not the stake owner");
if (totalNutsEarned < MAXIMUM_GLOBAL_NUTS) {
owed = uint128(((block.timestamp.sub(stake.value)).mu... | 0.8.7 |
/**
* emergency unstake tokens
* @param tokenIds the IDs of the tokens to claim earnings from
*/ | function rescue(uint16[] calldata tokenIds) external nonReentrant {
require(rescueEnabled, "RESCUE DISABLED");
uint16 tokenId;
Stake memory stake;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
stake = casinoEmployees[tokenId];
require(stake.owner == _msgSend... | 0.8.7 |
/**
* Creates a ProphetPool smart contract set the manager(owner) of the pool.
*
* @param _poolName Pool name
* @param _buyToken ERC20 token to enter the pool
* @param _manager Manager of the pool
* @param _feeRecipient Where the fee of the prophet pool go
* @p... | function createProphetPool(
string memory _poolName,
address _buyToken,
address _manager,
address _feeRecipient,
uint256 _chanceTokenId
) external onlyAllowedCreator(msg.sender) returns (address) {
require(_buyToken != address(0), "invalid buyToken");
... | 0.6.10 |
/**
* Creates a SecondChancePool smart contract set the manager(owner) of the pool.
*
* @param _poolName Pool name
* @param _rewardToken Reward token of the pool
* @param _manager Manager of the pool
* @param _chanceTokenId ERC1155 Token id for chance token
*/ | function createSecondChancePool(
string memory _poolName,
address _rewardToken,
address _manager,
uint256 _chanceTokenId
) external onlyAllowedCreator(msg.sender) returns (address) {
require(_rewardToken != address(0), "invalid rewardToken");
require(_manager !... | 0.6.10 |
/**
* OWNER ONLY: Toggle ability for passed addresses to create a prophet pool
*
* @param _creators Array creator addresses to toggle status
* @param _statuses Booleans indicating if matching creator can create
*/ | function updateCreatorStatus(address[] calldata _creators, bool[] calldata _statuses) external onlyOwner {
require(_creators.length == _statuses.length, "array mismatch");
require(_creators.length > 0, "invalid length");
for (uint256 i = 0; i < _creators.length; i++) {
address ... | 0.6.10 |
/**
* @param _startIndex start index
* @param _endIndex end index
* @param _revert sort array asc or desc
* @return the list of the beneficiary addresses
*/ | function paginationBeneficiaries(uint256 _startIndex, uint256 _endIndex, bool _revert) public view returns (address[] memory) {
uint256 startIndex = _startIndex;
uint256 endIndex = _endIndex;
if (startIndex >= _lockupBeneficiaries.length) {
return new address[](0);
}
if (endIndex > _lockupBeneficiari... | 0.5.16 |
/**
* @param _beneficiary beneficiary address
* @param _startIndex start index
* @param _endIndex end index
* @param _revert sort array asc or desc
* @return the list of the bundle identifies of beneficiary address
*/ | function paginationBundleIdentifiesOf(address _beneficiary, uint256 _startIndex, uint256 _endIndex, bool _revert) public view returns (uint256[] memory) {
uint256 startIndex = _startIndex;
uint256 endIndex = _endIndex;
if (startIndex >= _lockupIdsOfBeneficiary[_beneficiary].length) {
return new uint256[](0... | 0.5.16 |
// @param _startBlock
// @param _endBlock
// @param _wolkWallet
// @return success
// @dev Wolk Genesis Event [only accessible by Contract Owner] | function wolkGenesis(uint256 _startBlock, uint256 _endBlock, address _wolkWallet) onlyOwner returns (bool success){
require( (totalTokens < 1) && (!settlers[msg.sender]) && (_endBlock > _startBlock) );
start_block = _startBlock;
end_block = _endBlock;
multisigWallet = _wolkWallet;
... | 0.4.13 |
// @dev Token Generation Event for Wolk Protocol Token. TGE Participant send Eth into this func in exchange of Wolk Protocol Token | function tokenGenerationEvent() payable external {
require(!saleCompleted);
require( (block.number >= start_block) && (block.number <= end_block) );
uint256 tokens = safeMul(msg.value, 5*10**9); //exchange rate
uint256 checkedSupply = safeAdd(totalTokens, tokens);
require(ch... | 0.4.13 |
// @dev If Token Generation Minimum is Not Met, TGE Participants can call this func and request for refund | function refund() external {
require( (contribution[msg.sender] > 0) && (!saleCompleted) && (totalTokens < tokenGenerationMin) && (block.number > end_block) );
uint256 tokenBalance = balances[msg.sender];
uint256 refundBalance = contribution[msg.sender];
balances[msg.sender] = 0;
... | 0.4.13 |
// @param _serviceProvider
// @param _feeBasisPoints
// @return success
// @dev Set Service Provider fee -- only Contract Owner can do this, affects Service Provider settleSeller | function setServiceFee(address _serviceProvider, uint256 _feeBasisPoints) onlyOwner returns (bool success) {
if ( _feeBasisPoints <= 0 || _feeBasisPoints > 4000){
// revoke Settler privilege
settlers[_serviceProvider] = false;
feeBasisPoints[_serviceProvider] = 0;
... | 0.4.13 |
// @param _buyer
// @param _value
// @return success
// @dev Service Provider Settlement with Buyer: a small percent is burnt (set in setBurnRate, stored in burnBasisPoints) when funds are transferred from buyer to Service Provider [only accessible by settlers] | function settleBuyer(address _buyer, uint256 _value) onlySettler returns (bool success) {
require( (burnBasisPoints > 0) && (burnBasisPoints <= 1000) && authorized[_buyer][msg.sender] ); // Buyer must authorize Service Provider
if ( balances[_buyer] >= _value && _value > 0) {
var burnCap... | 0.4.13 |
/**
* @return the all phases detail
*/ | function getLockupPhases() public view returns (uint256[] memory ids, uint256[] memory percentages, uint256[] memory extraTimes, bool[] memory hasWithdrawals, bool[] memory canWithdrawals) {
ids = new uint256[](_lockupPhases.length);
percentages = new uint256[](_lockupPhases.length);
extraTimes = new uint256[]... | 0.5.16 |
// @param _owner
// @param _providerToAdd
// @return authorizationStatus
// @dev Grant authorization between account and Service Provider on buyers' behalf [only accessible by Contract Owner]
// @note Explicit permission from balance owner MUST be obtained beforehand | function grantService(address _owner, address _providerToAdd) onlyOwner returns (bool authorizationStatus) {
var isPreauthorized = authorized[_owner][msg.sender];
if (isPreauthorized && settlers[_providerToAdd] ) {
authorized[_owner][_providerToAdd] = true;
AuthorizeServicePr... | 0.4.13 |
/**
@dev given a token supply, reserve, CRR and a deposit amount (in the reserve token), calculates the return for a given change (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / 100) - 1)
@param _supply token total supply
@param _res... | function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _depositAmount) public constant returns (uint256) {
// validate input
require(_supply != 0 && _reserveBalance != 0 && _reserveRatio > 0 && _reserveRatio <= 100);
// special case for 0 de... | 0.4.13 |
/**
@dev given a token supply, reserve, CRR and a sell amount (in the main token), calculates the return for a given change (in the reserve token)
Formula:
Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / 100)))
@param _supply token total supply
@param _res... | function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _sellAmount) public constant returns (uint256) {
// validate input
require(_supply != 0 && _reserveBalance != 0 && _reserveRatio > 0 && _reserveRatio <= 100 && _sellAmount <= _supply);
// sp... | 0.4.13 |
/**
@dev Calculate (_baseN / _baseD) ^ (_expN / _expD)
Returns result upshifted by PRECISION
This method is overflow-safe
*/ | function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal returns (uint256 resN) {
uint256 logbase = ln(_baseN, _baseD);
// Not using safeDiv here, since safeDiv protects against
// precision loss. It’s unavoidable, however
// Both `ln` and `fixedExp` are ov... | 0.4.13 |
/**
input range:
- numerator: [1, uint256_max >> PRECISION]
- denominator: [1, uint256_max >> PRECISION]
output range:
[0, 0x9b43d4f8d6]
This method asserts outside of bounds
*/ | function ln(uint256 _numerator, uint256 _denominator) internal returns (uint256) {
// denominator > numerator: less than one yields negative values. Unsupported
assert(_denominator <= _numerator);
// log(1) is the lowest we can go
assert(_denominator != 0 && _numerator != 0);
... | 0.4.13 |
/**
input range:
[0x100000000,uint256_max]
output range:
[0, 0x9b43d4f8d6]
This method asserts outside of bounds
*/ | function fixedLoge(uint256 _x) internal returns (uint256 logE) {
/*
Since `fixedLog2_min` output range is max `0xdfffffffff`
(40 bits, or 5 bytes), we can use a very large approximation
for `ln(2)`. This one is used since it’s the max accuracy
of Python `ln(2)`
... | 0.4.13 |
/**
Returns log2(x >> 32) << 32 [1]
So x is assumed to be already upshifted 32 bits, and
the result is also upshifted 32 bits.
[1] The function returns a number which is lower than the
actual value
input-range :
[0x100000000,uint256_max]
output-range:
[0,0xdfffffffff]
This method asser... | function fixedLog2(uint256 _x) internal returns (uint256) {
// Numbers below 1 are negative.
assert( _x >= FIXED_ONE);
uint256 hi = 0;
while (_x >= FIXED_TWO) {
_x >>= 1;
hi += FIXED_ONE;
}
for (uint8 i = 0; i < PRECISION; ++i) {
... | 0.4.13 |
// @return Estimated Liquidation Cap
// @dev Liquidation Cap per transaction is used to ensure proper price discovery for Wolk Exchange | function EstLiquidationCap() public constant returns (uint256) {
if (saleCompleted){
var liquidationMax = safeDiv(safeMul(totalTokens, maxPerExchangeBP), 10000);
if (liquidationMax < 100 * 10**decimals){
liquidationMax = 100 * 10**decimals;
}
... | 0.4.13 |
// @param _wolkAmount
// @return ethReceivable
// @dev send Wolk into contract in exchange for eth, at an exchange rate based on the Bancor Protocol derivation and decrease totalSupply accordingly | function sellWolk(uint256 _wolkAmount) isTransferable() external returns(uint256) {
uint256 sellCap = EstLiquidationCap();
uint256 ethReceivable = calculateSaleReturn(totalTokens, reserveBalance, percentageETHReserve, _wolkAmount);
require( (sellCap >= _wolkAmount) && (balances[msg.sender] >=... | 0.4.13 |
// @param _exactWolk
// @return ethRefundable
// @dev send eth into contract in exchange for exact amount of Wolk tokens with margin of error of no more than 1 Wolk.
// @note Purchase with the insufficient eth will be cancelled and returned; exceeding eth balanance from purchase, if any, will be returned. | function purchaseExactWolk(uint256 _exactWolk) isTransferable() payable external returns(uint256){
uint256 wolkReceivable = calculatePurchaseReturn(totalTokens, reserveBalance, percentageETHReserve, msg.value);
if (wolkReceivable < _exactWolk){
// Cancel Insufficient Purchase
... | 0.4.13 |
/**
* @notice Transfers amount of _tokenId from-to addresses with safety call.
* If _to is a smart contract, will call onERC1155Received
* @dev ERC-1155
* @param _from Source address
* @param _to Destination address
* @param _tokenId ID of the token
* @param _value Transfer amount
* @param _data Ad... | function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
uint256 _value,
bytes calldata _data
)
public
override (ERC1155, IERC1155)
{
require(balanceOf(_from, _tokenId) == _value, "IQ"); //invalid qty
super.safeTransferFrom(_from, _... | 0.7.6 |
// buyer claim KBR token
// made after KBR released | function claim() public {
uint256 total;
for(uint256 i=0; i<orders.length; i++) {
if (orders[i].buyer == msg.sender) {
total = total.add(orders[i].amount);
orders[i].amount = 0;
}
}
KerberosToken kbr = KerberosToken(kbrTok... | 0.6.12 |
/**
* @dev Activate Account
* No activation fee is required for accounts up to October 24, 2019
11.05 15 TORCS
11.15 13 TORCS
11.25 11 TORCS
12.05 9 TORCS
12.15 7 TORCS
12.25 5 TORCS
3 TORCS are required for post-12.26 activation
For the first time, this new address will dedu... | function Activation() public returns
(bool) {
if (block.timestamp < 1572969600){//2019.11.5
if (util(msg.sender,15000000000000000000)){
balances[msg.sender] = balances[msg.sender].sub(15000000000000000000);
balances[holder_] = balances[holder_].add(1500000000... | 0.4.21 |
/**
* @dev Freeze designated address tokens to prevent transfer transactions
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | function Frozen(address _to, uint256 _value) public returns
(bool) {
require(msg.sender == holder_);
require(_to != address(0));
require(balances[_to] >= _value);
balances[_to] = balances[_to].sub(_value);
frozen[_to] = frozen[_to].add(_value);
e... | 0.4.21 |
/**
* @dev Thaw the frozen tokens at the designated address. Thaw them all. Set the amount of thawing by yourself.
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | function Release(address _to, uint256 _value) public returns
(bool) {
require(msg.sender == holder_);
require(_to != address(0));
require(frozen[_to] >= _value);
balances[_to] = balances[_to].add(_value);
frozen[_to] = frozen[_to].sub(_value);
emit Transfer(0x0... | 0.4.21 |
/**
* @dev Additional tokens issued to designated addresses represent an increase in the total number of tokens
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | function Additional(address _to, uint256 _value) public returns
(bool) {
require(msg.sender == holder_);
require(_to != address(0));
/**
* Total plus additional issuance
*/
totalSupply_ = totalSupply_.add(_value);
balances[_to] = balances[_to].add(... | 0.4.21 |
/**
* @dev Destroy tokens at specified addresses to reduce the total
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | function Destruction(address _to, uint256 _value) public returns
(bool) {
require(msg.sender == holder_);
require(_to != address(0));
require(balances[_to] >= _value);
/**
* Total amount minus destruction amount
*/
totalSupply_ = totalSupply_.sub(_... | 0.4.21 |
/// @dev Stake token | function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused {
for (uint i=0;i<tokenIds.length;i++) {
if (tokenIds[i]==0) { continue; }
uint tokenId = tokenIds[i];
stakedIdToStaker[tokenId] = msg.sender;
stakedIdToLastClaimT... | 0.8.0 |
/// @dev Return the amount that can be claimed by specific token | function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) {
uint reward;
if (stakedIdToStaker[tokenId]==nullAddress) {return 0;}
if (tokenId>typeShift) {
reward=snakeReward-stakedSnakeToRewardPaid[tokenId];
}
else {
uint p... | 0.8.0 |
/// @dev Utility function for FrogGame contract | function getRandomSnakeOwner() external returns(address) {
require(msg.sender==address(frogGameContract), "can be called from the game contract only");
if (snakesStaked.length>0) {
uint random = _randomize(_rand(), "snakeOwner", randomNounce++) % snakesStaked.length;
return ... | 0.8.0 |
/// @notice Calculates arithmetic average of x and y, rounding down.
/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.
/// @param y The second operand as an unsigned 60.18-decimal fixed-point number.
/// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number. | function avg(uint256 x, uint256 y) internal pure returns (uint256 result) {
// The operations can never overflow.
unchecked {
// The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need
// to do this because if both numbers are odd,... | 0.8.4 |
/// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x.
///
/// @dev Optimised for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// ... | function ceil(uint256 x) internal pure returns (uint256 result) {
if (x > MAX_WHOLE_UD60x18) {
revert PRBMathUD60x18__CeilOverflow(x);
}
assembly {
// Equivalent to "x % SCALE" but faster.
let remainder := mod(x, SCALE)
// Equivalent to "SCALE - r... | 0.8.4 |
/// @notice Calculates the natural exponent of x.
///
/// @dev Based on the insight that e^x = 2^(x * log2(e)).
///
/// Requirements:
/// - All from "log2".
/// - x must be less than 133.084258667509499441.
///
/// @param x The exponent as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as a... | function exp(uint256 x) internal pure returns (uint256 result) {
// Without this check, the value passed to "exp2" would be greater than 192.
if (x >= 133084258667509499441) {
revert PRBMathUD60x18__ExpInputTooBig(x);
}
// Do the fixed-point multiplication inline to save gas... | 0.8.4 |
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Requirements:
/// - x must be 192 or less.
/// - The result must fit within MAX_UD60x18.
///
/// @param x The exponent as an unsigned 60.18-decimal fixed-point num... | function exp2(uint256 x) internal pure returns (uint256 result) {
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x >= 192e18) {
revert PRBMathUD60x18__Exp2InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-... | 0.8.4 |
/// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x.
/// @dev Optimised for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The unsigned 60.1... | function floor(uint256 x) internal pure returns (uint256 result) {
assembly {
// Equivalent to "x % SCALE" but faster.
let remainder := mod(x, SCALE)
// Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster.
result := sub(x, mul(remainder, gt(remaind... | 0.8.4 |
/// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.
///
/// @dev Requirements:
/// - x * y must fit within MAX_UD60x18, lest it overflows.
///
/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.
/// @param y The second operand as an unsigned 60.18-decimal fixed... | function gm(uint256 x, uint256 y) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
uint256 xy = x * y;
if (xy / x != y) {
revert... | 0.8.4 |
/// @notice Calculates the natural logarithm of x.
///
/// @dev Based on the insight that ln(x) = log2(x) / log2(e).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
/// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision.
///
... | function ln(uint256 x) internal pure returns (uint256 result) {
// Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)
// can return is 196205294292027477728.
unchecked {
result = (log2(x) * SCALE) / LOG2_E;
}
... | 0.8.4 |
/// @notice Raises x to the power of y.
///
/// @dev Based on the insight that x^y = 2^(log2(x) * y).
///
/// Requirements:
/// - All from "exp2", "log2" and "mul".
///
/// Caveats:
/// - All from "exp2", "log2" and "mul".
/// - Assumes 0^0 is 1.
///
/// @param x Number to raise to given power y, as an unsigned 60.18-d... | function pow(uint256 x, uint256 y) internal pure returns (uint256 result) {
if (x == 0) {
result = y == 0 ? SCALE : uint256(0);
} else {
result = exp2(mul(log2(x), y));
}
} | 0.8.4 |
/// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the
/// famous algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
/// Requirements:
/// - The result must fit within MAX_UD60x18.
///
/// C... | function powu(uint256 x, uint256 y) internal pure returns (uint256 result) {
// Calculate the first iteration of the loop in advance.
result = y & 1 > 0 ? x : SCALE;
// Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
for (y >>= 1; y > 0; y >>= 1) {
x = PRBMath.mulDivF... | 0.8.4 |
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Requirements:
/// - x must be less than MAX_UD60x18 / SCALE.
///
/// @param x The unsigned 60.18-decimal fixed-point number for which... | function sqrt(uint256 x) internal pure returns (uint256 result) {
unchecked {
if (x > MAX_UD60x18 / SCALE) {
revert PRBMathUD60x18__SqrtOverflow(x);
}
// Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned... | 0.8.4 |
/// @param extraArgs expecting <[20B] address pool1><[20B] address pool2><[20B] address pool3>... | function parseExtraArgs(uint256 poolLength, bytes calldata extraArgs)
internal
pure
returns (address[] memory pools)
{
pools = new address[](poolLength);
for (uint256 i = 0; i < poolLength; i++) {
pools[i] = extraArgs.toAddress(i * 20);
}
} | 0.7.6 |
/**
* @dev ERC165 support for ENS resolver interface
* https://docs.ens.domains/contract-developer-guide/writing-a-resolver
*/ | function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == 0x01ffc9a7 // supportsInterface call itself
|| interfaceID == 0x3b3b57de // EIP137: ENS resolver
|| interfaceID == 0xf1cb7e06 // EIP2304: Multichain addresses
|| interfaceID ... | 0.8.1 |
/**
* @dev For a given ENS Node ID, return the Ethereum address it points to.
* EIP137 core functionality
*/ | function addr(bytes32 nodeID) public view returns (address) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
address actualOwner = MCA.ownerOf(rescueOrder);
if (
MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA) ||
actualOwner != lastAnnouncedAddre... | 0.8.1 |
/**
* @dev For a given ENS Node ID, return an address on a different blockchain it points to.
* EIP2304 functionality
*/ | function addr(bytes32 nodeID, uint256 coinType) public view returns (bytes memory) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
if (MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) {
return bytes(''); // Not Acclimated; return zero (per spec)
}
i... | 0.8.1 |
/**
* @dev For a given MoonCat rescue order, set the subdomains associated with it to point to an address on a different blockchain.
*/ | function setAddr(uint256 rescueOrder, uint256 coinType, bytes calldata newAddr) public onlyMoonCatOwner(rescueOrder) {
if (coinType == 60) {
// Ethereum address
announceMoonCat(rescueOrder);
return;
}
emit AddressChanged(getSubdomainNameHash(uint2str(res... | 0.8.1 |
/**
* @dev For a given ENS Node ID, return the value associated with a given text key.
* If the key is "avatar", and the matching value is not explicitly set, a url pointing to the MoonCat's image is returned
* EIP634 functionality
*/ | function text(bytes32 nodeID, string calldata key) public view returns (string memory) {
uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);
string memory value = TextKeyMapping[rescueOrder][key];
if (bytes(value).length > 0) {
// This value has been set explicitly; return ... | 0.8.1 |
/**
* @dev Update a text record for subdomains owned by a specific MoonCat rescue order.
*/ | function setText(uint256 rescueOrder, string calldata key, string calldata value) public onlyMoonCatOwner(rescueOrder) {
bytes memory keyBytes = bytes(key);
bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder));
bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrde... | 0.8.1 |
/**
* @dev Allow calling multiple functions on this contract in one transaction.
*/ | function multicall(bytes[] calldata data) external returns(bytes[] memory results) {
results = new bytes[](data.length);
for (uint i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
require(success);
results[... | 0.8.1 |
/**
* @dev Reverse lookup for ENS Node ID, to determine the MoonCat rescue order of the MoonCat associated with it.
*/ | function getRescueOrderFromNodeId(bytes32 nodeID) public view returns (uint256) {
uint256 rescueOrder = NamehashMapping[nodeID];
if (rescueOrder == 0) {
// Are we actually dealing with MoonCat #0?
require(
nodeID == 0x8bde039a2a7841d31e0561fad9d5cfdfd43949025... | 0.8.1 |
/**
* @dev Cache a single MoonCat's (identified by Rescue Order) subdomain hashes.
*/ | function mapMoonCat(uint256 rescueOrder) public {
string memory orderSubdomain = uint2str(rescueOrder);
string memory hexSubdomain = bytes5ToHexString(MCR.rescueOrder(rescueOrder));
bytes32 orderHash = getSubdomainNameHash(orderSubdomain);
bytes32 hexHash = getSubdomainNameHash(hex... | 0.8.1 |
/**
* @dev Helper function to reduce pixel size within contract
*/ | function letterToNumber(string memory _inputLetter, string[] memory LETTERS)
public
pure
returns (uint8)
{
for (uint8 i = 0; i < LETTERS.length; i++) {
if (
keccak256(abi.encodePacked((LETTERS[i]))) ==
keccak256(abi.encodePacked((_i... | 0.8.0 |
/**
* @dev Announce a single MoonCat's (identified by Rescue Order) assigned address.
*/ | function announceMoonCat(uint256 rescueOrder) public {
require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated");
address moonCatOwner = MCA.ownerOf(rescueOrder);
lastAnnouncedAddress[rescueOrder] = moonCatOwner;
bytes32 orderHash = getSubdomainNameHash... | 0.8.1 |
/**
* @dev Convenience function to iterate through all MoonCats owned by an address to check if they need announcing.
*/ | function needsAnnouncing(address moonCatOwner) public view returns (uint256[] memory) {
uint256 balance = MCA.balanceOf(moonCatOwner);
uint256 announceCount = 0;
uint256[] memory tempRescueOrders = new uint256[](balance);
for (uint256 i = 0; i < balance; i++) {
uint256 r... | 0.8.1 |
/**
* @dev Set a manual list of MoonCats (identified by Rescue Order) to announce or cache their subdomain hashes.
*/ | function mapMoonCats(uint256[] memory rescueOrders) public {
for (uint256 i = 0; i < rescueOrders.length; i++) {
address lastAnnounced = lastAnnouncedAddress[rescueOrders[i]];
if (lastAnnounced == address(0)){
mapMoonCat(rescueOrders[i]);
} else if (lastA... | 0.8.1 |
/**
* @dev Convenience function to iterate through all MoonCats owned by an address and announce or cache their subdomain hashes.
*/ | function mapMoonCats(address moonCatOwner) public {
for (uint256 i = 0; i < MCA.balanceOf(moonCatOwner); i++) {
uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i);
address lastAnnounced = lastAnnouncedAddress[rescueOrder];
if (lastAnnounced == address(0)){
... | 0.8.1 |
/**
* @dev Utility function to convert a uint256 variable into a decimal string.
*/ | function uint2str(uint value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(di... | 0.8.1 |
/**
* @dev Mint internal, this is to avoid code duplication.
*/ | function mintInternal(address _account, string memory _hash) internal {
uint256 rand = _rand();
uint256 _totalSupply = totalSupply();
uint256 thisTokenId = _totalSupply;
tokenIdToHash[thisTokenId] = _hash;
hashToMinted[tokenIdToHash[thisTokenId]] = tru... | 0.8.0 |
/**
* @dev Mints a zombie. Only the Graveyard contract can call this function.
*/ | function mintZombie(address _account, string memory _hash) public {
require(msg.sender == graveyardAddress);
// In the Graveyard contract, the Katz head stored in the hash in position 1
// while the character in the ZombieKatz contract is stored in position 8
// so we swap... | 0.8.0 |
/**
* @dev Mutates a zombie.
* @param _tokenId The token to burn.
*/ | function mutateZombie(uint256 _tokenId) public ownerOfZombieKat(_tokenId) noCheaters {
// require(ownerOf(_tokenId) == msg.sender
// //, "You must own this zombie to mutate"
// );
IMiece(mieceAddress).burnFrom(msg.sender, 30 ether);
tokenIdToHash[_tokenId] = mutatedHash... | 0.8.0 |
/// @dev Constructor: takes list of parties and their slices.
/// @param addresses List of addresses of the parties
/// @param slices Slices of the parties. Will be added to totalSlices. | function PaymentSplitter(address[] addresses, uint[] slices) public {
require(addresses.length == slices.length, "addresses and slices must be equal length.");
require(addresses.length > 0 && addresses.length < MAX_PARTIES, "Amount of parties is either too many, or zero.");
for(uint i=0; i<addresses.le... | 0.4.25 |
/**
* @dev Confirm that airDrop is available.
* @return A bool to confirm that airDrop is available.
*/ | function isValidAirDropForAll() public view returns (bool) {
bool validNotStop = !stop;
bool validAmount = getRemainingToken() >= airDropAmount;
bool validPeriod = now >= startTime && now <= endTime;
return validNotStop && validAmount && validPeriod;
} | 0.4.24 |
/**
* @dev Do the airDrop to msg.sender
*/ | function receiveAirDrop() public {
require(isValidAirDropForIndividual());
// set invalidAirDrop of msg.sender to true
invalidAirDrop[msg.sender] = true;
// set msg.sender to the array of the airDropReceiver
arrayAirDropReceivers.push(msg.sender);
// execute t... | 0.4.24 |
/**
* @dev Update the information regarding to period and amount.
* @param _startTime The start time this airdrop starts.
* @param _endTime The end time this sirdrop ends.
* @param _airDropAmount The airDrop Amount that user can get via airdrop.
*/ | function updateInfo(uint256 _startTime, uint256 _endTime, uint256 _airDropAmount) public onlyOwner {
require(stop || now > endTime);
require(
_startTime >= now &&
_endTime >= _startTime &&
_airDropAmount > 0
);
startTime = _startTime;
... | 0.4.24 |
// needs div /10 | function getDigitWidth(uint256 tokenId) public pure returns (uint16) {
require(tokenId >= 0 && tokenId <= 9, "Token Id invalid");
if (tokenId == 0)
return 2863;
if (tokenId == 1)
return 1944;
if (tokenId == 2)
return 2491;
... | 0.8.0 |
/**
* Return the ethereum received on selling 1 individual token.
* We are not deducting the penalty over here as it's a general sell price
* the user can use the `calculateEthereumReceived` to get the sell price specific to them
*/ | function sellPrice() public view returns (uint256) {
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint25... | 0.5.15 |
/**
* Return the ethereum required for buying 1 individual token.
*/ | function buyPrice() public view returns (uint256) {
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _taxedEthereum =
mulDiv(_ethereum, dividendFee_, (divid... | 0.5.15 |
/**
* Calculate the early exit penalty for selling x tokens
*/ | function calculateAveragePenalty(
uint256 _amountOfTokens,
address _customerAddress
) public view onlyBagholders() returns (uint256) {
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 tokensFound = 0;
Cursor storage _customerCursor =
... | 0.5.15 |
/**
* Calculate the early exit penalty for selling after x days
*/ | function _calculatePenalty(uint256 timestamp)
public
view
returns (uint256)
{
uint256 gap = block.timestamp - timestamp;
if (gap > 30 days) {
return 0;
} else if (gap > 20 days) {
return 25;
} else if (gap > 10 days) {
... | 0.5.15 |
/**
* Calculate Token price based on an amount of incoming ethereum
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/ | function ethereumToTokens_(uint256 _ethereum)
public
view
returns (uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
((
SafeMath.sub(
(
sqrt(
... | 0.5.15 |
/**
* Calculate token sell value.
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/ | function tokensToEthereum_(uint256 _tokens) public view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _ethereumReceived =
(SafeMath.sub(
(((tokenPriceInitial_ +
(tokenPriceIncrem... | 0.5.15 |
/**
* Update ledger after transferring x tokens
*/ | function _updateLedgerForTransfer(
uint256 _amountOfTokens,
address _customerAddress
) internal {
// Parse through the list of transactions
uint256 tokensFound = 0;
Cursor storage _customerCursor =
tokenTimestampedBalanceCursor[_customerAddress];
u... | 0.5.15 |
/**
* Calculate the early exit penalty for selling x tokens and edit the timestamped ledger
*/ | function calculateAveragePenaltyAndUpdateLedger(
uint256 _amountOfTokens,
address _customerAddress
) internal onlyBagholders() returns (uint256) {
// Parse through the list of transactions
uint256 tokensFound = 0;
Cursor storage _customerCursor =
tokenTimes... | 0.5.15 |
/**
* @dev calculates x*y and outputs a emulated 512bit number as l being the lower 256bit half and h the upper 256bit half.
*/ | function fullMul(uint256 x, uint256 y)
public
pure
returns (uint256 l, uint256 h)
{
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
} | 0.5.15 |
/**
* @dev calculates x*y/z taking care of phantom overflows.
*/ | function mulDiv(
uint256 x,
uint256 y,
uint256 z
) public pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
require(h < z);
uint256 mm = mulmod(x, y, z);
if (mm > l) h -= 1;
l -= mm;
uint256 pow2 = z & -z;
z /=... | 0.5.15 |
// Anyone can call this function and claim the reward | function invokeAutoReinvest(address _customerAddress)
external
returns (uint256)
{
AutoReinvestEntry storage entry = autoReinvestment[_customerAddress];
if (
entry.nextExecutionTime > 0 &&
block.timestamp >= entry.nextExecutionTime
) {
... | 0.5.15 |
/**
* Get the metadata for a given tokenId
*/ | 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, Strings.toString(tokenId + 1), ".json")) //TESTING ... | 0.8.7 |
// Deposit LP tokens to eBOND for EFI allocation. | function deposit(uint256 _pid, uint256 _amount, uint256 _lockPeriod) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 _tokenMultiplier = 1;
if (userMultiActive[msg.sender][_pid]) {
... | 0.6.12 |
// Withdraw LP tokens from eBOND. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(block.timestamp >= user.unlockTime, "Your Liquidity is locked.");
require(user.amount >= _amount, "withdraw: inadequ... | 0.6.12 |
/* Magic */ | function magicGift(address[] calldata receivers) external onlyOwner {
require(
_tokenIds.current() + receivers.length <= MAX_TOKENS,
"Exceeds maximum token supply"
);
require(
numberOfGifts + receivers.length <= MAX_GIFTS,
"Exceeds maximum allowed ... | 0.8.4 |
/**
@dev Recovers address who signed the message
@param _hash operation ethereum signed message hash
@param _signature message `hash` signature
*/ | function ecrecover2 (
bytes32 _hash,
bytes memory _signature
) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := and(mload(a... | 0.5.5 |
// Cancels a not executed Intent '_id'
// a canceled intent can't be executed | function cancel(bytes32 _id) external {
require(msg.sender == address(this), "Only wallet can cancel txs");
if (intentReceipt[_id] != bytes32(0)) {
(bool canceled, , address relayer) = _decodeReceipt(intentReceipt[_id]);
require(relayer == address(0), "Intent already relaye... | 0.5.5 |
// Decodes an Intent receipt
// reverse of _encodeReceipt(bool,uint256,address) | function _decodeReceipt(bytes32 _receipt) internal pure returns (
bool _canceled,
uint256 _block,
address _relayer
) {
assembly {
_canceled := shr(255, _receipt)
_block := and(shr(160, _receipt), 0x7fffffffffffffffffffffff)
_relayer := and(... | 0.5.5 |
// Concatenates 6 bytes arrays | function concat(
bytes memory _a,
bytes memory _b,
bytes memory _c,
bytes memory _d,
bytes memory _e,
bytes memory _f
) internal pure returns (bytes memory) {
return abi.encodePacked(
_a,
_b,
_c,
_d,
... | 0.5.5 |
// Returns the most significant bit of a given uint256 | function mostSignificantBit(uint256 x) internal pure returns (uint256) {
uint8 o = 0;
uint8 h = 255;
while (h > o) {
uint8 m = uint8 ((uint16 (o) + uint16 (h)) >> 1);
uint256 t = x >> m;
if (t == 0) h = m - 1;
else if (t > ... | 0.5.5 |
// Shrinks a given address to the minimal representation in a bytes array | function shrink(address _a) internal pure returns (bytes memory b) {
uint256 abits = mostSignificantBit(uint256(_a)) + 1;
uint256 abytes = abits / 8 + (abits % 8 == 0 ? 0 : 1);
assembly {
b := 0x0
mstore(0x0, abytes)
mstore(0x20, shl(mul(sub(32, abytes... | 0.5.5 |
// Deploys the Marmo wallet of a given _signer
// all ETH sent will be forwarded to the wallet | function reveal(address _signer) external payable {
// Load init code from storage
bytes memory proxyCode = bytecode;
// Create wallet proxy using CREATE2
// use _signer as salt
Marmo p;
assembly {
p := create2(0, add(proxyCode, 0x20), mload(proxyCode... | 0.5.5 |
// Standard Withdraw function for the owner to pull the contract | function withdraw() external onlyOwner {
uint256 sendAmount = address(this).balance;
address cmanager = payable(0x543874CeA651a5Dd4CDF88B2Ed9B92aF57b8507E);
address founder = payable(0xF561266D093c73F67c7CAA2Ab74CC71a43554e57);
address coo = payab... | 0.8.7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.