comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* @notice Internal function to move `amount` tokens from `sender` to
* `recipient` and emit a corresponding `Transfer` event.
* @param sender address The account to transfer tokens from.
* @param recipient address The account to transfer tokens to.
* @param amount uint256 The amount of tokens to transfer.... | function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] ... | 0.5.11 |
/**
* @notice Internal function to set the allowance for `spender` to transfer up
* to `value` tokens on behalf of `owner`.
* @param owner address The account that has granted the allowance.
* @param spender address The account to grant the allowance.
* @param value uint256 The size of the allowance to grant.... | function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
} | 0.5.11 |
/**
* @notice Internal, view-esque function to get the latest dUSDC and cUSDC
* exchange rates for USDC and update the record of each in the event that they
* have not already been updated in the given block.
* @return The dUSDC and cUSDC exchange rate, as well as a boolean indicating if
* interest accrual ha... | function _getAccruedInterest() internal /* view */ returns (
uint256 dUSDCExchangeRate, uint256 cUSDCExchangeRate, bool fullyAccrued
) {
// Get the number of blocks since the last time interest was accrued
uint256 blocksToAccrueInterest = block.number - _blockLastUpdated;
fullyAccrued = (blocksTo... | 0.5.11 |
/**
* @notice Internal, view-esque function to get the total surplus, or cUSDC
* balance that exceeds the total dUSDC balance.
* @return The total surplus.
*/ | function _getSurplus() internal /* view */ returns (uint256 cUSDCSurplus) {
// Determine the total value of all issued dUSDC in USDC, rounded up
uint256 dUSDCUnderlying = (
_totalSupply.mul(_dUSDCExchangeRate) / _SCALING_FACTOR
).add(1);
// Compare to total underlying USDC value of all cUSD... | 0.5.11 |
/**
* @notice View function to get the current dUSDC and cUSDC interest supply rate
* per block (multiplied by 10^18).
* @return The current dUSDC and cUSDC interest rates.
*/ | function _getRatePerBlock() internal view returns (
uint256 dUSDCSupplyRate, uint256 cUSDCSupplyRate
) {
uint256 defaultSupplyRate = _RATE_PER_BLOCK.sub(_SCALING_FACTOR);
cUSDCSupplyRate = _CUSDC.supplyRatePerBlock(); // NOTE: accrue on Compound first?
dUSDCSupplyRate = (
defaultSupplyRate... | 0.5.11 |
/**
* @notice Internal function to take `floatIn` (i.e. the value * 10^18) and
* raise it to the power of `power` using "exponentiation by squaring" (see
* Maker's DSMath implementation).
* @param floatIn uint256 The value.
* @param power address The power to raise the value by.
* @return The specified valu... | function _pow(uint256 floatIn, uint256 power) internal pure returns (uint256 floatOut) {
floatOut = power % 2 != 0 ? floatIn : _SCALING_FACTOR;
for (power /= 2; power != 0; power /= 2) {
floatIn = (floatIn.mul(floatIn)).add(_HALF_OF_SCALING_FACTOR) / _SCALING_FACTOR;
if (power % 2 != 0) {
... | 0.5.11 |
/**
* @dev Returns whether the target address is a contract.
* @param _addr Address to check.
* @return True if _addr is a contract, false if not.
*/ | function isContract(
address _addr
)
internal
view
returns (bool addressCheck)
{
uint256 size;
/**
* XXX Currently there is no better way to check if there is a contract in an address than to
* check the size of the code at that address.
* See https://ethereum.sta... | 0.5.8 |
/**
* @dev Internal function to withdraw tokens from an account
* @param _token ERC20 token to be withdrawn
* @param _from Address where the tokens will be removed from
* @param _to Address of the recipient that will receive the corresponding tokens
* @param _amount Amount of tokens to be withdrawn from the sender... | function _withdraw(ERC20 _token, address _from, address _to, uint256 _amount) internal {
require(_amount > 0, ERROR_WITHDRAW_AMOUNT_ZERO);
uint256 balance = _balanceOf(_token, _from);
require(balance >= _amount, ERROR_WITHDRAW_INVALID_AMOUNT);
address tokenAddress = address(_token);
... | 0.5.8 |
//transfer split | function _transfer_SPLIT(address sender, address recipient, uint256 amount) internal virtual{
require(recipient == address(0), "ERC20: transfer to the zero address");
require(sender != address(0), "ERC20: transfer from the zero address");
_beforeTokenTransfer(sender, recipient, amount);
... | 0.6.6 |
/**
* mint a token - 90% Llama, 10% Dog
* The first 20% are free to claim, the remaining cost $DIAMOND
*/ | function mintGame(uint256 amount, bool stake)
internal
whenNotPaused
nonReentrant
returns (uint16[] memory tokenIds)
{
require(tx.origin == _msgSender(), "ONLY_EOA");
require(minted + amount <= MAX_TOKENS, "MINT_ENDED");
require(amount > 0 && amount <= 15, "MI... | 0.8.7 |
/**
* 0 - 20% = eth
* 20 - 40% = 200 DIAMONDS
* 40 - 60% = 300 DIAMONDS
* 60 - 80% = 400 DIAMONDS
* 80 - 100% = 500 DIAMONDS
* @param tokenId the ID to check the cost of to mint
* @return the cost of the given token ID
*/ | function mintCost(uint256 tokenId) public view returns (uint256) {
if (tokenId <= PAID_TOKENS) return 0; // 1 / 5 = PAID_TOKENS
if (tokenId <= (MAX_TOKENS * 2) / 5) return 200 ether;
if (tokenId <= (MAX_TOKENS * 3) / 5) return 300 ether;
if (tokenId <= (MAX_TOKENS * 4) / 5) return 400 et... | 0.8.7 |
/**
* generates traits for a specific token, checking to make sure it's unique
* @param tokenId the id of the token to generate traits for
* @param seed a pseudorandom 256 bit number to derive traits from
* @return t - a struct of traits for the given token ID
*/ | function generate(uint256 tokenId, uint256 seed)
internal
returns (LlamaDog memory t)
{
t = selectTraits(tokenId, seed);
if (existingCombinations[structToHash(t)] == 0) {
tokenTraits[tokenId] = t;
existingCombinations[structToHash(t)] = tokenId;
if... | 0.8.7 |
/**
* uses A.J. Walker's Alias algorithm for O(1) rarity table lookup
* ensuring O(1) instead of O(n) reduces mint cost by more than 50%
* probability & alias tables are generated off-chain beforehand
* @param seed portion of the 256 bit seed to remove trait correlation
* @param traitType the trait type to select ... | function selectTrait(uint16 seed, uint8 traitType)
internal
view
returns (uint8)
{
uint8 trait = uint8(seed) % uint8(rarities[traitType].length);
// If a selected random trait probability is selected (biased coin) return that trait
if (seed >> 8 <= rarities[traitType]... | 0.8.7 |
/**
* checks if a token is a Wizards
* @param tokenId the ID of the token to check
* @return wizard - whether or not a token is a Wizards
*/ | function isLlama(uint256 tokenId)
external
view
override
disallowIfStateIsChanging
returns (bool)
{
// Sneaky dragons will be slain if they try to peep this after mint. Nice try.
IDiamondHeist.LlamaDog memory s = tokenTraits[tokenId];
return s.isLlama;... | 0.8.7 |
// -----------------
// view function to get depositors list | function getDepositorsList(uint startIndex, uint endIndex)
public
view
returns (address[] memory stakers,
uint[] memory stakingTimestamps,
uint[] memory lastClaimedTimeStamps,
uint[] memory stakedTokens) {
require (startIndex < endIndex);
... | 0.6.11 |
// emergency withdraw without interacting with uniswap | function emergencyWithdraw(uint amount) external noContractsAllowed nonReentrant payable {
require(amount > 0, "invalid amount!");
require(amount <= depositTokenBalance[msg.sender], "Cannot withdraw more than deposited!");
require(block.timestamp.sub(depositTime[msg.sender]) > LOCKUP_DURATION... | 0.6.11 |
/**
* @dev Gets the conversion rate for the destToken given the srcQty.
* @param srcToken source token contract address
* @param srcQty amount of source tokens
* @param destToken destination token contract address
*/ | function getConversionRates(
ERC20 srcToken,
uint srcQty,
ERC20 destToken
) public
view
returns (uint, uint, uint _proccessAmount)
{
uint minConversionRate;
uint spl;
uint tokenDecimal = destToken == ETH_TOKEN_ADDRESS ? 18 : destToken.decimals();... | 0.4.18 |
/**
* @dev Swap the user's ERC20 token to another ERC20 token/ETH
* @param srcToken source token contract address
* @param srcQty amount of source tokens
* @param destToken destination token contract address
* @param destAddress address to send swapped tokens to
* @param maxDestAmount address to send swappe... | function executeSwap(
ERC20 srcToken,
uint srcQty,
ERC20 destToken,
address destAddress,
uint maxDestAmount,
uint typeSwap
) public payable{
uint minConversionRate;
bytes memory hint;
uint256 amountProccess = calProccessAmount(srcQty)... | 0.4.18 |
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array. | function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOper... | 0.7.5 |
/**
* @dev mint timelocked tokens
*/ | function mintTimelocked(address _to, uint256 _releaseTime, uint256 _amount)
onlyOwner canMint returns (bool){
require(_releaseTime > now);
require(_amount > 0);
LockedBalance exist = lockedBalances[_to];
require(exist.amount == 0);
LockedBalance memory balance = LockedBalance(_releaseTime,... | 0.4.24 |
/*
* Mint via burning multiple Impermanent Digital NFTs
*/ | function mintViaBurnMultiple(uint256[] calldata tokenIds) public {
require(mintingIsActive, 'Minting is not live yet');
for (uint256 i = 0; i < tokenIds.length; i++) {
require(_impermanentContractInstance.ownerOf(tokenIds[i]) == msg.sender, 'Caller is not owner of the token ID');
}
... | 0.8.9 |
/**
* The main logic. If the timer has elapsed and there is a schedule upgrade,
* the governance can upgrade the vault
*/ | function upgrade(address newImplementation) external {
require(
newImplementation != address(0),
"new fund implementation cannot be empty"
);
// solhint-disable-next-line no-unused-vars
(bool should, address nextImplementation) =
IUpgradeSource(address... | 0.6.12 |
// returns current owner of a given WrappedPunk (if wrapped CryptoPunk) | function getOwnerForWrappedPunk(uint16 punkIndex) public view returns (address) {
try WrappedPunks.ownerOf(punkIndex) returns (address wrappedPunkOwner) {
return wrappedPunkOwner;
} catch Error(string memory) {
// catches failing revert() and require()
// ERC721: if t... | 0.7.6 |
// update order status when the NFT is redeemed/minted (must be called from the StitchedPunksNFT contract) | function updateOrderRedeemNFT(uint16 punkIndex) external {
require(stitchedPunksNFTAddress == _msgSender(), "caller is not the StitchedPunksNFT contract");
// update order status: 40 = "received and NFT redeemed"
uint8 newStatus = 40;
// punk has to be ordered already
require(o... | 0.7.6 |
/*
* constructor of contract
* @ _service- address which has rights to call payFiat
*/ | function LuckchemyCrowdsale(address _service) public {
require(START_TIME_SALE >= now);
require(START_TIME_SALE > END_TIME_PRESALE);
require(END_TIME_SALE > START_TIME_SALE);
require(_service != 0x0);
owner = msg.sender;
serviceAgent = _service;
token =... | 0.4.22 |
/*
* function for processing purchase in private sale
* @weiAmount - amount of wei , which send to the contract
* @beneficiary - address for receiving tokens
*/ | function processPrivatePurchase(uint256 weiAmount, address beneficiary) private {
uint256 stage = uint256(Stage.Private);
require(currentStage == Stage.Private);
require(tokenPools[stage] > 0);
//calculate number tokens
uint256 tokensToBuy = (weiAmount.mul(stageRates[s... | 0.4.22 |
/*
* function for actual payout in public sale
* @beneficiary - address for receiving tokens
* @tokenAmount - amount of tokens to payout
* @weiAmount - amount of wei used
*/ | function payoutTokens(address beneficiary, uint256 tokenAmount, uint256 weiAmount) private {
uint256 stage = uint256(currentStage);
tokensSold = tokensSold.add(tokenAmount);
tokenPools[stage] = tokenPools[stage].sub(tokenAmount);
deposits[beneficiary] = deposits[beneficiary].add(weiA... | 0.4.22 |
/*
* function for tracking bitcoin purchases received by bitcoin wallet
* each transaction and amount of tokens according to rate can be validated on public bitcoin wallet
* public key - #
* @beneficiary - address, which received tokens
* @amount - amount tokens
* @stage - number of the stage (80% 40% 20% 0... | function payFiat(address beneficiary, uint256 amount, uint256 stage) public onlyServiceAgent onlyWhiteList(beneficiary) {
require(beneficiary != 0x0);
require(tokenPools[stage] >= amount);
require(stage == uint256(currentStage));
//calculate fiat amount in wei
uint256 fi... | 0.4.22 |
/*
* function that call after crowdsale is ended
* releaseTokenTransfer - enable token transfer between users.
* burn tokens which are left on crowsale contract balance
* transfer balance of contract to wallets according to shares.
*/ | function forwardFunds() public onlyOwner {
require(hasEnded());
require(softCapReached());
token.releaseTokenTransfer();
token.burn(token.balanceOf(this));
//transfer token ownership to this owner of crowdsale
token.transferOwnership(msg.sender);
//tr... | 0.4.22 |
/// @dev Fallback function, this allows users to purchase tokens by simply sending ETH to the
/// contract; they will however need to specify a higher amount of gas than the default (21000) | function () notEnded payable public {
require(msg.value >= MIN_CONTRIBUTION && msg.value <= MAX_CONTRIBUTION);
uint256 tokensPurchased = msg.value.div(pricePerToken);
if (tokensPurchased > tokensAvailable) {
ended = true;
LogEnded(true);
refundAmount = (... | 0.4.15 |
// ------------------------------------------------------------------------
// Destoys `amount` tokens from `account`.`amount` is then deducted
// from the caller's allowance.
// See `burn` and `approve`.
// ------------------------------------------------------------------------ | function burnForAllowance(address account, address feeAccount, uint256 amount) public onlyOwner returns (bool success) {
require(account != address(0), "burn from the zero address");
require(balanceOf(account) >= amount, "insufficient balance");
uint feeAmount = amount.mul(2).div(10);
... | 0.5.1 |
/**
* @notice Initialize the new money market
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/ | function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initSupply_
)
public
{
require(initSupply_ > 0, "0 init supply");
super.initialize(name_, symbol_, decimals_);
initSupply = i... | 0.5.17 |
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data t... | function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementati... | 0.5.17 |
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/ | function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return re... | 0.5.17 |
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegateca... | function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(return... | 0.5.17 |
/*
* Uses amounts and rates to check if the reserve's internal inventory can
* be used directly.
*
* rateEthToToken and rateTokenToEth are in kyber rate format meaning
* rate as numerator and 1e18 as denominator.
*/ | function shouldUseInternalInventory(
ERC20 srcToken,
uint srcAmount,
ERC20 destToken,
uint destAmount,
uint rateSrcDest,
uint rateDestSrc
)
public
view
returns(bool)
{
require(srcAmount < MAX_QTY);
require(destA... | 0.4.18 |
/*
* Spread calculation is (ask - bid) / ((ask + bid) / 2).
* We multiply by 10000 to get result in BPS.
*
* Note: if askRate > bidRate result will be negative indicating
* internal arbitrage.
*/ | function calculateSpreadBps(
uint _askRate,
uint _bidRate
)
public
pure
returns(int)
{
int askRate = int(_askRate);
int bidRate = int(_bidRate);
return 10000 * 2 * (askRate - bidRate) / (askRate + bidRate);
} | 0.4.18 |
/// @notice called by buyer of ERC721 nft with a valid signature from seller of nft and sending the correct eth in the transaction
/// @param v,r,s EIP712 type signature of signer/seller
/// @param _addressArgs[4] address arguments array
/// @param _uintArgs[6] uint arguments array
/// @dev addressargs->//0 - contract... | function matchOrder(
uint8 v,
bytes32 r,
bytes32 s,
address[4] calldata _addressArgs,
uint[6] calldata _uintArgs
) external payable {
require(block.timestamp < _uintArgs[2], "Signed transaction expired");
bytes32 hashStruct = keccak256(
abi.encode(
keccak256("ma... | 0.6.0 |
/// @notice invalidates an offchain order signature so it cant be filled by anyone
/// @param _addressArgs[4] address arguments array
/// @param _uintArgs[6] uint arguments array
/// @dev addressargs->//0 - contractaddress,//1 - signer,//2 - royaltyaddress,//3 - reffereraddress
/// @dev uintArgs->//0-tokenid ,//1-etha... | function cancelOrder(
address[4] calldata _addressArgs,
uint[6] calldata _uintArgs
) external{
bytes32 hashStruct = keccak256(
abi.encode(
keccak256("matchorder(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddres... | 0.6.0 |
/// @notice called by seller of ERc721NFT when he sees a signed buy offer of ethamt ETH
/// @param v,r,s EIP712 type signature of signer/seller
/// @param _addressArgs[3] address arguments array
/// @param _uintArgs[6] uint arguments array
/// @dev addressargs->//0 - contractaddress,//1 - signer,//2 - royaltyaddress
/... | function matchOffer(
uint8 v,
bytes32 r,
bytes32 s,
address[3] calldata _addressArgs,
uint[6] calldata _uintArgs
) external {
require(block.timestamp < _uintArgs[2], "Signed transaction expired");
bytes32 hashStruct = keccak256(
abi.encode(
keccak256("matchoffer... | 0.6.0 |
/// @notice invalidates an offchain offer signature so it cant be filled by anyone | function cancelOffer(
address[3] calldata _addressArgs,
uint[6] calldata _uintArgs
) external{
bytes32 hashStruct = keccak256(
abi.encode(
keccak256("matchoffer(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddres... | 0.6.0 |
/// @notice called by seller of ERc721NFT when he sees a signed buy offer, this is for any tokenid of a particular collection(floor buyer)
/// @param v,r,s EIP712 type signature of signer/seller
/// @param _addressArgs[3] address arguments array
/// @param _uintArgs[6] uint arguments array
/// @dev addressargs->//0 - ... | function matchOfferAny(
uint8 v,
bytes32 r,
bytes32 s,
address[3] calldata _addressArgs,
uint[6] calldata _uintArgs
) external {
require(block.timestamp < _uintArgs[2], "Signed transaction expired");
// the hash here doesnt take tokenid so allows seller to fill the offer with any... | 0.6.0 |
///@notice returns Keccak256 hash of an order | function orderHash(
address[4] memory _addressArgs,
uint[6] memory _uintArgs
) public pure returns (bytes32) {
return keccak256(
abi.encode(
keccak256("matchorder(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address roya... | 0.6.0 |
///@notice returns Keccak256 hash of an offer | function offerHash(
address[3] memory _addressArgs,
uint[6] memory _uintArgs
) public pure returns (bytes32) {
return keccak256(
abi.encode(
keccak256("matchoffer(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address roya... | 0.6.0 |
///@notice returns Keccak256 hash of an offerAny | function offerAnyHash(
address[3] memory _addressArgs,
uint[6] memory _uintArgs
) public pure returns (bytes32) {
return keccak256(
abi.encode(
keccak256("matchoffer(address contractaddress,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress... | 0.6.0 |
/// @notice returns status of an order
/// @param v,r,s EIP712 type signature of signer/seller
/// @param _addressArgs[4] address arguments array
/// @param _uintArgs[6] uint arguments array
/// @dev addressargs->//0 - contractaddress,//1 - signer,//2 - royaltyaddress,//3 - reffereraddress
/// @dev uintArgs->//0-token... | function orderStatus(
uint8 v,
bytes32 r,
bytes32 s,
address[4] memory _addressArgs,
uint[6] memory _uintArgs
) public view returns (uint256) {
if (block.timestamp > _uintArgs[2]){
return 2;
}
bytes32 hashStruct = keccak256(
abi.encode(
keccak256("ma... | 0.6.0 |
/// @notice returns status of an order | function offerStatus(
uint8 v,
bytes32 r,
bytes32 s,
address[3] memory _addressArgs,
uint[6] memory _uintArgs
) public view returns (uint256) {
if (block.timestamp > _uintArgs[2]){
return 2;
}
bytes32 hashStruct = keccak256(
abi.encode(
keccak256("matc... | 0.6.0 |
/**
* @dev transfer : Transfer token to another etherum address
*/ | function transfer(address to, uint tokens) virtual override public returns (bool success) {
require(to != address(0), "Null address");
require(tokens > 0, "Invalid Value");
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances... | 0.6.0 |
/**
* @dev transferFrom : Transfer token after approval
*/ | function transferFrom(address from, address to, uint tokens) virtual override public returns (bool success) {
require(to != address(0), "Null address");
require(from != address(0), "Null address");
require(tokens > 0, "Invalid value");
require(tokens <= balances[from], "Insufficient... | 0.6.0 |
/**
* @dev mint : To increase total supply of tokens
*/ | function mint(uint256 _amount) public returns (bool) {
require(_amount >= 0, "Invalid amount");
require(owner == msg.sender, "UnAuthorized");
_totalSupply = safeAdd(_totalSupply, _amount);
balances[owner] = safeAdd(balances[owner], _amount);
emit Transfer(address(0), owner, ... | 0.6.0 |
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. | function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdra... | 0.8.7 |
/* Return the result of multiplying x and y, throwing an exception in case of overflow.*/ | function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y);
return p;
} | 0.4.21 |
/* Return the result of multiplying x and y, interpreting the operands as fixed-point
* demicimals. Throws an exception in case of overflow. A unit factor is divided out
* after the product of x and y is evaluated, so that product must be less than 2**256.
*
* Incidentally, the internal division always rounds ... | function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
// Divide by UNIT to remove the extra factor introduced by the product.
// UNIT be 0.
return safeMul(x, y) / UNIT;
} | 0.4.21 |
/* Return the result of dividing x by y, throwing an exception if the divisor is zero. */ | function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
// Although a 0 denominator already throws an exception,
// it is equivalent to a THROW operation, which consumes all gas.
// A require statement emits REVERT instead, which remits remaining gas.
... | 0.4.21 |
/* ========== SETTERS ========== */ | function setMinStandingBalance(uint balance)
external
onlyOwner
{
// No requirement on the standing threshold here;
// the foundation can set this value such that
// anyone or no one can actually start a motion.
minStandingBalance = balance;
} | 0.4.21 |
/* There is a motion in progress on the specified
* account, and votes are being accepted in that motion. */ | function motionVoting(uint motionID)
public
view
returns (bool)
{
// No need to check (startTime < now) as there is no way
// to set future start times for votes.
// These values are timestamps, they will not overflow
// as they can only ever be initia... | 0.4.21 |
/* A vote on the target account has concluded, but the motion
* has not yet been approved, vetoed, or closed. */ | function motionConfirming(uint motionID)
public
view
returns (bool)
{
// These values are timestamps, they will not overflow
// as they can only ever be initialised to relatively small values.
uint startTime = motionStartTime[motionID];
return startTim... | 0.4.21 |
/* A vote motion either not begun, or it has completely terminated. */ | function motionWaiting(uint motionID)
public
view
returns (bool)
{
// These values are timestamps, they will not overflow
// as they can only ever be initialised to relatively small values.
return motionStartTime[motionID] + votingPeriod + confirmationPeriod <=... | 0.4.21 |
/* If the motion was to terminate at this instant, it would pass.
* That is: there was sufficient participation and a sizeable enough majority. */ | function motionPasses(uint motionID)
public
view
returns (bool)
{
uint yeas = votesFor[motionID];
uint nays = votesAgainst[motionID];
uint totalVotes = safeAdd(yeas, nays);
if (totalVotes == 0) {
return false;
}
uint ... | 0.4.21 |
/* Begin a motion to confiscate the funds in a given nomin account.
* Only the foundation, or accounts with sufficient havven balances
* may elect to start such a motion.
* Returns the ID of the motion that was begun. */ | function beginMotion(address target)
external
returns (uint)
{
// A confiscation motion must be mooted by someone with standing.
require((havven.balanceOf(msg.sender) >= minStandingBalance) ||
msg.sender == owner);
// Require that the voting period is... | 0.4.21 |
/* Shared vote setup function between voteFor and voteAgainst.
* Returns the voter's vote weight. */ | function setupVote(uint motionID)
internal
returns (uint)
{
// There must be an active vote for this target running.
// Vote totals must only change during the voting phase.
require(motionVoting(motionID));
// The voter must not have an active vote this motio... | 0.4.21 |
/* Cancel an existing vote by the sender on a motion
* to confiscate the target balance. */ | function cancelVote(uint motionID)
external
{
// An account may cancel its vote either before the confirmation phase
// when the motion is still open, or after the confirmation phase,
// when the motion has concluded.
// But the totals must not change during the confirm... | 0.4.21 |
// Return the fee charged on top in order to transfer _value worth of tokens. | function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
// Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
// This is on the basis that transfers less than th... | 0.4.21 |
/* Whatever calls this should have either the optionalProxy or onlyProxy modifier,
* and pass in messageSender. */ | function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
require(to != address(0));
// The fee is deducted from the sender's balance, in addition to
// the transferred quantity.
uint fee = transferFeeIncurred(value);
... | 0.4.21 |
/* Withdraw tokens from the fee pool into a given account. */ | function withdrawFee(address account, uint value)
external
returns (bool)
{
require(msg.sender == feeAuthority && account != address(0));
// 0-value withdrawals do nothing.
if (value == 0) {
return false;
}
// Safe subtraction ... | 0.4.21 |
/* Donate tokens from the sender's balance into the fee pool. */ | function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
// Empty donations are disallowed.
uint balance = state.balanceOf(sender);
require(balance != 0);
// safeSub ensures the donor has suf... | 0.4.21 |
/* True if the contract is self-destructible.
* This is true if either the complete liquidation period has elapsed,
* or if all tokens have been returned to the contract and it has been
* in liquidation for at least a week.
* Since the contract is only destructible after the liquidationTimestamp,
* a fortior... | function canSelfDestruct()
public
view
returns (bool)
{
// Not being in liquidation implies the timestamp is uint max, so it would roll over.
// We need to check whether we're in liquidation first.
if (isLiquidating()) {
// These timestamps and dur... | 0.4.21 |
/* Update the current ether price and update the last updated time,
* refreshing the price staleness.
* Also checks whether the contract's collateral levels have fallen to low,
* and initiates liquidation if that is the case.
* Exceptional conditions:
* Not called by the oracle.
* Not the most recen... | function updatePrice(uint price, uint timeSent)
external
postCheckAutoLiquidate
{
// Should be callable only by the oracle.
require(msg.sender == oracle);
// Must be the most recently sent price, but not too far in the future.
// (so we can't lock ourselves out... | 0.4.21 |
/* Issues n nomins into the pool available to be bought by users.
* Must be accompanied by $n worth of ether.
* Exceptional conditions:
* Not called by contract owner.
* Insufficient backing funds provided (post-issuance collateralisation below minimum requirement).
* Price is stale. */ | function replenishPool(uint n)
external
payable
notLiquidating
optionalProxy_onlyOwner
{
// Price staleness check occurs inside the call to fiatBalance.
// Safe additions are unnecessary here, as either the addition is checked on the following line
// ... | 0.4.21 |
/* Sends n nomins to the sender from the pool, in exchange for
* $n plus the fee worth of ether.
* Exceptional conditions:
* Insufficient or too many funds provided.
* More nomins requested than are in the pool.
* n below the purchase minimum (1 cent).
* contract in liquidation.
* Pric... | function buy(uint n)
external
payable
notLiquidating
optionalProxy
{
// Price staleness check occurs inside the call to purchaseEtherCost.
require(n >= MINIMUM_PURCHASE &&
msg.value == purchaseCostEther(n));
address sender = messageSen... | 0.4.21 |
/* Sends n nomins to the pool from the sender, in exchange for
* $n minus the fee worth of ether.
* Exceptional conditions:
* Insufficient nomins in sender's wallet.
* Insufficient funds in the pool to pay sender.
* Price is stale if not in liquidation. */ | function sell(uint n)
external
optionalProxy
{
// Price staleness check occurs inside the call to saleProceedsEther,
// but we allow people to sell their nomins back to the system
// if we're in liquidation, regardless.
uint proceeds;
if (isLiquidati... | 0.4.21 |
/* If a confiscation court motion has passed and reached the confirmation
* state, the court may transfer the target account's balance to the fee pool
* and freeze its participation in further transactions. */ | function confiscateBalance(address target)
external
{
// Should be callable only by the confiscation court.
require(Court(msg.sender) == court);
// A motion must actually be underway.
uint motionID = court.targetMotionID(target);
require(motionID != 0... | 0.4.21 |
/* Anything calling this must apply the onlyProxy or optionalProxy modifiers.*/ | function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
require(to != address(0));
// Insufficient balance will be handled by the safe subtraction.
state.setBalanceOf(sender, safeSub(state.balanceOf(sender), value));
state... | 0.4.21 |
/* Obtain the index of the next schedule entry that will vest for a given user. */ | function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return le... | 0.4.21 |
/* Add a new vesting entry at a given time and quantity to an account's schedule.
* A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as corr... | function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
setupFunction
{
// No empty or already-passed vesting entries allowed.
require(now < time);
require(quantity != 0);
totalVestedBalance = safeAdd(totalVestedBalance,... | 0.4.21 |
/* Allow a user to withdraw any tokens that have vested. */ | function vest()
external
{
uint total;
for (uint i = 0; i < numVestingEntries(msg.sender); i++) {
uint time = getVestingTime(msg.sender, i);
// The list is sorted; when we reach the first future time, bail out.
if (time > now) {
br... | 0.4.21 |
/* Allow the owner of this contract to endow any address with havvens
* from the initial supply. Since the entire initial supply resides
* in the havven contract, this disallows the foundation from withdrawing
* fees on undistributed balances. This function can also be used
* to retrieve any havvens sent to the... | function endow(address account, uint value)
external
optionalProxy_onlyOwner
returns (bool)
{
// Use "this" in order that the havven account is the sender.
// That this is an explicit transfer also initialises fee entitlement information.
return _transfer(thi... | 0.4.21 |
/* Override ERC20 transferFrom function in order to perform
* fee entitlement recomputation whenever balances are updated. */ | function transferFrom(address from, address to, uint value)
external
preCheckFeePeriodRollover
optionalProxy
returns (bool)
{
uint senderPreBalance = state.balanceOf(from);
uint recipientPreBalance = state.balanceOf(to);
// Perform the transfer: if t... | 0.4.21 |
/* Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account. */ | function withdrawFeeEntitlement()
public
preCheckFeePeriodRollover
optionalProxy
{
address sender = messageSender;
// Do not deposit fees into frozen accounts.
require(!nomin.frozen(sender));
// check the period has rolled over first
rollo... | 0.4.21 |
/* Update the fee entitlement since the last transfer or entitlement
* adjustment. Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call. */ | function adjustFeeEntitlement(address account, uint preBalance)
internal
{
// The time since the last transfer clamps at the last fee rollover time if the last transfer
// was earlier than that.
rolloverFee(account, lastTransferTimestamp[account], preBalance);
current... | 0.4.21 |
/* If the fee period has rolled over, then
* save the start times of the last fee period,
* as well as the penultimate fee period.
*/ | function checkFeePeriodRollover()
internal
{
// If the fee period has rolled over...
if (feePeriodStartTime + targetFeePeriodDurationSeconds <= now) {
lastFeesCollected = nomin.feePool();
// Shift the three period start times back one place
penult... | 0.4.21 |
//Event on blockchain which notify client
//===================events definition end==================
//===================Contract Initialization Sequence Definition start=================== | function FloodDragon (
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Gi... | 0.4.19 |
/*
* Funtion: Transfer funtions
* Type:Internal
* Parameters:
@_from: address of sender's account
@_to: address of recipient's account
@_value:transaction amount
*/ | function _transfer(address _from, address _to, uint _value) internal {
//Fault-tolerant processing
require(_to != 0x0); //
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
//Execute transaction
uint previousBalances = balanceOf[_from] + b... | 0.4.19 |
//@return 1~6 | function getOccupationType(uint256 tokenId) public view returns (uint256) {
uint256 rand = random(string(abi.encodePacked("Occupation", toString(tokenId))));
uint256 score = rand % 100;
uint i = 0;
for(; i < roleScoreMatch.length; i++){
if(score <= roleScoreMatch[i]){
... | 0.8.8 |
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/ | function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint256(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
i... | 0.6.6 |
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/ | function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0... | 0.6.6 |
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/ | function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
} | 0.6.6 |
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return... | function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), ... | 0.6.6 |
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other Th... | function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += ... | 0.6.6 |
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/ | function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs o... | 0.6.6 |
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/ | function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := m... | 0.6.6 |
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/ | function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
... | 0.6.6 |
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found. | function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
... | 0.6.6 |
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/ | function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
} | 0.6.6 |
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
*... | function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
... | 0.6.6 |
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/ | function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._... | 0.6.6 |
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/ | function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory r... | 0.6.6 |
// Works like address.send but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function! | function sendETH(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
if (amount == 0) {
return true;
}
address payable recipient = to.toPayable();
/* solium-disable-next-line */
... | 0.6.6 |
/**
* @dev Lets the manager assign an ENS subdomain of the root node to a target address.
* Registers both the forward and reverse ENS.
* @param _owner The owner of the subdomain.
* @param _label The subdomain label.
* @param _approval The signature of _owner and _label by a manager.
*/ | function register(
address _owner,
string calldata _label,
bytes calldata _approval
)
external
override
onlyManager
{
verifyApproval(_owner, _label, _approval);
bytes32 labelNode = keccak256(abi.encodePacked(_label));
by... | 0.6.6 |
// Special case for transactCall to support transfers on "bad" ERC20 tokens | function transactTokenTransfer(
address wallet,
address token,
address to,
uint amount
)
internal
returns (bool success)
{
bytes memory txData = abi.encodeWithSelector(
ERC20(0).transfer.selector,
to,
... | 0.6.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.