comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
/// @dev Internal function to check if a delegate has the permission to call a given contract function
/// @param delegate the delegate to be checked
/// @param to the target contract
/// @param selector the function selector of the contract function to be called
/// @return true|false
|
function _hasPermission(
address delegate,
address to,
bytes4 selector
) internal view returns (bool) {
bytes32[] memory roles = getRolesByDelegate(delegate);
EnumerableSet.Bytes32Set storage funcRoles = funcToRoles[to][selector];
for (uint256 index = 0; index < roles.length; index++) {
if (funcRoles.contains(roles[index])) {
return true;
}
}
return false;
}
|
0.7.6
|
/// @notice Associate a role with given contract funcs
/// @dev only owners are allowed to call this function, the given role has
/// to be predefined. On success, the role will be associated with the
/// given contract function, `AssocContractFuncs` event will be fired.
/// @param role the role to be associated
/// @param _contract the contract address to be associated with the role
/// @param funcList the list of contract functions to be associated with the role
|
function assocRoleWithContractFuncs(
bytes32 role,
address _contract,
string[] calldata funcList
) external onlyOwner roleDefined(role) {
require(funcList.length > 0, "empty funcList");
for (uint256 index = 0; index < funcList.length; index++) {
bytes4 funcSelector = bytes4(keccak256(bytes(funcList[index])));
bytes32 funcSelector32 = bytes32(funcSelector);
funcToRoles[_contract][funcSelector32].add(role);
contractToFuncs[_contract].add(funcSelector32);
}
contractSet.add(_contract);
emit AssocContractFuncs(role, _contract, funcList, _msgSender());
}
|
0.7.6
|
/// @notice Dissociate a role from given contract funcs
/// @dev only owners are allowed to call this function, the given role has
/// to be predefined. On success, the role will be disassociated from
/// the given contract function, `DissocContractFuncs` event will be
/// fired.
/// @param role the role to be disassociated
/// @param _contract the contract address to be disassociated from the role
/// @param funcList the list of contract functions to be disassociated from the role
|
function dissocRoleFromContractFuncs(
bytes32 role,
address _contract,
string[] calldata funcList
) external onlyOwner roleDefined(role) {
require(funcList.length > 0, "empty funcList");
for (uint256 index = 0; index < funcList.length; index++) {
bytes4 funcSelector = bytes4(keccak256(bytes(funcList[index])));
bytes32 funcSelector32 = bytes32(funcSelector);
funcToRoles[_contract][funcSelector32].remove(role);
if (funcToRoles[_contract][funcSelector32].length() <= 0) {
contractToFuncs[_contract].remove(funcSelector32);
}
}
if (contractToFuncs[_contract].length() <= 0) {
contractSet.remove(_contract);
}
emit DissocContractFuncs(role, _contract, funcList, _msgSender());
}
|
0.7.6
|
/**
@dev everyone can buy
@param qty - the quantity that a user wants to buy
*/
|
function publicBuy(uint256 id, uint256 qty) external payable nonReentrant {
require(prices[id] != 0, "not live");
require(prices[id] * qty == msg.value, "exact amount needed");
require(qty <= 5, "max 5 at once");
require(totalSupply(id) + qty <= maxSupplies[id], "out of stock");
require(block.timestamp >= publicStartTime, "not live");
_mint(msg.sender, id, qty, "");
}
|
0.8.13
|
// Operation for multiplication
|
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
|
0.5.2
|
// ERC20 Transfer function
|
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
require(balanceOf[msg.sender] >= _value);
require(balanceOf[_to].add(_value) >= balanceOf[_to]);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
|
0.5.2
|
// ERC20 Transfer from wallet
|
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_from != address(0) && _to != address(0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to].add(_value) >= balanceOf[_to]);
require(allowance[_from][msg.sender] >= _value);
balanceOf[_to] = balanceOf[_to].add(_value);
balanceOf[_from] = balanceOf[_from].sub(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
|
0.5.2
|
// Approve to allow tranfer tokens
|
function approve(address _spender, uint256 _value) public returns (bool success) {
require(_spender != address(0));
require(_value <= balanceOf[msg.sender]);
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
|
0.5.2
|
/**
* @dev Presale mint
*/
|
function presaleMint(bytes32[] calldata _merkleProof, uint16 _mintAmount)
external
payable
onlyAllowValidCountAndActiveSale(_mintAmount)
{
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(
MerkleProof.verify(_merkleProof, merkleRoot, leaf),
"Not on the list"
);
require(costPresale.mul(_mintAmount) == msg.value, "Wrong amount");
require(!publicSaleEnabled && presaleEnabled, "Presale closed");
require(
addressMints[_msgSender()] + _mintAmount <=
maxTokensPerWalletPresale,
"Exceeds max"
);
_mintNFT(_msgSender(), _mintAmount);
}
|
0.8.9
|
/**
* @dev Returns list of token ids owned by address
*/
|
function walletOfOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
uint256 k = 0;
for (uint256 i = 1; i <= totalTokens; i++) {
if (_exists(i) && _owner == ownerOf(i)) {
tokenIds[k] = i;
k++;
}
}
delete k;
return tokenIds;
}
|
0.8.9
|
/**
* @dev Returns the URI to the tokens metadata
*/
|
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return _notRevealedURI;
}
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(
baseURI,
tokenId.toString(),
_baseExtension
)
)
: "";
}
|
0.8.9
|
/**
* @dev Burn tokens in mutiples of 5
*/
|
function burn(uint256[] memory _tokenIds) external {
require(burnEnabled, "Burn disabled");
require(_tokenIds.length % 5 == 0, "Multiples of 5");
for (uint256 i = 0; i < _tokenIds.length; i++) {
require(
_isApprovedOrOwner(_msgSender(), _tokenIds[i]),
"ERC721Burnable: caller is not owner nor approved"
);
}
require(
totalBurned() + _tokenIds.length <= totalBurnTokens,
"Exceeds burn limit"
);
for (uint256 i = 0; i < _tokenIds.length; i++) {
_burn(_tokenIds[i]);
_totalBurnSupply++;
addressBurns[_msgSender()] += 1;
}
}
|
0.8.9
|
/**
* @dev Get information for a handler
* @param handlerID Handler ID
* @return (success or failure, handler address, handler name)
*/
|
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory)
{
bool support;
address tokenHandlerAddr;
string memory tokenName;
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);
IProxy TokenHandler = IProxy(tokenHandlerAddr);
bytes memory data;
(, data) = TokenHandler.handlerViewProxy(
abi.encodeWithSelector(
IMarketHandler
.getTokenName.selector
)
);
tokenName = abi.decode(data, (string));
support = true;
}
return (support, tokenHandlerAddr, tokenName);
}
|
0.6.12
|
/**
* @dev Register a handler
* @param handlerID Handler ID and address
* @param tokenHandlerAddr The handler address
* @return result the setter call in contextSetter contract
*/
|
function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) onlyOwner external returns (bool result) {
bytes memory callData = abi.encodeWithSelector(
IManagerSlotSetter
.handlerRegister.selector,
handlerID, tokenHandlerAddr, flashFeeRate, discountBase
);
(result, ) = slotSetterAddr.delegatecall(callData);
assert(result);
}
|
0.6.12
|
/**
* @dev Update the (SI) rewards for a user
* @param userAddr The address of the user
* @param callerID The handler ID
* @return true (TODO: validate results)
*/
|
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool)
{
ContractInfo memory handlerInfo;
(handlerInfo.support, handlerInfo.addr) = dataStorageInstance.getTokenHandlerInfo(callerID);
if (handlerInfo.support)
{
IProxy TokenHandler;
TokenHandler = IProxy(handlerInfo.addr);
TokenHandler.siProxy(
abi.encodeWithSelector(
IServiceIncentive
.updateRewardLane.selector,
userAddr
)
);
}
return true;
}
|
0.6.12
|
/**
* @dev Update interest of a user for a handler (internal)
* @param userAddr The user address
* @param callerID The handler ID
* @param allFlag Flag for the full calculation mode (calculting for all handlers)
* @return (uint256, uint256, uint256, uint256, uint256, uint256)
*/
|
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256) {
bytes memory callData = abi.encodeWithSelector(
IHandlerManager
.applyInterestHandlers.selector,
userAddr, callerID, allFlag
);
(bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (uint256, uint256, uint256, uint256, uint256, uint256));
}
|
0.6.12
|
/**
* @dev Claim handler rewards for the user
* @param handlerID The ID of claim reward handler
* @param userAddr The user address
* @return true (TODO: validate results)
*/
|
function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256) {
bytes memory callData = abi.encodeWithSelector(
IHandlerManager
.claimHandlerReward.selector,
handlerID, userAddr
);
(bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (uint256));
}
|
0.6.12
|
/**
* @dev Get the borrow and margin call limits of the user for all handlers
* @param userAddr The address of the user
* @return userTotalBorrowLimitAsset the sum of borrow limit for all handlers
* @return userTotalMarginCallLimitAsset the sume of margin call limit for handlers
*/
|
function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256)
{
uint256 userTotalBorrowLimitAsset;
uint256 userTotalMarginCallLimitAsset;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID);
uint256 marginCallLimit = _getTokenHandlerMarginCallLimit(handlerID);
uint256 userBorrowLimitAsset = depositHandlerAsset.unifiedMul(borrowLimit);
uint256 userMarginCallLimitAsset = depositHandlerAsset.unifiedMul(marginCallLimit);
userTotalBorrowLimitAsset = userTotalBorrowLimitAsset.add(userBorrowLimitAsset);
userTotalMarginCallLimitAsset = userTotalMarginCallLimitAsset.add(userMarginCallLimitAsset);
}
else
{
continue;
}
}
return (userTotalBorrowLimitAsset, userTotalMarginCallLimitAsset);
}
|
0.6.12
|
/**
* @dev Get the maximum allowed amount to borrow of the user from the given handler
* @param userAddr The address of the user
* @param callerID The target handler to borrow
* @return extraCollateralAmount The maximum allowed amount to borrow from
the handler.
*/
|
function getUserCollateralizableAmount(address payable userAddr, uint256 callerID) external view returns (uint256)
{
uint256 userTotalBorrowAsset;
uint256 depositAssetBorrowLimitSum;
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
userTotalBorrowAsset = userTotalBorrowAsset.add(borrowHandlerAsset);
depositAssetBorrowLimitSum = depositAssetBorrowLimitSum
.add(
depositHandlerAsset
.unifiedMul( _getTokenHandlerBorrowLimit(handlerID) )
);
}
}
if (depositAssetBorrowLimitSum > userTotalBorrowAsset)
{
return depositAssetBorrowLimitSum
.sub(userTotalBorrowAsset)
.unifiedDiv( _getTokenHandlerBorrowLimit(callerID) )
.unifiedDiv( _getTokenHandlerPrice(callerID) );
}
return 0;
}
|
0.6.12
|
/**
* @dev Partial liquidation for a user
* @param delinquentBorrower The address of the liquidation target
* @param liquidateAmount The amount to liquidate
* @param liquidator The address of the liquidator (liquidation operator)
* @param liquidateHandlerID The hander ID of the liquidating asset
* @param rewardHandlerID The handler ID of the reward token for the liquidator
* @return (uint256, uint256, uint256)
*/
|
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) onlyLiquidationManager external returns (uint256, uint256, uint256)
{
address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(liquidateHandlerID);
IProxy TokenHandler = IProxy(tokenHandlerAddr);
bytes memory data;
data = abi.encodeWithSelector(
IMarketHandler
.partialLiquidationUser.selector,
delinquentBorrower,
liquidateAmount,
liquidator,
rewardHandlerID
);
(, data) = TokenHandler.handlerProxy(data);
return abi.decode(data, (uint256, uint256, uint256));
}
|
0.6.12
|
/**
* @dev Get the maximum liquidation reward by checking sufficient reward
amount for the liquidator.
* @param delinquentBorrower The address of the liquidation target
* @param liquidateHandlerID The hander ID of the liquidating asset
* @param liquidateAmount The amount to liquidate
* @param rewardHandlerID The handler ID of the reward token for the liquidator
* @param rewardRatio delinquentBorrowAsset / delinquentDepositAsset
* @return The maximum reward token amount for the liquidator
*/
|
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256)
{
uint256 liquidatePrice = _getTokenHandlerPrice(liquidateHandlerID);
uint256 rewardPrice = _getTokenHandlerPrice(rewardHandlerID);
uint256 delinquentBorrowerRewardDeposit;
(delinquentBorrowerRewardDeposit, ) = _getHandlerAmount(delinquentBorrower, rewardHandlerID);
uint256 rewardAsset = delinquentBorrowerRewardDeposit.unifiedMul(rewardPrice).unifiedMul(rewardRatio);
if (liquidateAmount.unifiedMul(liquidatePrice) > rewardAsset)
{
return rewardAsset.unifiedDiv(liquidatePrice);
}
else
{
return liquidateAmount;
}
}
|
0.6.12
|
/**
* @dev Reward the liquidator
* @param delinquentBorrower The address of the liquidation target
* @param rewardAmount The amount of reward token
* @param liquidator The address of the liquidator (liquidation operator)
* @param handlerID The handler ID of the reward token for the liquidator
* @return The amount of reward token
*/
|
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external returns (uint256)
{
address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);
IProxy TokenHandler = IProxy(tokenHandlerAddr);
bytes memory data;
data = abi.encodeWithSelector(
IMarketHandler
.partialLiquidationUserReward.selector,
delinquentBorrower,
rewardAmount,
liquidator
);
(, data) = TokenHandler.handlerProxy(data);
return abi.decode(data, (uint256));
}
|
0.6.12
|
/**
* @dev Execute flashloan contract with delegatecall
* @param handlerID The ID of the token handler to borrow.
* @param receiverAddress The address of receive callback contract
* @param amount The amount of borrow through flashloan
* @param params The encode metadata of user
* @return Whether or not succeed
*/
|
function flashloan(
uint256 handlerID,
address receiverAddress,
uint256 amount,
bytes calldata params
) external returns (bool) {
bytes memory callData = abi.encodeWithSelector(
IManagerFlashloan
.flashloan.selector,
handlerID, receiverAddress, amount, params
);
(bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (bool));
}
|
0.6.12
|
/**
* @dev Withdraw accumulated flashloan fee with delegatecall
* @param handlerID The ID of handler with accumulated flashloan fee
* @return Whether or not succeed
*/
|
function withdrawFlashloanFee(
uint256 handlerID
) external onlyOwner returns (bool) {
bytes memory callData = abi.encodeWithSelector(
IManagerFlashloan
.withdrawFlashloanFee.selector,
handlerID
);
(bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (bool));
}
|
0.6.12
|
/**
* @dev Get flashloan fee for flashloan amount before make product(BiFi-X)
* @param handlerID The ID of handler with accumulated flashloan fee
* @param amount The amount of flashloan amount
* @param bifiAmount The amount of Bifi amount
* @return The amount of fee for flashloan amount
*/
|
function getFeeFromArguments(
uint256 handlerID,
uint256 amount,
uint256 bifiAmount
) external returns (uint256) {
bytes memory callData = abi.encodeWithSelector(
IManagerFlashloan
.getFeeFromArguments.selector,
handlerID, amount, bifiAmount
);
(bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);
assert(result);
return abi.decode(returnData, (uint256));
}
|
0.6.12
|
/**
* @dev Get the deposit and borrow amount of the user for the handler (internal)
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The deposit and borrow amount
*/
|
function _getHandlerAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256)
{
IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID));
bytes memory data;
(, data) = TokenHandler.handlerViewProxy(
abi.encodeWithSelector(
IMarketHandler
.getUserAmount.selector,
userAddr
)
);
return abi.decode(data, (uint256, uint256));
}
|
0.6.12
|
/**
* @dev Calculates the fee and takes it, transfers the fee to the charity
* address and the remains to this contract.
* emits feeTaken()
* Then, it checks if there is enough approved for the swap, if not it
* approves it to the uniswap contract. Emits approvedForTrade if so.
* @param user: The payer
* @param token: The token that will be swapped and the fee will be paid
* in
* @param totalAmount: The total amount of tokens that will be swapped, will
* be used to calculate how much the fee will be
*/
|
function takeFeeAndApprove(address user, IERC20 token, uint256 totalAmount) internal returns (uint256){
uint256 _feeTaken = (totalAmount / 10000) * _charityFee;
token.transferFrom(user, address(this), totalAmount - _feeTaken);
token.transferFrom(user, _charityAddress, _feeTaken);
if (token.allowance(address(this), address(_uniswapV2Router)) < totalAmount){
token.approve(address(_uniswapV2Router), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
emit approvedForTrade(token);
}
emit feeTaken(user, token, _feeTaken);
return totalAmount -= _feeTaken;
}
|
0.8.4
|
/**
* @dev Get the deposit and borrow amount of the user with interest added
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The deposit and borrow amount of the user with interest
*/
|
function _getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256)
{
uint256 price = _getTokenHandlerPrice(handlerID);
IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID));
uint256 depositAmount;
uint256 borrowAmount;
bytes memory data;
(, data) = TokenHandler.handlerViewProxy(
abi.encodeWithSelector(
IMarketHandler.getUserAmountWithInterest.selector,
userAddr
)
);
(depositAmount, borrowAmount) = abi.decode(data, (uint256, uint256));
uint256 depositAsset = depositAmount.unifiedMul(price);
uint256 borrowAsset = borrowAmount.unifiedMul(price);
return (depositAsset, borrowAsset);
}
|
0.6.12
|
/**
* @dev Get the depositTotalCredit and borrowTotalCredit
* @param userAddr The address of the user
* @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit)
* @return borrowTotalCredit The sum of borrow amount for all handlers
*/
|
function _getUserTotalIntraCreditAsset(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalCredit;
uint256 borrowTotalCredit;
for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)
{
if (dataStorageInstance.getTokenHandlerSupport(handlerID))
{
uint256 depositHandlerAsset;
uint256 borrowHandlerAsset;
(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);
uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID);
uint256 depositHandlerCredit = depositHandlerAsset.unifiedMul(borrowLimit);
depositTotalCredit = depositTotalCredit.add(depositHandlerCredit);
borrowTotalCredit = borrowTotalCredit.add(borrowHandlerAsset);
}
else
{
continue;
}
}
return (depositTotalCredit, borrowTotalCredit);
}
|
0.6.12
|
/**
* @dev Get the amount of token that the user can borrow more
* @param userAddr The address of user
* @param handlerID The handler ID
* @return The amount of token that user can borrow more
*/
|
function _getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256) {
uint256 depositCredit;
uint256 borrowCredit;
(depositCredit, borrowCredit) = _getUserTotalIntraCreditAsset(userAddr);
if (depositCredit == 0)
{
return 0;
}
if (depositCredit > borrowCredit)
{
return depositCredit.sub(borrowCredit).unifiedDiv(_getTokenHandlerPrice(handlerID));
}
else
{
return 0;
}
}
|
0.6.12
|
/**
* @dev The functions below are all the same as the Uniswap contract but
* they call takeFeeAndApprove() or takeFeeETH() (See the functions above)
* and deduct the fee from the amount that will be traded.
*/
|
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external override returns (uint[] memory amounts){
uint256 newAmount = takeFeeAndApprove(_msgSender(), IERC20(path[0]), amountIn);
return _uniswapV2Router.swapExactTokensForTokens(newAmount, amountOutMin, path, to,deadline);
}
|
0.8.4
|
/**
* @dev Same as Uniswap
*/
|
function quote(uint amountA, uint reserveA, uint reserveB) external override pure returns (uint amountB){
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = (amountA * reserveB) / reserveA;
}
|
0.8.4
|
/**
* @dev To mint OAP Tokens
* @param _receiver Reciever address
* @param _amount Amount to mint
* @param _mrs _mrs[0] - message hash _mrs[1] - r of signature _mrs[2] - s of signature
* @param _v v of signature
*/
|
function mint(address _receiver, uint256 _amount,bytes32[3] memory _mrs, uint8 _v) public returns (bool) {
require(_receiver != address(0), "Invalid address");
require(_amount >= 0, "Invalid amount");
require(hashConfirmation[_mrs[0]] != true, "Hash exists");
require(msg.sender == ethermaxxAddress,"only From ETHERMAXX");
require(ecrecover(_mrs[0], _v, _mrs[1], _mrs[2]) == sigAddress, "Invalid Signature");
totalSupply = totalSupply.add(_amount);
balances[_receiver] = balances[_receiver].add(_amount);
hashConfirmation[_mrs[0]] = true;
emit Transfer(address(0), _receiver, _amount);
return true;
}
|
0.5.16
|
/**
* @dev To mint OAP Tokens
* @param _receiver Reciever address
* @param _amount Amount to mint
*/
|
function ownerMint(address _receiver, uint256 _amount) public onlyOwner returns (bool) {
require(_receiver != address(0), "Invalid address");
require(_amount >= 0, "Invalid amount");
totalSupply = totalSupply.add(_amount);
balances[_receiver] = balances[_receiver].add(_amount);
emit Transfer(address(0), _receiver, _amount);
return true;
}
|
0.5.16
|
/**
* @notice executes before each token transfer or mint
* @param _from address
* @param _to address
* @param _amount value to transfer
* @dev See {ERC20-_beforeTokenTransfer}.
* @dev minted tokens must not cause the total supply to go over the cap.
* @dev Reverts if the to address is equal to token address
*/
|
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _amount);
require(
_to != address(this),
"TCAP::transfer: can't transfer to TCAP contract"
);
if (_from == address(0) && capEnabled) {
// When minting tokens
require(
totalSupply().add(_amount) <= cap,
"TCAP::Transfer: TCAP cap exceeded"
);
}
}
|
0.7.5
|
/**
* @dev recovers any tokens stuck in Contract's balance
* NOTE! if ownership is renounced then it will not work
*/
|
function recoverTokens(address tokenAddress, uint256 amountToRecover) external onlyOwner {
IERC20Upgradeable token = IERC20Upgradeable(tokenAddress);
uint256 balance = token.balanceOf(address(this));
require(balance >= amountToRecover, "Not Enough Tokens in contract to recover");
if(amountToRecover > 0)
token.transfer(msg.sender, amountToRecover);
}
|
0.8.10
|
/*
@dev (Required) Set the per-second token issuance rate.
@param what The tag of the value to change (ex. bytes32("cap"))
@param data The value to update (ex. cap of 1000 tokens/yr == 1000*WAD/365 days)
*/
|
function file(bytes32 what, uint256 data) external auth lock {
if (what == "cap") cap = data; // The maximum amount of tokens that can be streamed per-second per vest
else revert("DssVest/file-unrecognized-param");
emit File(what, data);
}
|
0.6.12
|
/*
@dev Govanance adds a vesting contract
@param _usr The recipient of the reward
@param _tot The total amount of the vest
@param _bgn The starting timestamp of the vest
@param _tau The duration of the vest (in seconds)
@param _eta The cliff duration in seconds (i.e. 1 years)
@param _mgr An optional manager for the contract. Can yank if vesting ends prematurely.
@return id The id of the vesting contract
*/
|
function create(address _usr, uint256 _tot, uint256 _bgn, uint256 _tau, uint256 _eta, address _mgr) external auth lock returns (uint256 id) {
require(_usr != address(0), "DssVest/invalid-user");
require(_tot > 0, "DssVest/no-vest-total-amount");
require(_bgn < add(block.timestamp, TWENTY_YEARS), "DssVest/bgn-too-far");
require(_bgn > sub(block.timestamp, TWENTY_YEARS), "DssVest/bgn-too-long-ago");
require(_tau > 0, "DssVest/tau-zero");
require(_tot / _tau <= cap, "DssVest/rate-too-high");
require(_tau <= TWENTY_YEARS, "DssVest/tau-too-long");
require(_eta <= _tau, "DssVest/eta-too-long");
require(ids < type(uint256).max, "DssVest/ids-overflow");
id = ++ids;
awards[id] = Award({
usr: _usr,
bgn: toUint48(_bgn),
clf: toUint48(add(_bgn, _eta)),
fin: toUint48(add(_bgn, _tau)),
tot: toUint128(_tot),
rxd: 0,
mgr: _mgr,
res: 0
});
emit Init(id, _usr);
}
|
0.6.12
|
/*
@dev Anyone (or only owner of a vesting contract if restricted) calls this to claim rewards
@param _id The id of the vesting contract
@param _maxAmt The maximum amount to vest
*/
|
function _vest(uint256 _id, uint256 _maxAmt) internal lock {
Award memory _award = awards[_id];
require(_award.usr != address(0), "DssVest/invalid-award");
require(_award.res == 0 || _award.usr == msg.sender, "DssVest/only-user-can-claim");
uint256 amt = unpaid(block.timestamp, _award.bgn, _award.clf, _award.fin, _award.tot, _award.rxd);
amt = min(amt, _maxAmt);
awards[_id].rxd = toUint128(add(_award.rxd, amt));
pay(_award.usr, amt);
emit Vest(_id, amt);
}
|
0.6.12
|
/*
@dev amount of tokens accrued, not accounting for tokens paid
@param _time the timestamp to perform the calculation
@param _bgn the start time of the contract
@param _end the end time of the contract
@param _amt the total amount of the contract
*/
|
function accrued(uint256 _time, uint48 _bgn, uint48 _fin, uint128 _tot) internal pure returns (uint256 amt) {
if (_time < _bgn) {
amt = 0;
} else if (_time >= _fin) {
amt = _tot;
} else {
amt = mul(_tot, sub(_time, _bgn)) / sub(_fin, _bgn); // 0 <= amt < _award.tot
}
}
|
0.6.12
|
/*
@dev amount of tokens accrued, not accounting for tokens paid
@param _time the timestamp to perform the calculation
@param _bgn the start time of the contract
@param _clf the timestamp of the cliff
@param _end the end time of the contract
@param _tot the total amount of the contract
@param _rxd the number of gems received
*/
|
function unpaid(uint256 _time, uint48 _bgn, uint48 _clf, uint48 _fin, uint128 _tot, uint128 _rxd) internal pure returns (uint256 amt) {
amt = _time < _clf ? 0 : sub(accrued(_time, _bgn, _fin, _tot), _rxd);
}
|
0.6.12
|
/*
@dev Allows governance or the manager to end pre-maturely a vesting contract
@param _id The id of the vesting contract
@param _end A scheduled time to end the vest
*/
|
function _yank(uint256 _id, uint256 _end) internal lock {
require(wards[msg.sender] == 1 || awards[_id].mgr == msg.sender, "DssVest/not-authorized");
Award memory _award = awards[_id];
require(_award.usr != address(0), "DssVest/invalid-award");
if (_end < block.timestamp) {
_end = block.timestamp;
}
if (_end < _award.fin) {
uint48 end = toUint48(_end);
awards[_id].fin = end;
if (end < _award.bgn) {
awards[_id].bgn = end;
awards[_id].clf = end;
awards[_id].tot = 0;
} else if (end < _award.clf) {
awards[_id].clf = end;
awards[_id].tot = 0;
} else {
awards[_id].tot = toUint128(
add(
unpaid(_end, _award.bgn, _award.clf, _award.fin, _award.tot, _award.rxd),
_award.rxd
)
);
}
}
emit Yank(_id, _end);
}
|
0.6.12
|
/**
* @notice Allows the owner to execute custom transactions
* @param target address
* @param value uint256
* @param signature string
* @param data bytes
* @dev Only owner can call it
*/
|
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data
) external payable onlyOwner returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(
target != address(0),
"Orchestrator::executeTransaction: target can't be zero"
);
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) =
target.call{value: value}(callData);
require(
success,
"Orchestrator::executeTransaction: Transaction execution reverted."
);
emit TransactionExecuted(target, value, signature, data);
(target, value, signature, data);
return returnData;
}
|
0.7.5
|
/**
* @dev Internal setter for the voting period.
*
* Emits a {VotingPeriodSet} event.
*/
|
function _setVotingPeriod(uint256 newVotingPeriod) internal virtual {
// voting period must be at least one block long
require(newVotingPeriod > 0, "GovernorSettings: voting period too low");
emit VotingPeriodSet(_votingPeriod, newVotingPeriod);
_votingPeriod = newVotingPeriod;
}
|
0.8.4
|
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @return bool success
*/
|
function transfer(address _to, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
|
0.4.24
|
/**
* @dev Return total stake amount of `account`
*/
|
function getStakeAmount(
address account
)
external
view
returns (uint256)
{
uint256[] memory stakeIds = stakerIds[account];
uint256 totalStakeAmount;
for (uint256 i = 0; i < stakeIds.length; i++) {
totalStakeAmount += stakes[stakeIds[i]].amount;
}
return totalStakeAmount;
}
|
0.8.4
|
/**
* @dev Return total stake amount that have been in the pool from `fromDate`
* Requirements:
*
* - `fromDate` must be past date
*/
|
function getEligibleStakeAmount(
uint256 fromDate
)
public
override
view
returns (uint256)
{
require(fromDate <= block.timestamp, "StakeToken#getEligibleStakeAmount: NO_PAST_DATE");
uint256 totalSAmount;
for (uint256 i = 1; i <= tokenIds; i++) {
if (_exists(i)) {
Stake memory stake = stakes[i];
if (stake.depositedAt > fromDate) {
break;
}
totalSAmount += stake.amount * stake.multiplier / multiplierDenominator;
}
}
return totalSAmount;
}
|
0.8.4
|
/**
* @dev Returns StakeToken multiplier.
*
* 0 < `tokenId` <300: 120.
* 300 <= `tokenId` <4000: 110.
* 4000 <= `tokenId`: 100.
*/
|
function _getMultiplier()
private
view
returns (uint256)
{
if (tokenIds < 300) {
return 120;
} else if (300 <= tokenIds && tokenIds < 4000) {
return 110;
} else {
return 100;
}
}
|
0.8.4
|
/**
* @dev Mint a new StakeToken.
* Requirements:
*
* - `account` must not be zero address, check ERC721 {_mint}
* - `amount` must not be zero
* @param account address of recipient.
* @param amount mint amount.
* @param depositedAt timestamp when stake was deposited.
*/
|
function _mint(
address account,
uint256 amount,
uint256 depositedAt
)
internal
virtual
returns (uint256)
{
require(amount > 0, "StakeToken#_mint: INVALID_AMOUNT");
tokenIds++;
uint256 multiplier = _getMultiplier();
super._mint(account, tokenIds);
Stake storage newStake = stakes[tokenIds];
newStake.amount = amount;
newStake.multiplier = multiplier;
newStake.depositedAt = depositedAt;
stakerIds[account].push(tokenIds);
return tokenIds;
}
|
0.8.4
|
/**
* @dev Burn stakeToken.
* Requirements:
*
* - `stakeId` must exist in stake pool
* @param stakeId id of buring token.
*/
|
function _burn(
uint256 stakeId
)
internal
override
{
require(_exists(stakeId), "StakeToken#_burn: STAKE_NOT_FOUND");
address stakeOwner = ownerOf(stakeId);
super._burn(stakeId);
delete stakes[stakeId];
uint256[] storage stakeIds = stakerIds[stakeOwner];
for (uint256 i = 0; i < stakeIds.length; i++) {
if (stakeIds[i] == stakeId) {
if (i != stakeIds.length - 1) {
stakeIds[i] = stakeIds[stakeIds.length - 1];
}
stakeIds.pop();
break;
}
}
}
|
0.8.4
|
/**
* @dev Decrease stake amount.
* If stake amount leads to be zero, the stake is burned.
* Requirements:
*
* - `stakeId` must exist in stake pool
* @param stakeId id of buring token.
* @param amount to withdraw.
*/
|
function _decreaseStakeAmount(
uint256 stakeId,
uint256 amount
)
internal
virtual
{
require(_exists(stakeId), "StakeToken#_decreaseStakeAmount: STAKE_NOT_FOUND");
require(amount <= stakes[stakeId].amount, "StakeToken#_decreaseStakeAmount: INSUFFICIENT_STAKE_AMOUNT");
if (amount == stakes[stakeId].amount) {
_burn(stakeId);
} else {
stakes[stakeId].amount = stakes[stakeId].amount.sub(amount);
emit StakeAmountDecreased(stakeId, amount);
}
}
|
0.8.4
|
/**
* @dev Sweep funds
* Accessible by operators
*/
|
function sweep(
address token_,
address to,
uint256 amount
)
public
onlyOperator
{
IERC20 token = IERC20(token_);
// balance check is being done in ERC20
token.transfer(to, amount);
emit Swept(msg.sender, token_, to, amount);
}
|
0.8.4
|
/**
* @dev Updates set of the globally enabled features (`features`),
* taking into account sender's permissions.=
* @dev Requires transaction sender to have `ROLE_FEATURE_MANAGER` permission.
* @param mask bitmask representing a set of features to enable/disable
*/
|
function updateFeatures(uint256 mask) public {
// caller must have a permission to update global features
require(isSenderInRole(ROLE_FEATURE_MANAGER));
// evaluate new features set and assign them
features = evaluateBy(msg.sender, features, mask);
// fire an event
emit FeaturesUpdated(msg.sender, mask, features);
}
|
0.4.23
|
/**
* @dev Updates set of permissions (role) for a given operator,
* taking into account sender's permissions.
* @dev Setting role to zero is equivalent to removing an operator.
* @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to
* copying senders permissions (role) to an operator.
* @dev Requires transaction sender to have `ROLE_ROLE_MANAGER` permission.
* @param operator address of an operator to alter permissions for
* @param role bitmask representing a set of permissions to
* enable/disable for an operator specified
*/
|
function updateRole(address operator, uint256 role) public {
// caller must have a permission to update user roles
require(isSenderInRole(ROLE_ROLE_MANAGER));
// evaluate the role and reassign it
userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);
// fire an event
emit RoleUpdated(msg.sender, operator, role, userRoles[operator]);
}
|
0.4.23
|
/**
* @dev Based on the actual role provided (set of permissions), operator address,
* and role required (set of permissions), calculate the resulting
* set of permissions (role).
* @dev If operator is super admin and has full permissions (FULL_PRIVILEGES_MASK),
* the function will always return `required` regardless of the `actual`.
* @dev In contrast, if operator has no permissions at all (zero mask),
* the function will always return `actual` regardless of the `required`.
* @param operator address of the contract operator to use permissions of
* @param actual input set of permissions to modify
* @param required desired set of permissions operator would like to have
* @return resulting set of permissions this operator can set
*/
|
function evaluateBy(address operator, uint256 actual, uint256 required) public constant returns(uint256) {
// read operator's permissions
uint256 p = userRoles[operator];
// taking into account operator's permissions,
// 1) enable permissions requested on the `current`
actual |= p & required;
// 2) disable permissions requested on the `current`
actual &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ required));
// return calculated result (actual is not modified)
return actual;
}
|
0.4.23
|
// Returns TUTs rate per 1 ETH depending on current time
|
function getRateByTime() public constant returns (uint256) {
uint256 timeNow = now;
if (timeNow > (startTime + 94 * unitTimeSecs)) {
return 1500;
} else if (timeNow > (startTime + 87 * unitTimeSecs)) {
return 1575; // + 5%
} else if (timeNow > (startTime + 80 * unitTimeSecs)) {
return 1650; // + 10%
} else if (timeNow > (startTime + 73 * unitTimeSecs)) {
return 1800; // + 20%
} else if (timeNow > (startTime + 56 * unitTimeSecs)) {
return 2025; // + 35%
} else if (timeNow > (startTime + 42 * unitTimeSecs)) {
return 2100; // + 40%
} else if (timeNow > (startTime + 28 * unitTimeSecs)) {
return 2175; // + 45%
} else {
return 2250; // + 50%
}
}
|
0.4.15
|
/**
* @dev Mints (creates) some tokens to address specified
* @dev The value passed is treated as number of units (see `ONE_UNIT`)
* to achieve natural impression on token quantity
* @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission
* @param _to an address to mint tokens to
* @param _value an amount of tokens to mint (create)
*/
|
function mint(address _to, uint256 _value) public {
// calculate native value, taking into account `decimals`
uint256 value = _value * ONE_UNIT;
// arithmetic overflow and non-zero value check
require(value > _value);
// delegate call to native `mintNative`
mintNative(_to, value);
}
|
0.4.23
|
/**
* @dev Mints (creates) some tokens to address specified
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
* @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission
* @param _to an address to mint tokens to
* @param _value an amount of tokens to mint (create)
*/
|
function mintNative(address _to, uint256 _value) public {
// check if caller has sufficient permissions to mint tokens
require(isSenderInRole(ROLE_TOKEN_CREATOR));
// non-zero recipient address check
require(_to != address(0));
// non-zero _value and arithmetic overflow check on the total supply
// this check automatically secures arithmetic overflow on the individual balance
require(tokensTotal + _value > tokensTotal);
// increase `_to` address balance
tokenBalances[_to] += _value;
// increase total amount of tokens value
tokensTotal += _value;
// fire ERC20 compliant transfer event
emit Transfer(address(0), _to, _value);
// fire a mint event
emit Minted(msg.sender, _to, _value);
}
|
0.4.23
|
/**
* @dev Burns (destroys) some tokens from the address specified
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
* @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission
* @param _from an address to burn some tokens from
* @param _value an amount of tokens to burn (destroy)
*/
|
function burnNative(address _from, uint256 _value) public {
// check if caller has sufficient permissions to burn tokens
require(isSenderInRole(ROLE_TOKEN_DESTROYER));
// non-zero burn value check
require(_value != 0);
// verify `_from` address has enough tokens to destroy
// (basically this is a arithmetic overflow check)
require(tokenBalances[_from] >= _value);
// decrease `_from` address balance
tokenBalances[_from] -= _value;
// decrease total amount of tokens value
tokensTotal -= _value;
// fire ERC20 compliant transfer event
emit Transfer(_from, address(0), _value);
// fire a burn event
emit Burnt(msg.sender, _from, _value);
}
|
0.4.23
|
/* User can allow another smart contract to spend some shares in his behalf
* (this function should be called by user itself)
* @param _spender another contract's address
* @param _value number of tokens
* @param _extraData Data that can be sent from user to another contract to be processed
* bytes - dynamically-sized byte array,
* see http://solidity.readthedocs.io/en/v0.4.15/types.html#dynamically-sized-byte-array
* see possible attack information in comments to function 'approve'
* > this may be used to convert pre-ICO tokens to ICO tokens
*/
|
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {
approve(_spender, _value);
// 'spender' is another contract that implements code as prescribed in 'allowanceRecipient' above
allowanceRecipient spender = allowanceRecipient(_spender);
// our contract calls 'receiveApproval' function of another contract ('allowanceRecipient') to send information about
// allowance and data sent by user
// 'this' is this (our) contract address
if (spender.receiveApproval(msg.sender, _value, address(this), _extraData)) {
emit DataSentToAnotherContract(msg.sender, _spender, _extraData);
return true;
}
else return false;
}
|
0.5.6
|
/* https://github.com/ethereum/EIPs/issues/677
* transfer tokens with additional info to another smart contract, and calls its correspondent function
* @param address _to - another smart contract address
* @param uint256 _value - number of tokens
* @param bytes _extraData - data to send to another contract
* > this may be used to convert pre-ICO tokens to ICO tokens
*/
|
function transferAndCall(address _to, uint256 _value, bytes memory _extraData) public returns (bool success){
transferFrom(msg.sender, _to, _value);
tokenRecipient receiver = tokenRecipient(_to);
if (receiver.tokenFallback(msg.sender, _value, _extraData)) {
emit DataSentToAnotherContract(msg.sender, _to, _extraData);
return true;
}
else return false;
}
|
0.5.6
|
/* set time for start and time for end pre-ICO
* time is integer representing block timestamp
* in UNIX Time,
* see: https://www.epochconverter.com
* @param uint256 startTime - time to start
* @param uint256 endTime - time to end
* should be taken into account that
* "block.timestamp" can be influenced by miners to a certain degree.
* That means that a miner can "choose" the block.timestamp, to a certain degree,
* to change the outcome of a transaction in the mined block.
* see:
* http://solidity.readthedocs.io/en/v0.4.15/frequently-asked-questions.html#are-timestamps-now-block-timestamp-reliable
*/
|
function startSale(uint256 _startUnixTime, uint256 _endUnixTime) public onlyBy(owner) returns (bool success){
require(balanceOf[address(this)] > 0);
require(salesCounter < maxSalesAllowed);
// time for sale can be set only if:
// this is first sale (saleStartUnixTime == 0 && saleEndUnixTime == 0) , or:
// previous sale finished ( saleIsFinished() )
require(
(saleStartUnixTime == 0 && saleEndUnixTime == 0) || saleIsFinished()
);
// time can be set only for future
require(_startUnixTime > now && _endUnixTime > now);
// end time should be later than start time
require(_endUnixTime - _startUnixTime > 0);
saleStartUnixTime = _startUnixTime;
saleEndUnixTime = _endUnixTime;
salesCounter = salesCounter + 1;
emit SaleStarted(_startUnixTime, _endUnixTime, salesCounter);
return true;
}
|
0.5.6
|
/* After sale contract owner
* (can be another contract or account)
* can withdraw all collected Ether
*/
|
function withdrawAllToOwner() public onlyBy(owner) returns (bool) {
// only after sale is finished:
require(saleIsFinished());
uint256 sumInWei = address(this).balance;
if (
// makes withdrawal and returns true or false
!msg.sender.send(address(this).balance)
) {
return false;
}
else {
// event
emit Withdrawal(msg.sender, sumInWei);
return true;
}
}
|
0.5.6
|
/**
* @dev Transfers the tokens from a Taraxa owned wallet to the participant.
*
* Emits a {TokensSent} event.
*/
|
function multisendToken(
address token,
address[] calldata _recipients,
uint256[] calldata _amounts
) public {
require(_recipients.length <= 200, 'Multisend: max transfers per tx exceeded');
require(
_recipients.length == _amounts.length,
'Multisend: contributors and balances have different sizes'
);
uint256 total = 0;
IERC20 erc20token = IERC20(token);
uint8 i = 0;
for (i; i < _recipients.length; i++) {
erc20token.transferFrom(msg.sender, _recipients[i], _amounts[i]);
total += _amounts[i];
}
emit TokensSent(total, token);
}
|
0.7.6
|
//200m coins total
//reward begins at 500 and is cut in half every reward era (as tokens are mined)
|
function getMiningReward() public constant returns (uint) {
//once we get half way thru the coins, only get 250 per block
//every reward era, the reward amount halves.
return (500 * 10**uint(decimals) ).div( 2**rewardEra ) ;
}
|
0.4.18
|
/**
* @dev Getting Deex Token prize of _lastParticipant
* @param _lastParticipant Address of _lastParticipant
*/
|
function calculateLastDeexPrize(address _lastParticipant) public view returns(uint) {
uint payout = 0;
uint totalSupply = (lastTotalDeexSupplyOfDragons.add(lastTotalDeexSupplyOfHamsters)).mul(80).div(100);
if (depositDragons[currentRound - 1][_lastParticipant] > 0) {
payout = totalSupply.mul(depositDragons[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfDragons);
}
if (depositHamsters[currentRound - 1][_lastParticipant] > 0) {
payout = totalSupply.mul(depositHamsters[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfHamsters);
}
return payout;
}
|
0.5.6
|
// To transfer tokens by proxy
|
function transferFrom(address _from, address _to, uint256 _amount)
public
canEnter
isHolder(_to)
returns (bool)
{
require(_amount <= holders[_from].allowances[msg.sender]);
Holder from = holders[_from];
Holder to = holders[_to];
from.allowances[msg.sender] -= _amount;
Transfer(_from, _to, _amount);
return xfer(from, to, _amount);
}
|
0.4.10
|
// Processes token transfers and subsequent change in voting power
|
function xfer(Holder storage _from, Holder storage _to, uint _amount)
internal
returns (bool)
{
// Ensure dividends are up to date at current balances
updateDividendsFor(_from);
updateDividendsFor(_to);
// Remove existing votes
revoke(_from);
revoke(_to);
// Transfer tokens
_from.tokenBalance -= _amount;
_to.tokenBalance += _amount;
// Revote accoring to changed token balances
revote(_from);
revote(_to);
// Force election
election();
return true;
}
|
0.4.10
|
//
// Security Functions
//
// Cause the contract to Panic. This will block most state changing
// functions for a set delay.
|
function PANIC()
public
isHolder(msg.sender)
returns (bool)
{
// A blocking holder requires at least 10% of tokens
require(holders[msg.sender].tokenBalance >= totalSupply / 10);
panicked = true;
timeToCalm = uint40(now + PANICPERIOD);
Panicked(msg.sender);
return true;
}
|
0.4.10
|
// Queues a pending transaction
|
function timeLockSend(address _from, address _to, uint _value, bytes _data)
internal
returns (uint8)
{
// Check that queue is not full
require(ptxHead + 1 != ptxTail);
TX memory tx = TX({
from: _from,
to: _to,
value: _value,
data: _data,
blocked: false,
timeLock: uint40(now + TXDELAY)
});
TransactionPending(ptxHead, _from, _to, _value, now + TXDELAY);
pendingTxs[ptxHead++] = tx;
return ptxHead - 1;
}
|
0.4.10
|
// Execute the first TX in the pendingTxs queue. Values will
// revert if the transaction is blocked or fails.
|
function sendPending()
public
preventReentry
isHolder(msg.sender)
returns (bool)
{
if (ptxTail == ptxHead) return false; // TX queue is empty
TX memory tx = pendingTxs[ptxTail];
if(now < tx.timeLock) return false;
// Have memory cached the TX so deleting store now to prevent any chance
// of double spends.
delete pendingTxs[ptxTail++];
if(!tx.blocked) {
if(tx.to.call.value(tx.value)(tx.data)) {
// TX sent successfully
committedEther -= tx.value;
Withdrawal(tx.from, tx.to, tx.value);
return true;
}
}
// TX is blocked or failed so manually revert balances to pre-pending
// state
if (tx.from == address(this)) {
// Was sent from fund balance
committedEther -= tx.value;
} else {
// Was sent from holder ether balance
holders[tx.from].etherBalance += tx.value;
}
TransactionFailed(tx.from, tx.to, tx.value);
return false;
}
|
0.4.10
|
// To block a pending transaction
|
function blockPendingTx(uint _txIdx)
public
returns (bool)
{
// Only prevent reentry not entry during panic
require(!__reMutex);
// A blocking holder requires at least 10% of tokens or is trustee or
// is from own account
require(holders[msg.sender].tokenBalance >= totalSupply / BLOCKPCNT ||
msg.sender == pendingTxs[ptxTail].from ||
msg.sender == trustee);
pendingTxs[_txIdx].blocked = true;
TransactionBlocked(msg.sender, _txIdx);
return true;
}
|
0.4.10
|
// admin methods
|
function withdrawByAdmin(address _investor, uint256 _investednum, address _target) onlyAdmin public {
require(_investednum > 0 && investedAmount[_investor] >= _investednum);
require(!investorVault[_investor][_investednum].withdrawn);
require(token.balanceOf(address(this)) >= investorVault[_investor][_investednum].value);
adminWithdraw[_investor][_investednum][_target][msg.sender] = true;
for (uint256 i = 0; i < admins.length; i++) {
if (!adminWithdraw[_investor][_investednum][_target][admins[i]]) {
return;
}
}
require(token.transfer(_target, investorVault[_investor][_investednum].value));
investorVault[_investor][_investednum].withdrawn = true;
emit FPWithdrawnByAdmins(_target, investorVault[_investor][_investednum].value, _investor,
_investednum, investorVault[_investor][_investednum].fpnum);
}
|
0.4.24
|
// For the trustee to commit an amount from the fund balance as a dividend
|
function payDividends(uint _value)
public
canEnter
onlyTrustee
returns (bool)
{
require(_value <= fundBalance());
// Calculates dividend as percent of current `totalSupply` in 10e17
// fixed point math
dividendPoints += 10**18 * _value / totalSupply;
totalDividends += _value;
committedEther += _value;
return true;
}
|
0.4.10
|
// Creates holder accounts. Called by addHolder() and issue()
|
function join(address _addr)
internal
returns (bool)
{
if(0 != holders[_addr].id) return true;
require(_addr != address(this));
uint8 id;
// Search for the first available slot.
while (holderIndex[++id] != 0) {}
// if `id` is 0 then there has been a array full overflow.
if(id == 0) revert();
Holder holder = holders[_addr];
holder.id = id;
holder.lastClaimed = dividendPoints;
holder.votingFor = trustee;
holderIndex[id] = _addr;
NewHolder(_addr);
return true;
}
|
0.4.10
|
// Enable trading and assign values of arguments to variables
|
function enableTrading(uint256 blocks) external onlyOwner {
require(!tradingEnabled, "Trading already enabled");
require(blocks <= 5, "Must be less than 5 blocks");
tradingEnabled = true;
swapEnabled = true;
tradingEnabledBlock = block.number;
justicePeriod = blocks;
emit EnabledTrading();
}
|
0.8.11
|
// Lock wallet from transferring out for given time
|
function lockTokens(address[] memory wallets, uint256[] memory numDays) external onlyOwner {
require(wallets.length == numDays.length, "Arrays must be the same length");
require(wallets.length < 200, "Can only lock 200 wallets per txn due to gas limits");
for (uint i = 0; i < wallets.length; i++) {
require(balanceOf(wallets[i]) > 0, "No tokens");
require(_lockedWallets[wallets[i]] < block.timestamp, "Already locked");
_lockedWallets[wallets[i]] = block.timestamp + numDays[i] * 1 days;
}
}
|
0.8.11
|
// Update token threshold for when the contract sells for liquidity, marketing and development
|
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner {
require(newAmount >= (totalSupply() * 1 / 100000) / 10**18, "Threshold lower than 0.001% total supply");
require(newAmount <= (totalSupply() * 1 / 1000) / 10**18, "Threshold higher than 0.1% total supply");
swapTokensAtAmount = newAmount * (10**18);
emit UpdatedSwapTokensAtAmount(swapTokensAtAmount);
}
|
0.8.11
|
// Transfer given number of tokens to given address
|
function airdropToWallets(address[] memory wallets, uint256[] memory amountsInTokens) external onlyOwner {
require(wallets.length == amountsInTokens.length, "Arrays must be the same length");
require(wallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits");
for (uint256 i = 0; i < wallets.length; i++) {
_transfer(msg.sender, wallets[i], amountsInTokens[i] * 10**18);
}
}
|
0.8.11
|
// Update fees on buys
|
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevelopmentFee = _developmentFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee;
require(buyTotalFees <= 9, "Must keep fees at 9% or less");
}
|
0.8.11
|
// Update fees on sells
|
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevelopmentFee = _developmentFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee;
require(sellTotalFees <= 18, "Must keep fees at 18% or less");
}
|
0.8.11
|
// Contract sells
|
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 10) {
contractBalance = swapTokensAtAmount * 10;
}
bool success;
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
swapTokensForEth(contractBalance - liquidityTokens);
uint256 ethBalance = address(this).balance;
uint256 ethForLiquidity = ethBalance;
uint256 ethForMarketing = ethBalance * tokensForMarketing / (totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForDevelopment = ethBalance * tokensForDevelopment / (totalTokensToSwap - (tokensForLiquidity / 2));
ethForLiquidity -= ethForMarketing + ethForDevelopment;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDevelopment = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
}
(success,) = address(DevelopmentAddress).call{value: ethForDevelopment}("");
(success,) = address(MarketingAddress).call{value: address(this).balance}("");
}
|
0.8.11
|
// Withdraw unnecessary tokens
|
function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) {
require(_token != address(0), "_token address cannot be 0");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
emit TransferForeignToken(_token, _contractBalance);
}
|
0.8.11
|
// For the trustee to issue an offer of new tokens to a holder
|
function issue(address _addr, uint _amount)
public
canEnter
onlyTrustee
returns (bool)
{
// prevent overflows in total supply
assert(totalSupply + _amount < MAXTOKENS);
join(_addr);
Holder holder = holders[_addr];
holder.offerAmount = _amount;
holder.offerExpiry = uint40(now + 7 days);
IssueOffer(_addr);
return true;
}
|
0.4.10
|
// To close a holder account
|
function vacate(address _addr)
public
canEnter
isHolder(msg.sender)
isHolder(_addr)
returns (bool)
{
Holder holder = holders[_addr];
// Ensure holder account is empty, is not the trustee and there are no
// pending transactions or dividends
require(_addr != trustee);
require(holder.tokenBalance == 0);
require(holder.etherBalance == 0);
require(holder.lastClaimed == dividendPoints);
require(ptxHead == ptxTail);
delete holderIndex[holder.id];
delete holders[_addr];
// NB can't garbage collect holder.allowances mapping
return (true);
}
|
0.4.10
|
// performs presale burn
|
function burn (uint256 _burnAmount, bool _presaleBurn) public onlyOwner returns (bool success) {
if (_presaleBurn) {
require(_presaleBurnTotal.add(_burnAmount) <= _maximumPresaleBurnAmount);
_presaleBurnTotal = _presaleBurnTotal.add(_burnAmount);
_transfer(_owner, address(0), _burnAmount);
_totalSupply = _totalSupply.sub(_burnAmount);
} else {
_transfer(_owner, address(0), _burnAmount);
_totalSupply = _totalSupply.sub(_burnAmount);
}
return true;
}
|
0.6.0
|
/**
* @notice Allows an user to create an unique Vault
* @dev Only one vault per address can be created
*/
|
function createVault() external virtual whenNotPaused {
require(
userToVault[msg.sender] == 0,
"VaultHandler::createVault: vault already created"
);
uint256 id = counter.current();
userToVault[msg.sender] = id;
Vault memory vault = Vault(id, 0, 0, msg.sender);
vaults[id] = vault;
counter.increment();
emit VaultCreated(msg.sender, id);
}
|
0.7.5
|
/**
* @notice Allows users to add collateral to their vaults
* @param _amount of collateral to be added
* @dev _amount should be higher than 0
* @dev ERC20 token must be approved first
*/
|
function addCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
require(
collateralContract.transferFrom(msg.sender, address(this), _amount),
"VaultHandler::addCollateral: ERC20 transfer did not succeed"
);
Vault storage vault = vaults[userToVault[msg.sender]];
vault.Collateral = vault.Collateral.add(_amount);
emit CollateralAdded(msg.sender, vault.Id, _amount);
}
|
0.7.5
|
/**
* @notice Allows users to remove collateral currently not being used to generate TCAP tokens from their vaults
* @param _amount of collateral to remove
* @dev reverts if the resulting ratio is less than the minimun ratio
* @dev _amount should be higher than 0
* @dev transfers the collateral back to the user
*/
|
function removeCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 currentRatio = getVaultRatio(vault.Id);
require(
vault.Collateral >= _amount,
"VaultHandler::removeCollateral: retrieve amount higher than collateral"
);
vault.Collateral = vault.Collateral.sub(_amount);
if (currentRatio != 0) {
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::removeCollateral: collateral below min required ratio"
);
}
require(
collateralContract.transfer(msg.sender, _amount),
"VaultHandler::removeCollateral: ERC20 transfer did not succeed"
);
emit CollateralRemoved(msg.sender, vault.Id, _amount);
}
|
0.7.5
|
/**
* @notice Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller
* @param _amount of tokens to mint
* @dev _amount should be higher than 0
* @dev requires to have a vault ratio above the minimum ratio
* @dev if reward handler is set stake to earn rewards
*/
|
function mint(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 collateral = requiredCollateral(_amount);
require(
vault.Collateral >= collateral,
"VaultHandler::mint: not enough collateral"
);
vault.Debt = vault.Debt.add(_amount);
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::mint: collateral below min required ratio"
);
if (address(rewardHandler) != address(0)) {
rewardHandler.stake(msg.sender, _amount);
}
TCAPToken.mint(msg.sender, _amount);
emit TokensMinted(msg.sender, vault.Id, _amount);
}
|
0.7.5
|
/**
* @notice Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimun vault ratio
* @param _amount of tokens to burn
* @dev _amount should be higher than 0
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
* @dev if reward handler is set exit rewards
*/
|
function burn(uint256 _amount)
external
payable
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
uint256 fee = getFee(_amount);
require(
msg.value >= fee,
"VaultHandler::burn: burn fee less than required"
);
Vault memory vault = vaults[userToVault[msg.sender]];
_burn(vault.Id, _amount);
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(msg.sender, _amount);
rewardHandler.getRewardFromVault(msg.sender);
}
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit TokensBurned(msg.sender, vault.Id, _amount);
}
|
0.7.5
|
/**
* @notice Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium
* @param _vaultId to liquidate
* @param _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate vault
* @dev Resulting ratio must be above or equal minimun ratio
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
*/
|
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP)
external
payable
nonReentrant
whenNotPaused
{
Vault storage vault = vaults[_vaultId];
require(vault.Id != 0, "VaultHandler::liquidateVault: no vault created");
uint256 vaultRatio = getVaultRatio(vault.Id);
require(
vaultRatio < ratio,
"VaultHandler::liquidateVault: vault is not liquidable"
);
uint256 requiredTCAP = requiredLiquidationTCAP(vault.Id);
require(
_maxTCAP >= requiredTCAP,
"VaultHandler::liquidateVault: liquidation amount different than required"
);
uint256 fee = getFee(requiredTCAP);
require(
msg.value >= fee,
"VaultHandler::liquidateVault: burn fee less than required"
);
uint256 reward = liquidationReward(vault.Id);
_burn(vault.Id, requiredTCAP);
//Removes the collateral that is rewarded to liquidator
vault.Collateral = vault.Collateral.sub(reward);
// Triggers update of CTX Rewards
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(vault.Owner, requiredTCAP);
}
require(
collateralContract.transfer(msg.sender, reward),
"VaultHandler::liquidateVault: ERC20 transfer did not succeed"
);
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit VaultLiquidated(vault.Id, msg.sender, requiredTCAP, reward);
}
|
0.7.5
|
/**
* @notice Returns the minimal required TCAP to liquidate a Vault
* @param _vaultId of the vault to liquidate
* @return amount required of the TCAP Token
* @dev LT = ((((D * r) / 100) - cTcap) * 100) / (r - (p + 100))
* cTcap = ((C * cp) / P)
* LT = Required TCAP
* D = Vault Debt
* C = Required Collateral
* P = TCAP Token Price
* cp = Collateral Price
* r = Min Vault Ratio
* p = Liquidation Penalty
*/
|
function requiredLiquidationTCAP(uint256 _vaultId)
public
view
virtual
returns (uint256 amount)
{
Vault memory vault = vaults[_vaultId];
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 collateralTcap =
(vault.Collateral.mul(collateralPrice)).div(tcapPrice);
uint256 reqDividend =
(((vault.Debt.mul(ratio)).div(100)).sub(collateralTcap)).mul(100);
uint256 reqDivisor = ratio.sub(liquidationPenalty.add(100));
amount = reqDividend.div(reqDivisor);
}
|
0.7.5
|
/**
* @notice Returns the Collateral Ratio of the Vault
* @param _vaultId id of vault
* @return currentRatio
* @dev vr = (cp * (C * 100)) / D * P
* vr = Vault Ratio
* C = Vault Collateral
* cp = Collateral Price
* D = Vault Debt
* P = TCAP Token Price
*/
|
function getVaultRatio(uint256 _vaultId)
public
view
virtual
returns (uint256 currentRatio)
{
Vault memory vault = vaults[_vaultId];
if (vault.Id == 0 || vault.Debt == 0) {
currentRatio = 0;
} else {
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
currentRatio = (
(collateralPrice.mul(vault.Collateral.mul(100))).div(
vault.Debt.mul(TCAPPrice())
)
);
}
}
|
0.7.5
|
/**
* @dev Get the raw trait indices for a given tokenId
* @param tokenId of a MEV Army NFT
* @return An array of integers that are indices for the trait arrays stored in this contract
* example: [ binary index, legion index, light index, mouth index, helmet index, eyes index, faces index ]
**/
|
function getTraitsIndices(uint256 tokenId) public view returns (EditionIndices memory){
require(tokenId > 0 && tokenId < 10000, "nonexistent tokenId");
// calculate the slot for a given token id
uint256 slotForTokenId = (tokenId - 1) >> 2;
// calculate the index within a slot for a given token id
uint256 slotIndex = ((tokenId - 1) % 4);
// get the slot from storage and unpack it
uint256 slot = EDITION_SLOTS[slotForTokenId];
uint256 unpackedSlot = _unPackSlot(slot, slotIndex);
// get the edition from the slot and unpack it
return _unPackEdition(unpackedSlot);
}
|
0.8.2
|
/**
* @dev Unpack an edition. Each edition contains 7 traits packed into an unsigned integer.
* Each packed trait is an 8-bit unsigned integer.
**/
|
function _unPackEdition(uint256 edition) internal pure returns (EditionIndices memory){
return EditionIndices(
uint8((edition) & uint256(type(uint8).max)),
uint8((edition >> 8) & uint256(type(uint8).max)),
uint8((edition >> 16) & uint256(type(uint8).max)),
uint8((edition >> 24) & uint256(type(uint8).max)),
uint8((edition >> 32) & uint256(type(uint8).max)),
uint8((edition >> 40) & uint256(type(uint8).max)),
uint8((edition >> 48) & uint256(type(uint8).max))
);
}
|
0.8.2
|
/// @notice Add the hypervisor position
/// @param pos Address of the hypervisor
/// @param version Type of hypervisor
|
function addPosition(address pos, uint8 version) external onlyOwner {
Position storage p = positions[pos];
require(p.version == 0, 'already added');
require(version > 0, 'version < 1');
p.version = version;
IHypervisor(pos).token0().safeApprove(pos, MAX_UINT);
IHypervisor(pos).token1().safeApprove(pos, MAX_UINT);
emit PositionAdded(pos, version);
}
|
0.7.6
|
/// @notice Get the amount of token to deposit for the given amount of pair token
/// @param pos Hypervisor Address
/// @param token Address of token to deposit
/// @param _deposit Amount of token to deposit
/// @return amountStart Minimum amounts of the pair token to deposit
/// @return amountEnd Maximum amounts of the pair token to deposit
|
function getDepositAmount(
address pos,
address token,
uint256 _deposit
) public view returns (uint256 amountStart, uint256 amountEnd) {
require(token == address(IHypervisor(pos).token0()) || token == address(IHypervisor(pos).token1()), "token mistmatch");
require(_deposit > 0, "deposits can't be zero");
(uint256 total0, uint256 total1) = IHypervisor(pos).getTotalAmounts();
if (IHypervisor(pos).totalSupply() == 0 || total0 == 0 || total1 == 0) {
amountStart = 0;
if (token == address(IHypervisor(pos).token0())) {
amountEnd = IHypervisor(pos).deposit1Max();
} else {
amountEnd = IHypervisor(pos).deposit0Max();
}
} else {
uint256 ratioStart;
uint256 ratioEnd;
if (token == address(IHypervisor(pos).token0())) {
ratioStart = FullMath.mulDiv(total0.mul(depositDelta), 1e18, total1.mul(deltaScale));
ratioEnd = FullMath.mulDiv(total0.mul(deltaScale), 1e18, total1.mul(depositDelta));
} else {
ratioStart = FullMath.mulDiv(total1.mul(depositDelta), 1e18, total0.mul(deltaScale));
ratioEnd = FullMath.mulDiv(total1.mul(deltaScale), 1e18, total0.mul(depositDelta));
}
amountStart = FullMath.mulDiv(_deposit, 1e18, ratioStart);
amountEnd = FullMath.mulDiv(_deposit, 1e18, ratioEnd);
}
}
|
0.7.6
|
/// @notice Check if the price change overflows or not based on given twap and threshold in the hypervisor
/// @param pos Hypervisor Address
/// @param _twapInterval Time intervals
/// @param _priceThreshold Price Threshold
/// @return price Current price
|
function checkPriceChange(
address pos,
uint32 _twapInterval,
uint256 _priceThreshold
) public view returns (uint256 price) {
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(IHypervisor(pos).currentTick());
price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), 1e18, 2**(96 * 2));
uint160 sqrtPriceBefore = getSqrtTwapX96(pos, _twapInterval);
uint256 priceBefore = FullMath.mulDiv(uint256(sqrtPriceBefore).mul(uint256(sqrtPriceBefore)), 1e18, 2**(96 * 2));
if (price.mul(100).div(priceBefore) > _priceThreshold || priceBefore.mul(100).div(price) > _priceThreshold)
revert("Price change Overflow");
}
|
0.7.6
|
/// @notice Get the sqrt price before the given interval
/// @param pos Hypervisor Address
/// @param _twapInterval Time intervals
/// @return sqrtPriceX96 Sqrt price before interval
|
function getSqrtTwapX96(address pos, uint32 _twapInterval) public view returns (uint160 sqrtPriceX96) {
if (_twapInterval == 0) {
/// return the current price if _twapInterval == 0
(sqrtPriceX96, , , , , , ) = IHypervisor(pos).pool().slot0();
}
else {
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = _twapInterval; /// from (before)
secondsAgos[1] = 0; /// to (now)
(int56[] memory tickCumulatives, ) = IHypervisor(pos).pool().observe(secondsAgos);
/// tick(imprecise as it's an integer) to price
sqrtPriceX96 = TickMath.getSqrtRatioAtTick(
int24((tickCumulatives[1] - tickCumulatives[0]) / _twapInterval)
);
}
}
|
0.7.6
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.