comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* Multiply one real by another. Truncates overflows.
*/ | function mul(int256 realA, int256 realB) internal pure returns (int256) {
// When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.
// So we just have to clip off the extra REAL_FBITS fractional bits.
return int256((int256(realA) * int256(realB)) >> REAL_FBITS);
} | 0.4.24 |
/**
* Divide one real by another real. Truncates overflows.
*/ | function div(int256 realNumerator, int256 realDenominator) internal pure returns (int256) {
// We use the reverse of the multiplication trick: convert numerator from
// x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
return int256((int256(realNumerator) * REAL_ONE) / ... | 0.4.24 |
/**
* Raise a number to a positive integer power in O(log power) time.
* See <https://stackoverflow.com/a/101613>
*/ | function ipow(int256 realBase, int216 exponent) internal pure returns (int256) {
if (exponent < 0) {
// Negative powers are not allowed here.
revert();
}
int256 tempRealBase = realBase;
int256 tempExponent = exponent;
// Start with the 0th power... | 0.4.24 |
/**
* Zero all but the highest set bit of a number.
* See <https://stackoverflow.com/a/53184>
*/ | function hibit(uint256 _val) internal pure returns (uint256) {
// Set all the bits below the highest set bit
uint256 val = _val;
val |= (val >> 1);
val |= (val >> 2);
val |= (val >> 4);
val |= (val >> 8);
val |= (val >> 16);
val |= (val >> 32);
... | 0.4.24 |
/**
* Given a number with one bit set, finds the index of that bit.
*/ | function findbit(uint256 val) internal pure returns (uint8 index) {
index = 0;
// We and the value with alternating bit patters of various pitches to find it.
if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) {
// Picth 1
index |= 1;
... | 0.4.24 |
/**
* Shift realArg left or right until it is between 1 and 2. Return the
* rescaled value, and the number of bits of right shift applied. Shift may be negative.
*
* Expresses realArg as realScaled * 2^shift, setting shift to put realArg between [1 and 2).
*
* Rejects 0 or negative arguments.
*/ | function rescale(int256 realArg) internal pure returns (int256 realScaled, int216 shift) {
if (realArg <= 0) {
// Not in domain!
revert();
}
// Find the high bit
int216 highBit = findbit(hibit(uint256(realArg)));
// We'll shift so the high bit i... | 0.4.24 |
/**
* Calculate e^x. Uses the series given at
* <http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html>.
*
* Lets you artificially limit the number of iterations.
*
* Note that it is potentially possible to get an un-converged value; lack
* of convergence does not throw.
*/ | function expLimited(int256 realArg, int maxIterations) internal pure returns (int256) {
// We will accumulate the result here
int256 realResult = 0;
// We use this to save work computing terms
int256 realTerm = REAL_ONE;
for (int216 n = 0; n < maxIterations; n++) {
... | 0.4.24 |
/**
* Raise any number to any power, except for negative bases to fractional powers.
*/ | function pow(int256 realBase, int256 realExponent) internal pure returns (int256) {
if (realExponent == 0) {
// Anything to the 0 is 1
return REAL_ONE;
}
if (realBase == 0) {
if (realExponent < 0) {
// Outside of domain!
... | 0.4.24 |
/**
* Compute the sin of a number to a certain number of Taylor series terms.
*/ | function sinLimited(int256 _realArg, int216 maxIterations) internal pure returns (int256) {
// First bring the number into 0 to 2 pi
// TODO: This will introduce an error for very large numbers, because the error in our Pi will compound.
// But for actual reasonable angle values we should be ... | 0.4.24 |
/**
* @dev Burns `_amount` of reputation from `_from`
* if _amount tokens to burn > balances[_from] the balance of _from will turn to zero.
* @param _from The address that will lose the reputation
* @param _amount The quantity of reputation to burn
* @return True if the reputation are burned correctly
*/ | function burn(address _from, uint _amount)
public
onlyOwner
returns (bool)
{
uint amountMinted = _amount;
if (balances[_from] < _amount) {
amountMinted = balances[_from];
}
totalSupply = totalSupply.sub(amountMinted);
balances[_from] = balanc... | 0.4.24 |
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @return the return bytes of the called contract's function.
*/ | function genericCall(address _contract,bytes _data) public onlyOwner {
// solium-disable-next-line security/no-low-level-calls
bool result = _contract.call(_data);
// solium-disable-next-line security/no-inline-assembly
assembly {
// Copy the returned data.
returnda... | 0.4.24 |
/**
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
* generated by calculating keccak256 of a incremented counter.
* @param _numOfChoices number of voting choices
* @param _avatar an address to be sent as the payload to the _executable contract.
* @param... | function propose(uint _numOfChoices, bytes32 , address _avatar, ExecutableInterface _executable,address _proposer)
external
returns(bytes32)
{
// Check valid params and number of choices:
require(_numOfChoices == NUM_OF_CHOICES);
require(ExecutableInterface(_executabl... | 0.4.24 |
/**
* @dev stakeWithSignature function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @param _nonce nonce value ,it is part of the signature to ensure that
a signature can be received only once.
* @param _signatureType signature type
1 - fo... | function stakeWithSignature(
bytes32 _proposalId,
uint _vote,
uint _amount,
uint _nonce,
uint _signatureType,
bytes _signature
)
external
returns(bool)
{
require(stakeSignatures[_signature] == false);
// Recreate... | 0.4.24 |
/**
* @dev redeemDaoBounty a reward for a successful stake, vote or proposing.
* The function use a beneficiary address as a parameter (and not msg.sender) to enable
* users to redeem on behalf of someone else.
* @param _proposalId the ID of the proposal
* @param _beneficiary - the beneficiary address
* @re... | function redeemDaoBounty(bytes32 _proposalId,address _beneficiary) public returns(uint redeemedAmount,uint potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed));
uint totalWinningS... | 0.4.24 |
/**
* @dev threshold return the organization's score threshold which required by
* a proposal to shift to boosted state.
* This threshold is dynamically set and it depend on the number of boosted proposal.
* @param _avatar the organization avatar
* @param _paramsHash the organization parameters hash
* @retu... | function threshold(bytes32 _paramsHash,address _avatar) public view returns(int) {
uint boostedProposals = getBoostedProposalsCount(_avatar);
int216 e = 2;
Parameters memory params = parameters[_paramsHash];
require(params.thresholdConstB > 0,"should be a valid parameter hash");
... | 0.4.24 |
/**
* @dev hash the parameters, save them if necessary, and return the hash value
* @param _params a parameters array
* _params[0] - _preBoostedVoteRequiredPercentage,
* _params[1] - _preBoostedVotePeriodLimit, //the time limit for a proposal to be in an absolute voting mode.
* _params[2] -_boostedVo... | function setParameters(
uint[14] _params //use array here due to stack too deep issue.
)
public
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] > 0,"0 < preBoostedVoteRequiredPercentage <= 100");
require(_params[4] > 0 && _params[4] <= 100000000,"0 < thresholdCo... | 0.4.24 |
/**
* @dev hashParameters returns a hash of the given parameters
*/ | function getParametersHash(
uint[14] _params) //use array here due to stack too deep issue.
public
pure
returns(bytes32)
{
return keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_param... | 0.4.24 |
/**
* @dev staking function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @param _staker the staker address
* @return bool true - the proposal has been executed
* false - otherwise.
*/ | function _stake(bytes32 _proposalId, uint _vote, uint _amount,address _staker) internal returns(bool) {
// 0 is not a valid vote.
require(_vote <= NUM_OF_CHOICES && _vote > 0);
require(_amount > 0);
if (_execute(_proposalId)) {
return true;
}
Propos... | 0.4.24 |
/**
* @notice Override isApprovedForAll to whitelist user's OpenSea proxy account to enable gas-less listings.
* @dev Used for integration with opensea's Wyvern exchange protocol.
* See {IERC721-isApprovedForAll}.
*/ | function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Create an instance of the ProxyRegistry contract from Opensea
ProxyRegistry proxyRegistry = ProxyRegistry(openseaProxyRegistryAddress);
// whitelist the... | 0.8.12 |
/**
* @dev Override msgSender to allow for meta transactions on OpenSea.
*/ | function _msgSender()
override
internal
view
returns (address sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from m... | 0.8.12 |
/**
* @dev Destroys `amount` tokens from the `account`.
*
* See {ERC20-_burn}.
*/ | function burn(address account, uint256 amount) public onlyOwner {
require(account != address(0), "AdaMarkets: burn from the zero address");
if( _balances[account] == _unlockedTokens[account]){
_unlockedTokens[account] = _unlockedTokens[account].sub(amount, "AdaMarkets: burn amount exc... | 0.8.4 |
// ------------------------------------------------------------------------
// Checks if there is required amount of unLockedTokens available
// ------------------------------------------------------------------------ | function _updateUnLockedTokens(address _from, uint tokens) private returns (bool success) {
// if _unlockedTokens are greater than "tokens" of "to", initiate transfer
if(_unlockedTokens[_from] >= tokens){
return true;
}
// if _unlockedTokens are less than "tokens" of "to... | 0.8.4 |
// ------------------------------------------------------------------------
// Unlocks the coins if lockingPeriod is expired
// ------------------------------------------------------------------------ | function _updateRecord(address account) private returns (bool success){
LockRecord[] memory tempRecords = records[account];
uint256 unlockedTokenCount = 0;
for(uint256 i=0; i < tempRecords.length; i++){
if(tempRecords[i].lockingPeriod < block.timestamp && tempRecords[i].isUnlocke... | 0.8.4 |
//this function only runs when emergency exit is true. this would report a big loss normally so we add a flag to force users to really want to report the loss | function liquidateAllPositions() internal override returns (uint256 _amountFreed){
(_amountFreed,) = liquidatePosition(vault.debtOutstanding());
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 position = deposits.sub(borrows);
//we want to rev... | 0.6.12 |
//called by flash loan | function useLoanTokens(
bool deficit,
uint256 amount,
uint256 repayAmount
) external {
uint256 bal = want.balanceOf(address(this));
require(bal >= amount, "FLASH_FAILED"); // to stop malicious calls
//if in deficit we repay amount and then withdraw
i... | 0.6.12 |
/**
* @dev Mint several HD Punks in a single transaction. Used in presale minting.
*/ | function mintMany(uint[] calldata _punkIds, address to) external payable {
// Take mint fee
require(msg.value >= _punkIds.length * mintFee() || to == owner(), "Please include mint fee");
for (uint i = 0; i < _punkIds.length; i++) {
_mint(_punkIds[i], to, true);
}
} | 0.8.4 |
/**
* @dev Mint `quantity` HDPunks, but chosen randomly. Used in public minting.
*/ | function mintRandom(address to, uint quantity) external payable {
require(_publicMinting || to == owner(), "Wait for public minting");
require(msg.sender == tx.origin, "No funny business");
require(msg.value >= quantity * mintFee() || to == owner(), "Please include mint fee");
// TOD... | 0.8.4 |
/**
* @dev Checks validity of the mint, but not the mint fee.
*/ | function _mint(uint _punkId, address to, bool requireIsOwner) internal {
// Check if token already exists
require(!_exists(_punkId), "HDPunk already minted");
overwriteIndex(_punkId);
if (requireIsOwner) {
address punkOwner = PUNKS.punkIndexToAddress(_punkId);
... | 0.8.4 |
//
//
// All air deliver related functions use counts insteads of wei
// _amount in BioX, not wei
// | function airDeliver(address _to, uint256 _amount) onlyOwner public {
require(owner != _to);
require(_amount > 0);
require(balances[owner].balance >= _amount);
// take big number as wei
if(_amount < bioxSupply){
_amount = _amount * bioxEthRate;
... | 0.4.24 |
//
// _amount, _freezeAmount in BioX
// | function freezeDeliver(address _to, uint _amount, uint _freezeAmount, uint _freezeMonth, uint _unfreezeBeginTime ) onlyOwner public {
require(owner != _to);
require(_freezeMonth > 0);
uint average = _freezeAmount / _freezeMonth;
BalanceInfo storage bi = balances[_to];
... | 0.4.24 |
// View function to see pending CHADs on frontend. | function pendingChad(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accChadPerShare = pool.accChadPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number ... | 0.6.12 |
// Deposit LP tokens to Chadfather for CHAD allocation. | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accChadPerShare).div(1e12).sub(
user.rewardDebt
);
if (pending... | 0.6.12 |
// Withdraw LP tokens from Chadfather. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accChadPerShare).div(1e12).sub(
user.re... | 0.6.12 |
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/ | function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowan... | 0.8.11 |
// Mint Tokens | function mint(uint256 n) public payable {
require(mintMode == MintMode.Open, "Public mint is closed");
require(n <= 7, "Too many tokens");
require(msg.value >= tokenPrice * n, "Didn't send enough ETH");
require(
totalSupply() + n <= maxTokens,
"Can't fulfill reque... | 0.8.0 |
// Mint tokens using voucher | function mintWithVoucher(uint256 n, Voucher calldata voucher)
public
payable
{
require(mintMode != MintMode.Closed, "Minting is closed");
require(msg.value >= tokenPrice * n, "Didn't send enough ETH");
require(
totalSupply() + n <= maxTokens,
"Can't fu... | 0.8.0 |
// Mint 1 token to each address in an array (owner only); | function send(address[] memory addr) external onlyOwner {
require(
totalSupply() + addr.length <= maxTokens,
"Can't fulfill requested tokens"
);
for (uint256 i = 0; i < addr.length; i++) {
_safeMint(addr[i], totalSupply() + 1);
}
devTokensMinte... | 0.8.0 |
// get all tokens owned by an address | function walletOfOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_... | 0.8.0 |
/**
* @notice Function to clear and set list of excluded addresses used for future dividends
* @param _excluded Addresses of investors
*/ | function setDefaultExcluded(address[] _excluded) public withPerm(MANAGE) {
require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, "Too many excluded addresses");
for (uint256 j = 0; j < _excluded.length; j++) {
require (_excluded[j] != address(0), "Invalid address");
for (uint25... | 0.4.24 |
/**
* @notice Function to set withholding tax rates for investors
* @param _investors Addresses of investors
* @param _withholding Withholding tax for individual investors (multiplied by 10**16)
*/ | function setWithholding(address[] _investors, uint256[] _withholding) public withPerm(MANAGE) {
require(_investors.length == _withholding.length, "Mismatched input lengths");
/*solium-disable-next-line security/no-block-members*/
emit SetWithholding(_investors, _withholding, now);
fo... | 0.4.24 |
/**
* @notice Function to set withholding tax rates for investors
* @param _investors Addresses of investor
* @param _withholding Withholding tax for all investors (multiplied by 10**16)
*/ | function setWithholdingFixed(address[] _investors, uint256 _withholding) public withPerm(MANAGE) {
require(_withholding <= 10**18, "Incorrect withholding tax");
/*solium-disable-next-line security/no-block-members*/
emit SetWithholdingFixed(_investors, _withholding, now);
for (uint25... | 0.4.24 |
/**
* @notice Issuer can push dividends to provided addresses
* @param _dividendIndex Dividend to push
* @param _payees Addresses to which to push the dividend
*/ | function pushDividendPaymentToAddresses(
uint256 _dividendIndex,
address[] _payees
)
public
withPerm(DISTRIBUTE)
validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
for (uint256 i = 0; i < _payees.length; i+... | 0.4.24 |
/**
* @notice Issuer can push dividends using the investor list from the security token
* @param _dividendIndex Dividend to push
* @param _start Index in investor list at which to start pushing dividends
* @param _iterations Number of addresses to push dividends for
*/ | function pushDividendPayment(
uint256 _dividendIndex,
uint256 _start,
uint256 _iterations
)
public
withPerm(DISTRIBUTE)
validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
address[] memory investors... | 0.4.24 |
/**
* @notice Calculate amount of dividends claimable
* @param _dividendIndex Dividend to calculate
* @param _payee Affected investor address
* @return claim, withheld amounts
*/ | function calculateDividend(uint256 _dividendIndex, address _payee) public view returns(uint256, uint256) {
require(_dividendIndex < dividends.length, "Invalid dividend");
Dividend storage dividend = dividends[_dividendIndex];
if (dividend.claimed[_payee] || dividend.dividendExcluded[_payee]) ... | 0.4.24 |
/**
* @notice Get the index according to the checkpoint id
* @param _checkpointId Checkpoint id to query
* @return uint256[]
*/ | function getDividendIndex(uint256 _checkpointId) public view returns(uint256[]) {
uint256 counter = 0;
for(uint256 i = 0; i < dividends.length; i++) {
if (dividends[i].checkpointId == _checkpointId) {
counter++;
}
}
uint256[] memory index ... | 0.4.24 |
/**
* @notice Creates a dividend with a provided checkpoint, specifying explicit excluded addresses
* @param _maturity Time from which dividend can be paid
* @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer
* @param _checkpointId Id of the checkpoint from which to issue d... | function _createDividendWithCheckpointAndExclusions(
uint256 _maturity,
uint256 _expiry,
uint256 _checkpointId,
address[] _excluded,
bytes32 _name
)
internal
{
require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, "Too many addresses excluded")... | 0.4.24 |
/**
* @notice Internal function for paying dividends
* @param _payee address of investor
* @param _dividend storage with previously issued dividends
* @param _dividendIndex Dividend to pay
*/ | function _payDividend(address _payee, Dividend storage _dividend, uint256 _dividendIndex) internal {
(uint256 claim, uint256 withheld) = calculateDividend(_dividendIndex, _payee);
_dividend.claimed[_payee] = true;
uint256 claimAfterWithheld = claim.sub(withheld);
if (claimAfter... | 0.4.24 |
/**
* @notice Issuer can reclaim remaining unclaimed dividend amounts, for expired dividends
* @param _dividendIndex Dividend to reclaim
*/ | function reclaimDividend(uint256 _dividendIndex) external withPerm(MANAGE) {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
/*solium-disable-next-line security/no-block-members*/
require(now >= dividends[_dividendIndex].expiry, "Dividend expiry is in the future");
... | 0.4.24 |
/**
* @notice Allows issuer to withdraw withheld tax
* @param _dividendIndex Dividend to withdraw from
*/ | function withdrawWithholding(uint256 _dividendIndex) external withPerm(MANAGE) {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
Dividend storage dividend = dividends[_dividendIndex];
uint256 remainingWithheld = dividend.dividendWithheld.sub(dividend.dividendWithheldRe... | 0.4.24 |
/// @notice Rounds down to the nearest tick where tick % tickSpacing == 0
/// @param tick The tick to round
/// @param tickSpacing The tick spacing to round to
/// @return the floored tick
/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24 | function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod >= 0) return tick - mod;
return tick - mod - tickSpacing;
}
} | 0.8.10 |
/// @notice Rounds up to the nearest tick where tick % tickSpacing == 0
/// @param tick The tick to round
/// @param tickSpacing The tick spacing to round to
/// @return the ceiled tick
/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24 | function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod > 0) return tick - mod + tickSpacing;
return tick - mod;
}
} | 0.8.10 |
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amoun... | function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
amount0 =
FullMath.mul... | 0.8.10 |
/// @dev Withdraws all liquidity and collects all fees | function withdraw(Position memory position, uint128 liquidity)
internal
returns (
uint256 burned0,
uint256 burned1,
uint256 earned0,
uint256 earned1
)
{
if (liquidity != 0) {
(burned0, burned1) = position.pool.burn(position.... | 0.8.10 |
/**
* @notice Amounts of TOKEN0 and TOKEN1 held in vault's position. Includes
* owed fees, except those accrued since last poke.
*/ | function collectableAmountsAsOfLastPoke(Position memory position, uint160 sqrtPriceX96)
internal
view
returns (
uint256,
uint256,
uint128
)
{
if (position.lower == position.upper) return (0, 0, 0);
(uint128 liquidity, , , uint128 e... | 0.8.10 |
/// @inheritdoc IAloeBlendActions | function deposit(
uint256 amount0Max,
uint256 amount1Max,
uint256 amount0Min,
uint256 amount1Min
)
external
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Max != 0 || amount1Max != ... | 0.8.10 |
/**
* @notice Attempts to withdraw `_amount` from silo0. If `_amount` is more than what's available, withdraw the
* maximum amount.
* @dev This reads and writes from/to `maintenanceBudget0`, so use sparingly
* @param _amount The desired amount of token0 to withdraw from silo0
* @return uint256 The actual amount of... | function _silo0Withdraw(uint256 _amount) private returns (uint256) {
unchecked {
uint256 a = silo0Basis;
uint256 b = silo0.balanceOf(address(this));
a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE
if (_amount > b - a) _amount = b - a;
... | 0.8.10 |
/**
* @dev Assumes that `_gasPrice` represents the fair value of 1e4 units of gas, denominated in `_token`.
* Updates the contract's gas price oracle accordingly, including incrementing the array index.
* @param _token The ERC20 token for which average gas price should be updated
* @param _gasPrice The amount of `_... | function _pushGasPrice(address _token, uint256 _gasPrice) private {
uint256[14] storage array = gasPriceArrays[_token];
uint8 idx = gasPriceIdxs[_token];
unchecked {
// New entry cannot be lower than 90% of the previous average
uint256 average = gasPrices[_token];
... | 0.8.10 |
/// @dev Unpacks `packedSlot` from storage, ensuring that `_packedSlot.locked == false` | function _loadPackedSlot()
private
view
returns (
Uniswap.Position memory,
Uniswap.Position memory,
uint48,
uint32,
bool
)
{
PackedSlot memory _packedSlot = packedSlot;
require(!_packedSlot.locked);
r... | 0.8.10 |
/// @inheritdoc IAloeBlendDerivedState | function getInventory() external view returns (uint256 inventory0, uint256 inventory1) {
(Uniswap.Position memory primary, Uniswap.Position memory limit, , , ) = _loadPackedSlot();
(uint160 sqrtPriceX96, , , , , , ) = UNI_POOL.slot0();
(inventory0, inventory1, ) = _getInventory(primary, limit, s... | 0.8.10 |
/// @dev Computes position width based on volatility. Doesn't revert | function _computeNextPositionWidth(uint256 _sigma) internal pure returns (int24) {
if (_sigma <= 9.9491783619e15) return MIN_WIDTH; // \frac{1e18}{B} (1 - \frac{1}{1.0001^(MIN_WIDTH / 2)})
if (_sigma >= 3.7500454036e17) return MAX_WIDTH; // \frac{1e18}{B} (1 - \frac{1}{1.0001^(MAX_WIDTH / 2)})
_... | 0.8.10 |
/// @dev Computes amounts that should be placed in primary Uniswap position to maintain 50/50 inventory ratio.
/// Doesn't revert as long as MIN_WIDTH <= _halfWidth * 2 <= MAX_WIDTH | function _computeMagicAmounts(
uint256 _inventory0,
uint256 _inventory1,
int24 _halfWidth
) internal pure returns (uint256 amount0, uint256 amount1) {
// the fraction of total inventory (X96) that should be put into primary Uniswap order to mimic Uniswap v2
uint96 magic = uin... | 0.8.10 |
/*function changePartnerShare(address partner, uint new_share) public onlyOwner {
if
ownerAddresses[partner] = new_share;
ownerAddresses[owner]=
}*/ | function destroy() onlyOwner public {
// Transfer tokens back to owner
uint256 balance = token.balanceOf(this);
assert(balance > 0);
token.transfer(owner, balance);
// There should be no ether in the contract but just in case
selfdestruct(owner);
} | 0.4.22 |
// change owner to 0x0 to lock this function | function editTokenProperties(string _name, string _symbol, int256 extraSupplay) onlyOwner public {
name = _name;
symbol = _symbol;
if (extraSupplay > 0)
{
balanceOf[owner] = balanceOf[owner].add(uint256(extraSupplay));
totalSupply = totalSupply.add(uint256(e... | 0.4.24 |
// get the tokens that we supports | function getSupportedTokenAddresses() public view returns (address[] memory){
address[] memory supportedTokenAddresses = new address[](supportedTokensCount);
uint16 count = 0;
for ( uint256 i = 0 ; i < tokenAddresses.length ; i ++ ){
if (supportedTokens[tokenAddresses[i]]) {
... | 0.8.7 |
/* Sushi IRewarder overrides */ | function onSushiReward(
uint256 _pid,
address _user,
address _to,
uint256,
uint256 _lpToken
) external override onlyMCV2 {
PoolInfo memory pool = updatePool(_pid);
UserInfo storage user = userInfo[_pid][_user];
uint256 pending;
if (user.amount ... | 0.6.12 |
/// @dev Assigns ownership of a specific deed to an address.
/// @param _from The address to transfer the deed from.
/// @param _to The address to transfer the deed to.
/// @param _deedId The identifier of the deed to transfer. | function _transfer(address _from, address _to, uint256 _deedId) internal {
// The number of plots is capped at 2^16 * 2^16, so this cannot
// be overflowed.
ownershipDeedCount[_to]++;
// Transfer ownership.
identifierToOwner[_deedId] = _to;
// Wh... | 0.4.18 |
/// @notice Approve a given address to take ownership of multiple deeds.
/// @param _to The address to approve taking ownership.
/// @param _deedIds The identifiers of the deeds to give approval for. | function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Ensure the sender is not approving themselves.
require(msg.sender != _to);
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
// Requir... | 0.4.18 |
/// @notice Transfers multiple deeds to another address. If transferring to
/// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721,
/// or your deeds may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _deedIds The identifiers of the deeds to trans... | function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
... | 0.4.18 |
/// @notice Transfer multiple deeds owned by another address, for which the
/// calling address has previously been granted transfer approval by the owner.
/// @param _deedIds The identifier of the deed to be transferred. | function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused {
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
address _from = identifierToOwner[_deedId];
// Check for transfer approval
require(_approved... | 0.4.18 |
/// @notice Returns a list of all deed identifiers assigned to an address.
/// @param _owner The owner whose deeds we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. It's very
/// expensive and is not supported in contract-to-contract calls as it returns
/// a dynamic array (only su... | function deedsOfOwner(address _owner) external view returns(uint256[]) {
uint256 deedCount = countOfDeedsByOwner(_owner);
if (deedCount == 0) {
// Return an empty array.
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](deedCoun... | 0.4.18 |
/// @notice Returns a deed identifier of the owner at the given index.
/// @param _owner The address of the owner we want to get a deed for.
/// @param _index The index of the deed we want. | function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
// The index should be valid.
require(_index < countOfDeedsByOwner(_owner));
// Loop through all plots, accounting the number of plots of the owner we've seen.
uint256 seen = 0;
u... | 0.4.18 |
/// @notice Returns an (off-chain) metadata url for the given deed.
/// @param _deedId The identifier of the deed to get the metadata
/// url for.
/// @dev Implementation of optional ERC-721 functionality. | function deedUri(uint256 _deedId) external pure returns (string uri) {
require(validIdentifier(_deedId));
var (x, y) = identifierToCoordinate(_deedId);
// Maximum coordinate length in decimals is 5 (65535)
uri = "https://dworld.io/plot/xxxxx/xxxxx";
bytes memory ... | 0.4.18 |
/// @dev Rent out a deed to an address.
/// @param _to The address to rent the deed out to.
/// @param _rentPeriod The rent period in seconds.
/// @param _deedId The identifier of the deed to rent out. | function _rentOut(address _to, uint256 _rentPeriod, uint256 _deedId) internal {
// Set the renter and rent period end timestamp
uint256 rentPeriodEndTimestamp = now.add(_rentPeriod);
identifierToRenter[_deedId] = _to;
identifierToRentPeriodEndTimestamp[_deedId] = rentPeriodEndTimesta... | 0.4.18 |
/// @notice Rents multiple plots out to another address.
/// @param _to The address of the renter, can be a user or contract.
/// @param _rentPeriod The rent time period in seconds.
/// @param _deedIds The identifiers of the plots to rent out. | function rentOutMultiple(address _to, uint256 _rentPeriod, uint256[] _deedIds) public whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to !... | 0.4.18 |
/// @notice Returns the address of the currently assigned renter and
/// end time of the rent period of a given plot.
/// @param _deedId The identifier of the deed to get the renter and
/// rent period for. | function renterOf(uint256 _deedId) external view returns (address _renter, uint256 _rentPeriodEndTimestamp) {
require(validIdentifier(_deedId));
if (identifierToRentPeriodEndTimestamp[_deedId] < now) {
// There is no active renter
_renter = address(0);
_ren... | 0.4.18 |
/// @dev Calculate the current price of an auction. | function _currentPrice(Auction storage _auction) internal view returns (uint256) {
require(now >= _auction.startedAt);
uint256 secondsPassed = now - _auction.startedAt;
if (secondsPassed >= _auction.duration) {
return _auction.endPrice;
} else {
... | 0.4.18 |
/// @dev Calculate the fee for a given price.
/// @param _price The price to calculate the fee for. | function _calculateFee(uint256 _price) internal view returns (uint256) {
// _price is guaranteed to fit in a uint128 due to the createAuction entry
// modifiers, so this cannot overflow.
return _price * fee / 100000;
} | 0.4.18 |
/// @notice Get the auction for the given deed.
/// @param _deedId The identifier of the deed to get the auction for.
/// @dev Throws if there is no auction for the given deed. | function getAuction(uint256 _deedId) external view returns (
address seller,
uint256 startPrice,
uint256 endPrice,
uint256 duration,
uint256 startedAt
)
{
Auction storage auction = identifierToAuction[_deedId];
//... | 0.4.18 |
/// @notice Create an auction for a given deed.
/// Must previously have been given approval to take ownership of the deed.
/// @param _deedId The identifier of the deed to create an auction for.
/// @param _startPrice The starting price of the auction.
/// @param _endPrice The ending price of the auction.
/// @param _... | function createAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration)
public
fitsIn128Bits(_startPrice)
fitsIn128Bits(_endPrice)
fitsIn64Bits(_duration)
whenNotPaused
{
// Get the owner of the deed to be auctioned
address d... | 0.4.18 |
/// @notice Cancel an auction
/// @param _deedId The identifier of the deed to cancel the auction for. | function cancelAuction(uint256 _deedId) external whenNotPaused {
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active.
require(_activeAuction(auction));
// The auction can only be cancelled by the seller
require(msg.sender... | 0.4.18 |
/// @notice Withdraw ether owed to a beneficiary.
/// @param beneficiary The address to withdraw the auction balance for. | function withdrawAuctionBalance(address beneficiary) external {
// The sender must either be the beneficiary or the core deed contract.
require(
msg.sender == beneficiary ||
msg.sender == address(deedContract)
);
uint256 etherOwed = addressToEtherO... | 0.4.18 |
/// @notice Withdraw (unowed) contract balance. | function withdrawFreeBalance() external {
// Calculate the free (unowed) balance. This never underflows, as
// outstandingEther is guaranteed to be less than or equal to the
// contract balance.
uint256 freeBalance = this.balance - outstandingEther;
address deedCon... | 0.4.18 |
/// @notice Create an auction for a given deed. Be careful when calling
/// createAuction for a RentAuction, that this overloaded function (including
/// the _rentPeriod parameter) is used. Otherwise the rent period defaults to
/// a week.
/// Must previously have been given approval to take ownership of the deed.
/// ... | function createAuction(
uint256 _deedId,
uint256 _startPrice,
uint256 _endPrice,
uint256 _duration,
uint256 _rentPeriod
)
external
{
// Require the rent period to be at least one hour.
require(_rentPeriod >= 3600);
// R... | 0.4.18 |
/// @dev Perform the bid win logic (in this case: give renter status to the winner).
/// @param _seller The address of the seller.
/// @param _winner The address of the winner.
/// @param _deedId The identifier of the deed.
/// @param _price The price the auction was bought at. | function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal {
DWorldRenting dWorldRentingContract = DWorldRenting(deedContract);
uint256 rentPeriod = identifierToRentPeriod[_deedId];
if (rentPeriod == 0) {
rentPeriod = 604800; // 1 week by d... | 0.4.18 |
/// @notice Create a sale auction.
/// @param _deedId The identifier of the deed to create a sale auction for.
/// @param _startPrice The starting price of the sale auction.
/// @param _endPrice The ending price of the sale auction.
/// @param _duration The duration in seconds of the dynamic pricing part of the sale au... | function createSaleAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration)
external
whenNotPaused
{
require(_owns(msg.sender, _deedId));
// Prevent creating a sale auction if no sale auction contract is configured.
require(address(s... | 0.4.18 |
/// @notice Allow withdrawing balances from the auction contracts
/// in a single step. | function withdrawAuctionBalances() external {
// Withdraw from the sale contract if the sender is owed Ether.
if (saleAuctionContract.addressToEtherOwed(msg.sender) > 0) {
saleAuctionContract.withdrawAuctionBalance(msg.sender);
}
// Withdraw from the rent contr... | 0.4.18 |
/// @notice Set the data associated with a plot. | function setPlotData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl)
public
whenNotPaused
{
// The sender requesting the data update should be
// the owner (without an active renter) or should
// be the active renter.
require(... | 0.4.18 |
/// @notice Set the data associated with multiple plots. | function setPlotDataMultiple(uint256[] _deedIds, string name, string description, string imageUrl, string infoUrl)
external
whenNotPaused
{
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
setPlotData(_deedId, name, descri... | 0.4.18 |
/**
* @dev Sets the values for `name` and `symbol`. Both of
* these values are immutable: they can only be set once during
* construction.
*/ | function init(string memory name, string memory symbol, address _beneficiary) public {
require(beneficiary == address(0), "Already initialized");
_name = name;
_symbol = symbol;
// Set beneficiary
require(_beneficiary != address(0), "Beneficiary can't be zero");
beneficiary = _beneficiary;
... | 0.5.11 |
// 10B tokens | function mintWithETH(PooledCDAI pcDAI, address to) public payable returns (bool) {
// convert `msg.value` ETH to DAI
ERC20 dai = ERC20(DAI_ADDRESS);
(uint256 actualDAIAmount, uint256 actualETHAmount) = _kyberTrade(ETH_TOKEN_ADDRESS, msg.value, dai);
// mint `actualDAIAmount` pcDAI
_mint(pcDAI, to, ... | 0.5.11 |
/**
* @notice Wrapper function for doing token conversion on Kyber Network
* @param _srcToken the token to convert from
* @param _srcAmount the amount of tokens to be converted
* @param _destToken the destination token
* @return _destPriceInSrc the price of the dest token, in terms of source tokens
* _src... | function _kyberTrade(ERC20 _srcToken, uint256 _srcAmount, ERC20 _destToken)
internal
returns(
uint256 _actualDestAmount,
uint256 _actualSrcAmount
)
{
// Get current rate & ensure token is listed on Kyber
KyberNetworkProxy kyber = KyberNetworkProxy(KYBER_ADDRESS);
(, uint256 rate) =... | 0.5.11 |
/**
* @notice Modify a uint256 parameter
* @param parameter The parameter name
* @param data The new parameter value
**/ | function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "openRefill") {
require(data <= 1, "StakeRewardRefill/invalid-open-refill");
openRefill = data;
} else if (parameter == "lastRefillTime") {
require(data >= lastRefillTim... | 0.6.7 |
/**
* @notice Send tokens to refillDestination
* @dev This function can only be called if msg.sender passes canRefill checks
**/ | function refill() external canRefill {
uint256 delay = subtract(now, lastRefillTime);
require(delay >= refillDelay, "StakeRewardRefill/wait-more");
// Update the last refill time
lastRefillTime = subtract(now, delay % refillDelay);
// Send tokens
uint256 amountT... | 0.6.7 |
// ------------------------------------------------------------------------
// 1,000 tokens per 1 ETH, with 20% bonus
// ------------------------------------------------------------------------ | function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 12000;
} else {
tokens = msg.value * 10000;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
... | 0.4.19 |
/********************************************\
* @dev Deposit function
* Anyone can pay while contract is active
\********************************************/ | function () public payable autobidActive {
// Calculate number of tokens owed to sender
uint tokenQuantity = msg.value * exchangeRate;
// Ensure that sender receives their tokens
require(Token(token).transfer(msg.sender, tokenQuantity));
// Check if contract has now expired (i.e. is empty)
... | 0.4.19 |
/******************************************************\
* @dev Redeem function (exchange tokens back to ETH)
* @param amount Number of tokens exchanged
* Anyone can redeem while contract is active
\******************************************************/ | function redeemTokens(uint amount) public autobidActive {
// NOTE: redeemTokens will only work once the sender has approved
// the RedemptionContract address for the deposit amount
require(Token(token).transferFrom(msg.sender, this, amount));
uint redemptionValue = amount / exchangeRate;
... | 0.4.19 |
/**************************************************************\
* @dev Expires contract if any expiration criteria is met
* (declared as public function to allow direct manual call)
\**************************************************************/ | function expirationCheck() public {
// If expirationTime has been passed, contract expires
if (now > expirationTime) {
active = false;
}
// If the contract's token supply is depleted, it expires
uint remainingTokenSupply = Token(token).balanceOf(this);
if (remainingTokenSupply < e... | 0.4.19 |
// get decision result address | function _getFinalAddress(uint[] _amounts, address[] _buyers, uint result) internal pure returns (address finalAddress) {
uint congest = 0;
address _finalAddress = 0x0;
for (uint j = 0; j < _amounts.length; j++) {
congest += _amounts[j];
if (result <= congest && _fin... | 0.4.20 |
// 500ETH investors, everyone 5% | function _shareOut(uint feeAmount) internal {
uint shareAmount;
address investor;
for (uint k = 0; k < investors.length; k++) {
shareAmount = feeAmount * 5 / 100;
investor = investors[k];
balanceOf[investor] += shareAmount;
quotaOf[investor]... | 0.4.20 |
// mall application delegate transfer | function delegateTransfer(address _from, address _to, uint _value, uint _fee) onlyOwner public {
if (_fee > 0) {
require(_fee < 100 * 10 ** uint256(decimals));
quotaOf[owner] += _fee;
}
if (_from != owner && _to != owner) {
_transfer(_from, owner, _fee);... | 0.4.20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.