comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/** @dev Request arbitration from Kleros for given _questionID.
* @param _questionID The question identifier in Realitio contract.
* @param _maxPrevious If specified, reverts if a bond higher than this was submitted after you sent your transaction.
* @return disputeID ID of the resulting dispute on arbitrator.
*... | function requestArbitration(bytes32 _questionID, uint256 _maxPrevious) external payable returns (uint256 disputeID) {
ArbitrationRequest storage arbitrationRequest = arbitrationRequests[uint256(_questionID)];
require(arbitrationRequest.status == Status.None, "Arbitration already requested");
//... | 0.7.6 |
/** @dev Receives ruling from Kleros and enforces it.
* @param _disputeID ID of Kleros dispute.
* @param _ruling Ruling that is given by Kleros. This needs to be converted to Realitio answer before reporting the answer by shifting by 1.
*/ | function rule(uint256 _disputeID, uint256 _ruling) public override {
require(IArbitrator(msg.sender) == arbitrator, "Only arbitrator allowed");
uint256 questionID = externalIDtoLocalID[_disputeID];
ArbitrationRequest storage arbitrationRequest = arbitrationRequests[questionID];
require... | 0.7.6 |
/** @dev Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved. For all rounds at once.
* This function has O(m) time complexity where m is number of rounds.
* It is safe to assume m is always less than 10 as appeal cost growth order is O(2^m).
* @param _questionID Identifier of the ... | function withdrawFeesAndRewardsForAllRounds(
uint256 _questionID,
address payable _contributor,
uint256 _ruling
) external override {
ArbitrationRequest storage arbitrationRequest = arbitrationRequests[_questionID];
uint256 noOfRounds = arbitrationRequest.rounds.length;
... | 0.7.6 |
/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved.
* @param _questionID Identifier of the Realitio question, casted to uint. This also serves as the local identifier in this contract.
* @param _contributor The address whose rewards to withdraw.
* @param _roundNumber The nu... | function withdrawFeesAndRewards(
uint256 _questionID,
address payable _contributor,
uint256 _roundNumber,
uint256 _ruling
) public override returns (uint256 amount) {
ArbitrationRequest storage arbitrationRequest = arbitrationRequests[_questionID];
require(arbitration... | 0.7.6 |
/** @dev Returns the sum of withdrawable amount.
* This function has O(m) time complexity where m is number of rounds.
* It is safe to assume m is always less than 10 as appeal cost growth order is O(m^2).
* @param _questionID Identifier of the Realitio question, casted to uint. This also serves as the local iden... | function getTotalWithdrawableAmount(
uint256 _questionID,
address payable _contributor,
uint256 _ruling
) external view override returns (uint256 sum) {
ArbitrationRequest storage arbitrationRequest = arbitrationRequests[_questionID];
if (arbitrationRequest.status < Status.Ru... | 0.7.6 |
/** @dev Returns withdrawable amount for given parameters.
* @param _round The round to calculate amount for.
* @param _contributor The contributor for which to query.
* @param _ruling The ruling option to search for potential withdrawal.
* @param _finalRuling Final ruling given by arbitrator.
* @return amoun... | function getWithdrawableAmount(
Round storage _round,
address _contributor,
uint256 _ruling,
uint256 _finalRuling
) internal view returns (uint256 amount) {
if (!_round.hasPaid[_ruling]) {
// Allow to reimburse if funding was unsuccessful for this ruling option.
... | 0.7.6 |
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update.
* - Add any relevan... | function _delivery(PurchaseData memory purchase) internal virtual override {
super._delivery(purchase);
uint256[] memory ids = new uint256[](purchase.quantity);
uint256[] memory values = new uint256[](purchase.quantity);
for (uint256 index = 0; index != purchase.quantity; ++index... | 0.6.8 |
/**
* Adds additional tokens to the sale supply.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `tokens` is empty.
* @dev Reverts if any of `tokens` are zero.
* @dev The list of tokens specified (in sequence) will be appended to the end of the ordered
* sale supply list.
... | function addSupply(uint256[] memory tokens) public virtual onlyOwner {
uint256 numTokens = tokens.length;
// solhint-disable-next-line reason-string
require(numTokens != 0, "FixedOrderInventorySale: empty tokens to add");
for (uint256 i = 0; i != numTokens; ++i) {
ui... | 0.6.8 |
/**
* Sets the tokens of the ordered sale supply list.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if called when the contract is not paused.
* @dev Reverts if the sale supply is empty.
* @dev Reverts if the lengths of `indexes` and `tokens` do not match.
* @dev Reverts if ... | function setSupply(uint256[] memory indexes, uint256[] memory tokens) public virtual onlyOwner whenPaused {
uint256 tokenListLength = tokenList.length;
// solhint-disable-next-line reason-string
require(tokenListLength != 0, "FixedOrderInventorySale: empty token list");
uint256 n... | 0.6.8 |
/**
* @dev Handle the SGA to SGR exchange.
*/ | function handleExchangeSGAtoSGRFor(address _sgaHolder) internal {
uint256 allowance = sgaToken.allowance(_sgaHolder, address(this));
require(allowance > 0, "SGA allowance must be greater than zero");
uint256 balance = sgaToken.balanceOf(_sgaHolder);
require(balance > 0, "SGA balance must... | 0.4.25 |
/**
* We originally passed the userIDs as: bytes20[] userIDs
* But it was discovered that this was inefficiently packed,
* and ended up sending 12 bytes of zero's per userID.
* Since gtxdatazero is set to 4 gas/bytes, this translated into
* 48 gas wasted per user due to inefficient packing.
**/ | function addMerkleTreeRoot(bytes32 merkleTreeRoot, bytes userIDsPacked) public onlyByOwner {
if (merkleTreeRoot == bytes32(0)) require(false);
bool addedUser = false;
uint numUserIDs = userIDsPacked.length / 20;
for (uint i = 0; i < numUserIDs; i++)
{
bytes20 userID;
assembly {
userID ... | 0.4.24 |
/// Utility function to return a full array of all your EtherFly | function getMyEtherFlies() public view returns (uint256[] memory) {
uint256 itemCount = balanceOf(msg.sender);
uint256[] memory items = new uint256[](itemCount);
for (uint256 i = 0; i < itemCount; i++) {
items[i] = tokenOfOwnerByIndex(msg.sender, i);
}
return ... | 0.8.4 |
/**
* @notice Returns interest earned since last rebalance.
* @dev Make sure to return value in collateral token and in order to do that
* we are using Uniswap to get collateral amount for earned DAI.
*/ | function interestEarned() external view virtual returns (uint256) {
uint256 daiBalance = _getDaiBalance();
uint256 debt = cm.getVaultDebt(vaultNum);
if (daiBalance > debt) {
uint256 daiEarned = daiBalance.sub(debt);
IUniswapV2Router02 uniswapRouter = IUniswapV2Router... | 0.6.12 |
/// @dev Create new Maker vault | function _createVault(bytes32 _collateralType, address _cm) internal returns (uint256 vaultId) {
address mcdManager = ICollateralManager(_cm).mcdManager();
ManagerInterface manager = ManagerInterface(mcdManager);
vaultId = manager.open(_collateralType, address(this));
manager.cdpAllo... | 0.6.12 |
// EIP-1167 | function derivate(bytes32 salt) external returns (address result) {
bytes20 targetBytes = bytes20(address(this));
assembly {
let bs := mload(0x40)
mstore(bs, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(bs, 0x14), targetBytes)
... | 0.8.9 |
/**
* @notice Deposit ETH to mint cube tokens
* @dev Quantity of cube tokens minted is calculated from the amount of ETH
* attached with transaction
* @param cubeToken Which cube token to mint
* @param recipient Address that receives the cube tokens
* @return cubeTokensOut Quantity of cube tokens that were minted... | function deposit(CubeToken cubeToken, address recipient)
external
payable
nonReentrant
returns (uint256 cubeTokensOut)
{
CubeTokenParams storage _params = params[cubeToken];
require(_params.added, "Not added");
require(!_params.depositPaused, "Paused");
... | 0.6.12 |
/**
* @notice Burn cube tokens to withdraw ETH
* @param cubeToken Which cube token to burn
* @param cubeTokensIn Quantity of cube tokens to burn
* @param recipient Address that receives the withdrawn ETH
* @return ethOut Amount of ETH withdrawn
*/ | function withdraw(
CubeToken cubeToken,
uint256 cubeTokensIn,
address recipient
) external nonReentrant returns (uint256 ethOut) {
CubeTokenParams storage _params = params[cubeToken];
require(_params.added, "Not added");
require(!_params.withdrawPaused, "Paused");
... | 0.6.12 |
/**
* @notice Add a new cube token. Can only be called by governance.
* @param spotSymbol Symbol of underlying token. Used to fetch price from oracle
* @param inverse True means 3x short token. False means 3x long token.
* @return address Address of cube token that was added
*/ | function addCubeToken(
string memory spotSymbol,
bool inverse,
uint256 depositWithdrawFee,
uint256 maxPoolShare
) external onlyGovernance returns (address) {
require(address(cubeTokensMap[spotSymbol][inverse]) == address(0), "Already added");
bytes32 salt = keccak256... | 0.6.12 |
/**
* @notice Calculate ETH withdrawn when burning `cubeTokensIn` cube tokens.
*/ | function quoteWithdraw(CubeToken cubeToken, uint256 cubeTokensIn) external view returns (uint256) {
(uint256 price, uint256 _totalEquity) = _priceAndTotalEquity(cubeToken);
uint256 ethOut = _mulPrice(cubeTokensIn, price, _totalEquity, poolBalance());
uint256 fees = _mulFee(ethOut, params[cubeTok... | 0.6.12 |
/**
* @notice Get the underlying price of a listed cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18)
*/ | function getUnderlyingPrice(CToken cToken) public view returns (uint) {
address cTokenAddress = address(cToken);
if (cTokenAddress == cEthAddress) {
// ether always worth 1
return 1e18;
}
// Handle xSUSHI.
if (cTokenAddress == cXSushiAddress) {
... | 0.5.17 |
/**
* @notice Get the price of a specific token. Return 1e18 is it's WETH.
* @param token The token to get the price of
* @return The price
*/ | function getTokenPrice(address token) internal view returns (uint) {
if (token == wethAddress) {
// weth always worth 1
return 1e18;
}
AggregatorV3Interface aggregator = aggregators[token];
if (address(aggregator) != address(0)) {
uint price = getPric... | 0.5.17 |
/**
* @notice Get price from ChainLink
* @param aggregator The ChainLink aggregator to get the price of
* @return The price
*/ | function getPriceFromChainlink(AggregatorV3Interface aggregator) internal view returns (uint) {
( , int price, , , ) = aggregator.latestRoundData();
require(price > 0, "invalid price");
// Extend the decimals to 1e18.
return mul_(uint(price), 10**(18 - uint(aggregator.decimals())));
... | 0.5.17 |
/**
* @notice Get the fair price of a LP. We use the mechanism from Alpha Finance.
* Ref: https://blog.alphafinance.io/fair-lp-token-pricing/
* @param pair The pair of AMM (Uniswap or SushiSwap)
* @return The price
*/ | function getLPFairPrice(address pair) internal view returns (uint) {
address token0 = IUniswapV2Pair(pair).token0();
address token1 = IUniswapV2Pair(pair).token1();
uint totalSupply = IUniswapV2Pair(pair).totalSupply();
(uint r0, uint r1, ) = IUniswapV2Pair(pair).getReserves();
u... | 0.5.17 |
/**
* @notice Get price for Yvault tokens
* @param token The Yvault token
* @return The price
*/ | function getYvTokenPrice(address token) internal view returns (uint) {
YvTokenInfo memory yvTokenInfo = yvTokens[token];
require(yvTokenInfo.isYvToken, "not a Yvault token");
uint pricePerShare;
address underlying;
if (yvTokenInfo.version == YvTokenVersion.V1) {
pric... | 0.5.17 |
/**
* @notice Get price for curve pool tokens
* @param token The curve pool token
* @return The price
*/ | function getCrvTokenPrice(address token) internal view returns (uint) {
CrvTokenInfo memory crvTokenInfo = crvTokens[token];
require(crvTokenInfo.isCrvToken, "not a curve pool token");
uint virtualPrice = CurveSwapInterface(crvTokenInfo.curveSwap).get_virtual_price();
if (crvTokenInfo.p... | 0.5.17 |
/**
* @notice Set ChainLink aggregators for multiple cTokens
* @param tokenAddresses The list of underlying tokens
* @param sources The list of ChainLink aggregator sources
*/ | function _setAggregators(address[] calldata tokenAddresses, address[] calldata sources) external {
require(msg.sender == admin || msg.sender == guardian, "only the admin or guardian may set the aggregators");
require(tokenAddresses.length == sources.length, "mismatched data");
for (uint i = 0; i... | 0.5.17 |
/**
* @notice See assets as LP tokens for multiple cTokens
* @param cTokenAddresses The list of cTokens
* @param isLP The list of cToken properties (it's LP or not)
*/ | function _setLPs(address[] calldata cTokenAddresses, bool[] calldata isLP) external {
require(msg.sender == admin, "only the admin may set LPs");
require(cTokenAddresses.length == isLP.length, "mismatched data");
for (uint i = 0; i < cTokenAddresses.length; i++) {
areUnderlyingLPs[cT... | 0.5.17 |
/**
* @notice See assets as Yvault tokens for multiple cTokens
* @param tokenAddresses The list of underlying tokens
* @param version The list of vault version
*/ | function _setYVaultTokens(address[] calldata tokenAddresses, YvTokenVersion[] calldata version) external {
require(msg.sender == admin, "only the admin may set Yvault tokens");
require(tokenAddresses.length == version.length, "mismatched data");
for (uint i = 0; i < tokenAddresses.length; i++) {... | 0.5.17 |
/**
* @notice See assets as curve pool tokens for multiple cTokens
* @param tokenAddresses The list of underlying tokens
* @param poolType The list of curve pool type (ETH or USD base only)
* @param swap The list of curve swap address
*/ | function _setCurveTokens(address[] calldata tokenAddresses, CurvePoolType[] calldata poolType, address[] calldata swap) external {
require(msg.sender == admin, "only the admin may set curve pool tokens");
require(tokenAddresses.length == poolType.length && tokenAddresses.length == swap.length, "mismatch... | 0.5.17 |
//
// Dessert distribution for each OCM# (j)
//
// If offset is 0, 15 Dessert3s at j = 364, 1301, 1453, 1527, 1601, 1629, 2214, 4097, 5227, 5956, 6694, 6754, 7442, 9132, 9850
// Overall distribution of Desserts is 15 Dessert3, 4485 Dessert2, 5500 Dessert1
// | function dessert(uint256 j) public view returns (uint256) {
require(counter > 0, "Dessert not served");
require(j>0 && j<10001, 'error');
j = (j + offset) % 10000; // this is the fair and random offset from the VRF
uint256 r = (uint256(keccak256(abi.encode(j.toString())))) % 10000; // th... | 0.8.7 |
// return a * b | function mul(uint256 a, uint256 b) public pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "mul overflow");
return c;
} | 0.6.8 |
// return the greatest uint256 less than or equal to the square root of a | function sqrt(uint256 a) public pure returns (uint256) {
uint256 result = 0;
uint256 bit = 1 << 254; // the second to top bit
while (bit > a) {
bit >>= 2;
}
while (bit != 0) {
uint256 sum = result + bit;
result >>= 1;
if (a... | 0.6.8 |
/// @dev call token.approve(this, _tokens) before this
/// @notice sells tokens for eth; if there is not enough eth in the exchange,
/// or amount of tokens is too big, only appropriate amount of tokens will be used for sale;
/// reverts if balance of the exchange is greater than 5*10^24 tokens | function sell(uint256 _tokens) public {
uint256 tokensBefore = Erc20(token).balanceOf(address(this));
require(tokensBefore <= maxAmount, "big balance");
uint256 tokensAfter = tokensBefore.add(_tokens);
if (tokensAfter > maxAmount) {
tokensAfter = maxAmount;
... | 0.6.8 |
/// @notice feel free to clean from all spam tokens,
/// grab free tokens if there is too much of them | function clean(address _contract, uint256 _value) public {
if (_contract == token) {
uint256 tokens = Erc20(token).balanceOf(address(this));
require(tokens > maxAmount, "no free tokens");
require(_value <= tokens.sub(maxAmount), "big _value");
}
Erc20(_c... | 0.6.8 |
/// @dev reverts if balance of the exchange is greater than 5*10^24 tokens
/// @return eth/10^18 to receive from sale of provided number of tokens/10^18 | function tokensToEthForSale(uint256 _tokens) public view returns (uint256) {
uint256 tokensBefore = Erc20(token).balanceOf(address(this));
require(tokensBefore <= maxAmount, "big balance");
uint256 tokensAfter = tokensBefore.add(_tokens);
if (tokensAfter > maxAmount) {
t... | 0.6.8 |
/// @dev reverts if there is not enough eth in the exchange,
/// or amount of tokens is too big,
/// or balance of the exchange is greater than 5*10^24 tokens
/// @return amount of tokens/10^18 required to get desired amount of eth/10^18 | function ethToTokensForSale(uint256 _eth) public view returns (uint256) {
uint256 tokensBefore = Erc20(token).balanceOf(address(this));
require(tokensBefore <= maxAmount, "big balance");
require(_eth <= address(this).balance, "big _eth");
uint256 tokensAfter = v(tokensBefore, false, ... | 0.6.8 |
// v0 - current volume in tokens
// require v0 <= 5*10^24, check this before!
// isV0Right - bool, if true, returns v <= v0, else returns v >= v0
// s - sum in wei
// returns volume v in tokens, reverts if s is too big
// 0 <= v <= 5*10^24 | function v(uint256 v0, bool isV0Right, uint256 s) private pure returns (uint256) {
uint256 d = 10**50;
if (isV0Right) {
d = d.add(s.mul(4*10**25)).sub(Math.sub(10**25, v0).mul(v0).mul(4));
} else {
d = d.sub(s.mul(4*10**25)).sub(Math.sub(10**25, v0).mul(v0).mul(4));
... | 0.6.8 |
/**
* recover '_from' address by signature
*/ | function testVerify(bytes32 s, bytes32 r, uint8 v, address _to, uint256 _value, uint256 _fee, uint256 _nonce) internal view returns (address) {
Unit memory _msgobj = Unit({
to : _to,
value : _value,
fee : _fee,
nonce : _nonce
});
return ecrecover(hashUnit(_msgobj)... | 0.4.26 |
/**
* burn the specific signature from the signatures
*
* Requirement:
* - sender(Caller) should be signer of that specific signature
*/ | function burnTransaction(bytes32 s, bytes32 r, uint8 v, address _to, uint256 _value, uint256 _fee, uint256 _nonce) validAddress(_to, "_to address is not valid") public {
require(!signatures[s], "this signature is burned or done before");
address from = testVerify(s, r, v, _to, _value, _fee, _nonce);
... | 0.4.26 |
/**
* check if the transferPreSigned is valid or not!?
*
* Requirement:
* - '_to' can not be zero address.
*/ | function validTransaction(bytes32 s, bytes32 r, uint8 v, address _to, uint256 _value, uint256 _fee, uint256 _nonce) validAddress(_to, "_to address is not valid") view public returns (bool, address) {
address from = testVerify(s, r, v, _to, _value, _fee, _nonce);
require(!isBlackListed[from], "from addre... | 0.4.26 |
/**
* submit the transferPreSigned
*
* Requirement:
* - '_to' can not be zero address.
* signature must be unused
*/ | function transferPreSigned(bytes32 s, bytes32 r, uint8 v, address _to, uint256 _value, uint256 _fee, uint256 _nonce) validAddress(_to, "_to address is not valid") public returns (bool){
require(signatures[s] == false, "signature has been used");
address from = testVerify(s, r, v, _to, _value, _fee, _non... | 0.4.26 |
/**
* sender(caller) vote for transfer `_from' address to '_to' address in board of directors
*
* Requirement:
* - sender(Caller) and _from` should be in the board of directors.
* - `_to` shouldn't be in the board of directors
*/ | function transferAuthority(uint256 from, address to) notInBoD(to, "_to address is already in board of directors") isAuthority(msg.sender, "you are not permitted to vote for transfer") public {
require(from < BoDAddresses.length);
if (BoDAddresses[from] == msg.sender) {
transferAuth(from, to)... | 0.4.26 |
/**
* this function is called if all of board of directors vote for the transfer `_from`->`_to'.
*/ | function transferAuth(uint256 from, address to) private {
for (uint j = 0; j < BoDAddresses.length; j++) {
transferObject.voted[BoDAddresses[j]] = false;
}
emit AuthorityTransfer(BoDAddresses[from], to);
BoDAddresses[from] = to;
transferObject.transferCounter = 0;
... | 0.4.26 |
/**
* Transfer token from sender(caller) to '_to' account
*
* Requirements:
*
* - `_to` cannot be the zero address.
* - the sender(caller) must have a balance of at least `_value`.
*/ | function transfer(address _to, uint256 _value) validAddress(_to, "_to address is not valid") smallerOrLessThan(_value, balances[msg.sender], "transfer value should be smaller than your balance") public returns (bool) {
require(!isBlackListed[msg.sender], "from address is blacklisted");
balances[msg.send... | 0.4.26 |
/**
* sender(caller) transfer '_value' token to '_to' address from '_from' address
*
* Requirements:
*
* - `_to` and `_from` cannot be the zero address.
* - `_from` must have a balance of at least `_value` .
* - the sender(caller) must have allowance for `_from`'s tokens of at least `_value`.
*/ | function transferFrom(address _from, address _to, uint256 _value) validAddress(_from, "_from address is not valid") validAddress(_to, "_to address is not valid") public returns (bool) {
require(_value<=allowances[_from][msg.sender], "_value should be smaller than your allowance");
require(_value<=balanc... | 0.4.26 |
/**
* Atomically decreases the allowance granted to `spender` by the sender(caller).
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `_spender` cannot be the zero address.
* - `_spender` must have allowance for the caller of at least `_subtractedValue`.
*/ | function decreaseApproval(address _spender, uint _subtractedValue) validAddress(_spender, "_spender is not valid address") public returns (bool) {
uint oldValue = allowances[msg.sender][_spender];
allowances[msg.sender][_spender] = _subtractedValue > oldValue ? 0 : oldValue.sub(_subtractedValue);
... | 0.4.26 |
/**
* Destroys `amount` tokens from `account`, reducing the
* total supply.
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
* - `amount` cannot be less than zero.
* - `amount` cannot be more than sender(caller)'s balance.
*/ | function burn(uint256 amount) public {
require(amount > 0, "amount cannot be less than zero");
require(amount <= balances[msg.sender], "amount to burn is more than the caller's balance");
balances[msg.sender] = balances[msg.sender].sub(amount);
totalSupply_ = totalSupply_.sub(amount);
... | 0.4.26 |
/*uint minBalanceForAccounts;
function setMinBalance(uint minimumBalanceInFinney) public onlyOwner {
minBalanceForAccounts = minimumBalanceInFinney * 1 finney;
}*/ | function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
... | 0.4.24 |
/**
* @dev Function to debit tokens
* @param _to The address that will receive the drawdown tokens.
* @param _amount The amount of tokens to debit.
* @return A boolean that indicates if the operation was successful.
*/ | function debit(
address _to,
uint256 _amount
)
public
hasDebitPermission
canDebit
returns (bool)
{
dc = COLLATERAL(collateral_contract);
uint256 rate = dc.CreditRate();
uint256 deci = 10 ** decimals;
uint256 _amount_1 = _amount / deci / rate;
uint256 _amoun... | 0.4.25 |
// IPeachProject | function canMint(uint256 quantity) public view override returns (bool) {
require(saleIsActive, "sale hasn't started");
require(!presaleIsActive, 'only presale');
require(totalSupply().add(quantity) <= MAX_TOKENS, 'quantity exceeds supply');
require(_publicMinted.add(quantity) <= maxM... | 0.8.7 |
// IPeachProjectAdmin | function mintToAddress(uint256 quantity, address to) external override onlyOwner {
require(totalSupply().add(quantity) <= MAX_TOKENS, 'quantity exceeds supply');
require(_adminMinted.add(quantity) <= maxAdminSupply, 'quantity exceeds mintable');
for (uint256 i = 0; i < quantity; i++) {
... | 0.8.7 |
// splits the amount of ETH according to a buy pressure formula, swaps the splitted fee,
// and pools the remaining ETH with NOS to create LP tokens | function purchaseLPFor(address beneficiary) public payable lock {
require(msg.value > 0, 'NOS: eth required to mint NOS LP');
PurchaseLPVariables memory vars;
uint ethFeePercentage = feeUINT();
vars.ethFee = msg.value.mul(ethFeePercentage).div(1000);
vars.netEth = msg.value.sub(v... | 0.7.1 |
// claims the oldest LP batch according to the lock period formula | function claimLP() public returns (bool) {
uint length = lockedLP[msg.sender].length;
require(length > 0, 'NOS: No locked LP.');
uint oldest = queueCounter[msg.sender];
LPbatch memory batch = lockedLP[msg.sender][oldest];
uint globalLPLockTime = _calculateLockPeriod();
r... | 0.7.1 |
//begins the public sale | function switchToPublicSale() public onlyOwner {
State saleState_ = saleState();
require(saleState_ != State.PublicSale, "Public Sale is already live!");
require(saleState_ != State.NoSale, "Cannot change to Public Sale if there has not been a Presale!");
publicSaleLaunchTi... | 0.8.7 |
// Victim actions, requires impersonation via delegatecall | function sellRewardForWeth(address, uint256 rewardAmount, address to) external override returns(uint256) {
pickle.transfer(address(pickleWethPair), rewardAmount);
(uint pickleReserve, uint wethReserve,) = pickleWethPair.getReserves();
uint amountOutput = UniswapV2Library.getAmountOut(rewardAm... | 0.6.12 |
// maps user to burned oneVBTC
// important: make sure changeInterval is a function to allow the interval of update to change | function addCollateral(address collateral_, uint256 collateralDecimal_, address oracleAddress_, bool oneCoinOracle, bool oracleHasUpdate)
external
oneLPGov
{
// only add collateral once
if (!previouslySeenCollateral[collateral_]) collateralArray.push(collateral_);
pre... | 0.6.12 |
// minimum amount of block time (seconds) required for an update in reserve ratio | function setMinimumRefreshTime(uint256 val_)
external
oneLPGov
returns (bool)
{
require(val_ != 0, "minimum refresh time must be valid");
minimumRefreshTime = val_;
// change collateral array
for (uint i = 0; i < collateralArray.length; i++){
... | 0.6.12 |
// ======================================================
// calculates how much you will need to send in order to mint oneVBTC, depending on current market prices + reserve ratio
// oneAmount: the amount of oneVBTC you want to mint
// collateral: the collateral you want to use to pay
// also works in the reverse direc... | function consultOneDeposit(uint256 oneAmount, address collateral)
public
view
returns (uint256, uint256)
{
require(oneAmount != 0, "must use valid oneAmount");
require(acceptedCollateral[collateral], "must be an accepted collateral");
uint256 stimulusUsd = ge... | 0.6.12 |
// @title: deposit collateral + stimulus token
// collateral: address of the collateral to deposit (USDC, DAI, TUSD, etc) | function mint(
uint256 oneAmount,
address collateral
)
public
payable
nonReentrant
updateProtocol()
{
require(acceptedCollateral[collateral], "must be an accepted collateral");
require(oneAmount != 0, "must mint non-zero amount");
... | 0.6.12 |
/// burns stablecoin and increments _burnedStablecoin mapping for user
/// user can claim collateral in a 2nd step below | function withdraw(
uint256 oneAmount,
address collateral
)
public
nonReentrant
updateProtocol()
{
require(oneAmount != 0, "must withdraw non-zero amount");
require(oneAmount <= _oneBalances[msg.sender], "insufficient balance");
require(pr... | 0.6.12 |
/// @notice If you are interested, I would recommend reading: https://slowmist.medium.com/
/// also https://cryptobriefing.com/50-million-lost-the-top-19-defi-cryptocurrency-hacks-2020/ | function withdrawFinal(address collateral, uint256 amount)
public
nonReentrant
updateProtocol()
{
require(previouslySeenCollateral[collateral], "must be an existing collateral");
require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, "action too soon - please wait... | 0.6.12 |
// can execute any abstract transaction on this smart contrat
// target: address / smart contract you are interracting with
// value: msg.value (amount of eth in WEI you are sending. Most of the time it is 0)
// signature: the function signature (name of the function and the types of the arguments).
// for e... | function executeTransaction(address target, uint value, string memory signature, bytes memory data) public payable oneLPGov returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(byt... | 0.6.12 |
/**
* @notice The airdrop function which will be permanently disabled once all tokens have been airdropped.
*
*/ | function airdrop(address[] memory _to, uint256[][] memory _tokenIds) public onlyOwner {
require(!airdropPermanentlyDisabled, "Once the airdrop is disabled, the function can never be called again.");
for (uint i = 0; i < _to.length; i++) {
for (uint z = 0; z < _tokenIds[i].length; z++) {
... | 0.8.7 |
/**
* @notice Generate the SVG of any Distortion piece, including token IDs that are out of bounds.
*
*/ | function generateDistortion(uint256 tokenId) public view returns (string memory) {
string memory output;
output = string(abi.encodePacked(
'<svg width="750px" height="750px" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="ba... | 0.8.7 |
/**
* @notice
*
*/ | function tokenURI(uint256 tokenId) override public view returns (string memory) {
require(_exists(tokenId), "Token doesn't exist. Try using the generateDistortion function to generate non-existant pieces.");
string memory ringCount = generateNum("ringCount", tokenId, hashOfBlock, 5, 15);
string... | 0.8.7 |
// ERC20 TransferFrom function | function transferFrom(address from, address to, uint value) public override returns (bool success) {
require(value <= allowance[from][msg.sender], 'Must not send more than allowance');
allowance[from][msg.sender] -= value;
_transfer(from, to, value);
return true;
} | 0.6.4 |
//======================================EMISSION========================================//
// Internal - Update emission function | function emittingAmount() internal returns(uint){
if(now >= nextEpochTime){
currentEpoch += 1;
if(currentEpoch > 10){
emission = BPE;
BPE -= emission.div(2);
balanceOf[address(this)] -= ... | 0.6.4 |
/** @dev initializes the farming contract.
* @param extension extension address.
* @param extensionInitData lm extension init payload.
* @param orchestrator address of the eth item orchestrator.
* @param rewardTokenAddress address of the reward token.
* @return extensionReturnCall result of the extension init... | function init(address extension, bytes memory extensionInitData, address orchestrator, address rewardTokenAddress, bytes memory farmingSetupInfosBytes) public returns(bytes memory extensionReturnCall) {
require(_factory == address(0), "Already initialized");
require((_extension = extension) != address... | 0.7.6 |
/** @dev updates the free setup with the given index.
* @param setupIndex index of the setup that we're updating.
* @param amount amount of liquidity that we're adding/removeing.
* @param positionId position id.
* @param fromExit if it's from an exit or not.
*/ | function _updateFreeSetup(uint256 setupIndex, uint256 amount, uint256 positionId, bool fromExit) private {
uint256 currentBlock = block.number < _setups[setupIndex].endBlock ? block.number : _setups[setupIndex].endBlock;
if (_setups[setupIndex].totalSupply != 0) {
uint256 lastUpdateBlock ... | 0.7.6 |
/** @dev mints a new FarmToken inside the collection for the given position.
* @param uniqueOwner farming position owner.
* @param amount amount of to mint for a farm token.
* @param setupIndex index of the setup.
* @return objectId new farm token object id.
*/ | function _mintFarmTokenAmount(address uniqueOwner, uint256 amount, uint256 setupIndex) private returns(uint256 objectId) {
if (_setups[setupIndex].objectId == 0) {
(objectId,) = INativeV1(_farmTokenCollection).mint(amount, string(abi.encodePacked("Farming LP ", _toString(_setupsInfo[_setups[setupI... | 0.7.6 |
/** @dev burns a farm token from the collection.
* @param objectId object id where to burn liquidity.
* @param amount amount of liquidity to burn.
*/ | function _burnFarmTokenAmount(uint256 objectId, uint256 amount) private {
INativeV1 tokenCollection = INativeV1(_farmTokenCollection);
// transfer the farm token to this contract
tokenCollection.safeTransferFrom(msg.sender, address(this), objectId, amount, "");
// burn the farm token... | 0.7.6 |
/** @dev calls the contract at the given location using the given payload and returns the returnData.
* @param location location to call.
* @param payload call payload.
* @return returnData call return data.
*/ | function _call(address location, bytes memory payload) private returns(bytes memory returnData) {
assembly {
let result := call(gas(), location, 0, add(payload, 0x20), mload(payload), 0, 0)
let size := returndatasize()
returnData := mload(0x40)
mstore(returnD... | 0.7.6 |
/** @dev returns the input address to string.
* @param _addr address to convert as string.
* @return address as string.
*/ | function _toString(address _addr) internal pure returns(string memory) {
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = '0';
str[1] = 'x';
for (uint i = 0; i < 20; i++) {
... | 0.7.6 |
/** @dev ensures the transfer from the contract to the extension.
* @param amount amount to transfer.
*/ | function _ensureTransfer(uint256 amount) private returns(bool) {
uint256 initialBalance = _rewardTokenAddress == address(0) ? address(this).balance : IERC20(_rewardTokenAddress).balanceOf(address(this));
uint256 expectedBalance = initialBalance + amount;
try IFarmExtension(_extension).transfe... | 0.7.6 |
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (). | function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _tsupply = totalSupply();
uint256 newSupply = _tsupply.add(_amount);
require(newSupply <= _maxSupply, "mint amount must not exeed maxSupply");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[... | 0.6.12 |
// TODO mapping(address => mapping (uint256 => bool)) usedApprovalMessages;
// TODO remove as we can use erc1155 totkensReceived hook | function setApprovalForAllAndCall(address _target, bytes memory _data) public payable returns(bytes memory){
require(BytesUtil.doFirstParamEqualsAddress(_data, msg.sender), "first param != sender");
_setApprovalForAllFrom(msg.sender, _target, true);
(bool success, bytes memory returnData) = _tar... | 0.5.2 |
// TODO 2 signatures one for approve and one for call ? | function approveAllAndCallViaSignedMessage(address _target, uint256 _nonce, bytes calldata _data, bytes calldata signature) external payable returns(bytes memory){
address signer; // TODO ecrecover(hash, v, r, s);
require(BytesUtil.doFirstParamEqualsAddress(_data, signer), "first param != signer");
... | 0.5.2 |
// --- Dependency setter --- | function setAddresses(
address _borrowerOperationsAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _lusdTokenAddres... | 0.6.11 |
// --- Inner single liquidation functions ---
// Liquidate one trove, in Normal Mode. | function _liquidateNormalMode(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _borrower,
uint _LUSDInStabPool
)
internal
returns (LiquidationValues memory singleLiquidation)
{
LocalVariables_InnerSingleLiquidateFunction memory vars;
(... | 0.6.11 |
/* In a full liquidation, returns the values for a trove's coll and debt to be offset, and coll and debt to be
* redistributed to active troves.
*/ | function _getOffsetAndRedistributionVals
(
uint _debt,
uint _coll,
uint _LUSDInStabPool
)
internal
pure
returns (uint debtToOffset, uint collToSendToSP, uint debtToRedistribute, uint collToRedistribute)
{
if (_LUSDInStabPool > 0) {
/*
*... | 0.6.11 |
/*
* Get its offset coll/debt and ETH gas comp, and close the trove.
*/ | function _getCappedOffsetVals
(
uint _entireTroveDebt,
uint _entireTroveColl,
uint _price,
uint _gasCompensation
)
internal
pure
returns (LiquidationValues memory singleLiquidation)
{
singleLiquidation.entireTroveDebt = _entireTroveDebt;
... | 0.6.11 |
/*
* Liquidate a sequence of troves. Closes a maximum number of n under-collateralized Troves,
* starting from the one with the lowest collateral ratio in the system, and moving upwards
*/ | function liquidateTroves(uint _n) external override {
ContractsCache memory contractsCache = ContractsCache(
activePool,
defaultPool,
ILUSDToken(address(0)),
ILQTYStaking(address(0)),
sortedTroves,
ICollSurplusPool(address(0)),
... | 0.6.11 |
/*
* Attempt to liquidate a custom list of troves provided by the caller.
*/ | function batchLiquidateTroves(address[] memory _troveArray) public override {
require(_troveArray.length != 0, "TroveManager: Calldata address array must not be empty");
IActivePool activePoolCached = activePool;
IDefaultPool defaultPoolCached = defaultPool;
IStabilityPool stabilityPool... | 0.6.11 |
// --- Liquidation helper functions --- | function _addLiquidationValuesToTotals(LiquidationTotals memory oldTotals, LiquidationValues memory singleLiquidation)
internal pure returns(LiquidationTotals memory newTotals) {
// Tally all the values with their respective running totals
newTotals.totalCollGasCompensation = oldTotals.totalCollGas... | 0.6.11 |
/*
* Called when a full redemption occurs, and closes the trove.
* The redeemer swaps (debt - liquidation reserve) LUSD for (debt - liquidation reserve) worth of ETH, so the LUSD liquidation reserve left corresponds to the remaining debt.
* In order to close the trove, the LUSD liquidation reserve is burned, and the... | function _redeemCloseTrove(ContractsCache memory _contractsCache, address _borrower, uint _LUSD, uint _ETH) internal {
_contractsCache.lusdToken.burn(gasPoolAddress, _LUSD);
// Update Active Pool LUSD, and send ETH to account
_contractsCache.activePool.decreaseLUSDDebt(_LUSD);
// send E... | 0.6.11 |
// Add the borrowers's coll and debt rewards earned from redistributions, to their Trove | function _applyPendingRewards(IActivePool _activePool, IDefaultPool _defaultPool, address _borrower) internal {
if (hasPendingRewards(_borrower)) {
_requireTroveIsActive(_borrower);
// Compute pending rewards
uint pendingETHReward = getPendingETHReward(_borrower);
... | 0.6.11 |
// Get the borrower's pending accumulated ETH reward, earned by their stake | function getPendingETHReward(address _borrower) public view override returns (uint) {
uint snapshotETH = rewardSnapshots[_borrower].ETH;
uint rewardPerUnitStaked = L_ETH.sub(snapshotETH);
if ( rewardPerUnitStaked == 0 || Troves[_borrower].status != Status.active) { return 0; }
uint sta... | 0.6.11 |
// Get the borrower's pending accumulated LUSD reward, earned by their stake | function getPendingLUSDDebtReward(address _borrower) public view override returns (uint) {
uint snapshotLUSDDebt = rewardSnapshots[_borrower].LUSDDebt;
uint rewardPerUnitStaked = L_LUSDDebt.sub(snapshotLUSDDebt);
if ( rewardPerUnitStaked == 0 || Troves[_borrower].status != Status.active) { retu... | 0.6.11 |
// Return the Troves entire debt and coll, including pending rewards from redistributions. | function getEntireDebtAndColl(
address _borrower
)
public
view
override
returns (uint debt, uint coll, uint pendingLUSDDebtReward, uint pendingETHReward)
{
debt = Troves[_borrower].debt;
coll = Troves[_borrower].coll;
pendingLUSDDebtReward = getPe... | 0.6.11 |
// Calculate a new stake based on the snapshots of the totalStakes and totalCollateral taken at the last liquidation | function _computeNewStake(uint _coll) internal view returns (uint) {
uint stake;
if (totalCollateralSnapshot == 0) {
stake = _coll;
} else {
/*
* The following assert() holds true because:
* - The system always contains >= 1 trove
* - W... | 0.6.11 |
/*
* Remove a Trove owner from the TroveOwners array, not preserving array order. Removing owner 'B' does the following:
* [A B C D E] => [A E C D], and updates E's Trove struct to point to its new array index.
*/ | function _removeTroveOwner(address _borrower, uint TroveOwnersArrayLength) internal {
Status troveStatus = Troves[_borrower].status;
// It’s set in caller function `_closeTrove`
assert(troveStatus != Status.nonExistent && troveStatus != Status.active);
uint128 index = Troves[_borrower].... | 0.6.11 |
/*
* This function has two impacts on the baseRate state variable:
* 1) decays the baseRate based on time passed since last redemption or LUSD borrowing operation.
* then,
* 2) increases the baseRate based on the amount redeemed, as a proportion of total supply
*/ | function _updateBaseRateFromRedemption(uint _ETHDrawn, uint _price, uint _totalLUSDSupply) internal returns (uint) {
uint decayedBaseRate = _calcDecayedBaseRate();
/* Convert the drawn ETH back to LUSD at face value rate (1 LUSD:1 USD), in order to get
* the fraction of total supply that was r... | 0.6.11 |
/**
@notice find the integer part of log2(p/q)
=> find largest x s.t p >= q * 2^x
=> find largest x s.t 2^x <= p / q
*/ | function log2Int(uint256 _p, uint256 _q) internal pure returns (uint256) {
uint256 res = 0;
uint256 remain = _p / _q;
while (remain > 0) {
res++;
remain /= 2;
}
return res - 1;
} | 0.7.6 |
/**
@notice log2 for a number that it in [1,2)
@dev _x is FP, return a FP
@dev function is from Kyber. Long modified the condition to be (_x >= one) && (_x < two)
to avoid the case where x = 2 may lead to incorrect result
*/ | function log2ForSmallNumber(uint256 _x) internal pure returns (uint256) {
uint256 res = 0;
uint256 one = (uint256(1) << PRECISION_BITS);
uint256 two = 2 * one;
uint256 addition = one;
require((_x >= one) && (_x < two), "MATH_ERROR");
require(PRECISION_BITS < 125, "MATH_E... | 0.7.6 |
/**
@notice log2 of (p/q). returns result in FP form
@dev function is from Kyber.
@dev _p & _q is FP, return a FP
*/ | function logBase2(uint256 _p, uint256 _q) internal pure returns (uint256) {
uint256 n = 0;
if (_p > _q) {
n = log2Int(_p, _q);
}
require(n * RONE <= BIG_NUMBER, "MATH_ERROR");
require(!checkMultOverflow(_p, RONE), "MATH_ERROR");
require(!checkMultOverflow(n,... | 0.7.6 |
/**
@notice calculate ln(p/q). returned result >= 0
@dev function is from Kyber.
@dev _p & _q is FP, return a FP
*/ | function ln(uint256 p, uint256 q) internal pure returns (uint256) {
uint256 ln2Numerator = 6931471805599453094172;
uint256 ln2Denomerator = 10000000000000000000000;
uint256 log2x = logBase2(p, q);
require(!checkMultOverflow(ln2Numerator, log2x), "MATH_ERROR");
return (ln2Numer... | 0.7.6 |
/**
@notice return e^exp in FP form
@dev estimation by formula at http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html
the function is based on exp function of:
https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol
@dev the function is expected to converge quite fast, after a... | function rpowe(uint256 exp) internal pure returns (uint256) {
uint256 res = 0;
uint256 curTerm = RONE;
for (uint256 n = 0; ; n++) {
res += curTerm;
curTerm = rmul(curTerm, rdiv(exp, toFP(n + 1)));
if (curTerm == 0) {
break;
}
... | 0.7.6 |
/**
@notice return base^exp with base in FP form and exp in Int
@dev this function use a technique called: exponentiating by squaring
complexity O(log(q))
@dev function is from Kyber.
@dev base is a FP, exp is an Int, return a FP
*/ | function rpowi(uint256 base, uint256 exp) internal pure returns (uint256) {
uint256 res = exp % 2 != 0 ? base : RONE;
for (exp /= 2; exp != 0; exp /= 2) {
base = rmul(base, base);
if (exp % 2 != 0) {
res = rmul(res, base);
}
}
return ... | 0.7.6 |
/**
@dev y is an Int, returns an Int
@dev babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
@dev from Uniswap
*/ | function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
} | 0.7.6 |
/**
* @dev update the balance of a type provided in _binBalances
* @param _binBalances Uint256 containing the balances of objects
* @param _index Index of the object in the provided bin
* @param _amount Value to update the type balance
* @param _operation Which operation to conduct :
* Operations.REPLACE : Re... | function updateTokenBalance(
uint256 _binBalances,
uint256 _index,
uint256 _amount,
Operations _operation) internal pure returns (uint256 newBinBalance)
{
uint256 objectBalance = 0;
if (_operation == Operations.ADD) {
objectBalance = getValueInBin(_binBalances, _index);
newBinB... | 0.5.2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.