Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
17 | // The EIP-712 typehash for the ballot struct used by the contract | bytes32 public constant BALLOT_TYPEHASH =
keccak256("Ballot(uint256 proposalId,bool support)");
| bytes32 public constant BALLOT_TYPEHASH =
keccak256("Ballot(uint256 proposalId,bool support)");
| 33,018 |
62 | // Startable tokenStandardToken modified with startable transfers. / | contract StartToken is Startable, ERC223TokenCompatible, StandardToken {
/** ******************************** */
/** START: ADDED BY HORIZON GLOBEX */
/** ******************************** */
// KYC submission hashes accepted by KYC service provider for AML/KYC review.
bytes32[] public kycHashes;
// All users that have passed the external KYC verification checks.
address[] public kycValidated;
/**
* The hash for all Know Your Customer information is calculated outside but stored here.
* This storage will be cleared once the ICO completes, see closeIco().
*
* ---- ICO-Platform Note ----
* The horizon-globex.com ICO platform's KYC app will register a hash of the Contributors
* KYC submission on the blockchain. Our Swiss financial-intermediary KYC provider will be
* notified of the submission and retrieve the Contributor data for formal review.
*
* All Contributors must successfully complete our ICO KYC review prior to being allowed on-board.
* -- End ICO-Platform Note --
*
* @param sha The hash of the customer data.
*/
function setKycHash(bytes32 sha) public onlyOwner {
kycHashes.push(sha);
}
/**
* A user has passed KYC verification, store them on the blockchain in the order it happened.
* This will be cleared once the ICO completes, see closeIco().
*
* ---- ICO-Platform Note ----
* The horizon-globex.com ICO platform's registered KYC provider submits their approval
* for this Contributor to particpate using the ICO-Platform portal.
*
* Each Contributor will then be sent the Ethereum, Bitcoin and IBAN account numbers to
* deposit their Approved Contribution in exchange for VOX Tokens.
* -- End ICO-Platform Note --
*
* @param who The user's address.
*/
function kycApproved(address who) public onlyOwner {
require(who != 0x0, "Cannot approve a null address.");
kycValidated.push(who);
}
/**
* Retrieve the KYC hash from the specified index.
*
* @param index The index into the array.
*/
function getKycHash(uint256 index) public view returns (bytes32) {
return kycHashes[index];
}
/**
* Retrieve the validated KYC address from the specified index.
*
* @param index The index into the array.
*/
function getKycApproved(uint256 index) public view returns (address) {
return kycValidated[index];
}
/**
* During the ICO phase the owner will allocate tokens once KYC completes and funds are deposited.
*
* ---- ICO-Platform Note ----
* The horizon-globex.com ICO platform's portal shall issue VOX Token to Contributors on receipt of
* the Approved Contribution funds at the KYC providers Escrow account/wallets.
* Only after VOX Tokens are issued to the Contributor can the Swiss KYC provider allow the transfer
* of funds from their Escrow to Company.
*
* -- End ICO-Platform Note --
*
* @param to The recipient of the tokens.
* @param value The number of tokens to send.
*/
function icoTransfer(address to, uint256 value) public onlyOwner {
// If an attempt is made to transfer more tokens than owned, transfer the remainder.
uint256 toTransfer = (value > (balances[msg.sender])) ? (balances[msg.sender]) : value;
transferFunction(msg.sender, to, toTransfer);
}
/** ******************************** */
/** END: ADDED BY HORIZON GLOBEX */
/** ******************************** */
function transfer(address _to, uint256 _value) public whenStarted returns (bool) {
return super.transfer(_to, _value);
}
function transfer(address _to, uint256 _value, bytes _data) public whenStarted returns (bool) {
return super.transfer(_to, _value, _data);
}
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public whenStarted returns (bool) {
return super.transfer(_to, _value, _data, _custom_fallback);
}
function transferFrom(address _from, address _to, uint256 _value) public whenStarted returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenStarted returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenStarted returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenStarted returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
| contract StartToken is Startable, ERC223TokenCompatible, StandardToken {
/** ******************************** */
/** START: ADDED BY HORIZON GLOBEX */
/** ******************************** */
// KYC submission hashes accepted by KYC service provider for AML/KYC review.
bytes32[] public kycHashes;
// All users that have passed the external KYC verification checks.
address[] public kycValidated;
/**
* The hash for all Know Your Customer information is calculated outside but stored here.
* This storage will be cleared once the ICO completes, see closeIco().
*
* ---- ICO-Platform Note ----
* The horizon-globex.com ICO platform's KYC app will register a hash of the Contributors
* KYC submission on the blockchain. Our Swiss financial-intermediary KYC provider will be
* notified of the submission and retrieve the Contributor data for formal review.
*
* All Contributors must successfully complete our ICO KYC review prior to being allowed on-board.
* -- End ICO-Platform Note --
*
* @param sha The hash of the customer data.
*/
function setKycHash(bytes32 sha) public onlyOwner {
kycHashes.push(sha);
}
/**
* A user has passed KYC verification, store them on the blockchain in the order it happened.
* This will be cleared once the ICO completes, see closeIco().
*
* ---- ICO-Platform Note ----
* The horizon-globex.com ICO platform's registered KYC provider submits their approval
* for this Contributor to particpate using the ICO-Platform portal.
*
* Each Contributor will then be sent the Ethereum, Bitcoin and IBAN account numbers to
* deposit their Approved Contribution in exchange for VOX Tokens.
* -- End ICO-Platform Note --
*
* @param who The user's address.
*/
function kycApproved(address who) public onlyOwner {
require(who != 0x0, "Cannot approve a null address.");
kycValidated.push(who);
}
/**
* Retrieve the KYC hash from the specified index.
*
* @param index The index into the array.
*/
function getKycHash(uint256 index) public view returns (bytes32) {
return kycHashes[index];
}
/**
* Retrieve the validated KYC address from the specified index.
*
* @param index The index into the array.
*/
function getKycApproved(uint256 index) public view returns (address) {
return kycValidated[index];
}
/**
* During the ICO phase the owner will allocate tokens once KYC completes and funds are deposited.
*
* ---- ICO-Platform Note ----
* The horizon-globex.com ICO platform's portal shall issue VOX Token to Contributors on receipt of
* the Approved Contribution funds at the KYC providers Escrow account/wallets.
* Only after VOX Tokens are issued to the Contributor can the Swiss KYC provider allow the transfer
* of funds from their Escrow to Company.
*
* -- End ICO-Platform Note --
*
* @param to The recipient of the tokens.
* @param value The number of tokens to send.
*/
function icoTransfer(address to, uint256 value) public onlyOwner {
// If an attempt is made to transfer more tokens than owned, transfer the remainder.
uint256 toTransfer = (value > (balances[msg.sender])) ? (balances[msg.sender]) : value;
transferFunction(msg.sender, to, toTransfer);
}
/** ******************************** */
/** END: ADDED BY HORIZON GLOBEX */
/** ******************************** */
function transfer(address _to, uint256 _value) public whenStarted returns (bool) {
return super.transfer(_to, _value);
}
function transfer(address _to, uint256 _value, bytes _data) public whenStarted returns (bool) {
return super.transfer(_to, _value, _data);
}
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public whenStarted returns (bool) {
return super.transfer(_to, _value, _data, _custom_fallback);
}
function transferFrom(address _from, address _to, uint256 _value) public whenStarted returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenStarted returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenStarted returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenStarted returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
| 19,562 |
5 | // PAW tokens created per block. | uint256 public pawPerBlock = 8 ether;
uint256 public constant MAX_EMISSION_RATE = 1000 ether; // Safety check
| uint256 public pawPerBlock = 8 ether;
uint256 public constant MAX_EMISSION_RATE = 1000 ether; // Safety check
| 12,968 |
18 | // Liquidate an asset bought via our listing / | ) public payable nonReentrant onlyOwner {
int256 tokenId = IERC721(_nftAddress).tokenId();
address assetManager = idToAssetListing[listingId].assetManager;
Asset storedAsset = IAssetManager(assetManager).getAsset(tokenId);
require(IAssetManager(assetManager).getAsset(tokenId), "Asset not valid");
require(msg.value == orderFee, "You need to pay fees to liquidate your asset");
require(balanceOf(market) > storedAsset.value, "Sorry, the market cannot buy back this asset from you right now");
// TODO: Manage transfer of asset manager for the asset in question
IERC721(_nftAddress).safeTransferFrom(msg.sender, address(this), tokenId);
payable(market).transfer(orderFee);
payable(seller).transfer(storedAsset.value);
}
| ) public payable nonReentrant onlyOwner {
int256 tokenId = IERC721(_nftAddress).tokenId();
address assetManager = idToAssetListing[listingId].assetManager;
Asset storedAsset = IAssetManager(assetManager).getAsset(tokenId);
require(IAssetManager(assetManager).getAsset(tokenId), "Asset not valid");
require(msg.value == orderFee, "You need to pay fees to liquidate your asset");
require(balanceOf(market) > storedAsset.value, "Sorry, the market cannot buy back this asset from you right now");
// TODO: Manage transfer of asset manager for the asset in question
IERC721(_nftAddress).safeTransferFrom(msg.sender, address(this), tokenId);
payable(market).transfer(orderFee);
payable(seller).transfer(storedAsset.value);
}
| 43,789 |
11 | // | /// @return {bytes}
///
function addAttributeSet(
bytes32 name,
bytes32[] calldata values
)internal pure returns(
bytes memory
){
return abi.encodeWithSignature(
STUB_ADD_ATTRIBUTE_SET,
name,
values
);
}
| /// @return {bytes}
///
function addAttributeSet(
bytes32 name,
bytes32[] calldata values
)internal pure returns(
bytes memory
){
return abi.encodeWithSignature(
STUB_ADD_ATTRIBUTE_SET,
name,
values
);
}
| 3,558 |
42 | // emitted when a proposal is created. proposalId id of the proposal creator address of the creator of the proposal accessLevel minimum level needed to be able to execute this proposal ipfsHash ipfs has containing the proposal metadata information / | event ProposalCreated(
| event ProposalCreated(
| 15,897 |
9 | // Array for holders | address[] internal holderaddresses; //array to store the holders
| address[] internal holderaddresses; //array to store the holders
| 50,420 |
139 | // We need to unregister tokens first | for (uint256 i=0; i < _registeredTokens.length; i++){
if (_registeredTokens[i] != address(0)) {
_unregisterToken(_registeredTokens[i]);
_registeredTokens[i] = address(0);
}
| for (uint256 i=0; i < _registeredTokens.length; i++){
if (_registeredTokens[i] != address(0)) {
_unregisterToken(_registeredTokens[i]);
_registeredTokens[i] = address(0);
}
| 48,101 |
5 | // could set more init variables too other than just owner useful when there's a more elaborate start state proxy can call it and set its state delegatecall into intialize, to set up the initial state in the proxy scope | function initialize(address _owner) public {
// only run once
require(_initialized == false);
owner = _owner;
_initialized = true;
}
| function initialize(address _owner) public {
// only run once
require(_initialized == false);
owner = _owner;
_initialized = true;
}
| 9,550 |
9 | // See {ERC20Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `VOLMEX_PROTOCOL_ROLE`. / | function unpause() public virtual {
require(
hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender),
"VolmexPositionToken: must have volmex protocol role to unpause"
);
_unpause();
}
| function unpause() public virtual {
require(
hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender),
"VolmexPositionToken: must have volmex protocol role to unpause"
);
_unpause();
}
| 58,271 |
108 | // Any action before `startStakingBlockIndex` is treated as acted in block `startStakingBlockIndex`. | if (block.number < startStakingBlockIndex) {
_stakingRecords[staker].blockIndex = startStakingBlockIndex;
}
| if (block.number < startStakingBlockIndex) {
_stakingRecords[staker].blockIndex = startStakingBlockIndex;
}
| 41,996 |
6 | // An event emitted when a vault handler is added | event VaultHandlerAdded(
address indexed _owner,
address indexed _tokenHandler
);
| event VaultHandlerAdded(
address indexed _owner,
address indexed _tokenHandler
);
| 17,946 |
38 | // update state | _weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
| _weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
| 786 |
218 | // removes a stream (only default admin role)/streamId stream index/streamFundReceiver receives the rest of the reward tokens in the stream | function removeStream(uint256 streamId, address streamFundReceiver)
external
virtual
onlyRole(STREAM_MANAGER_ROLE)
| function removeStream(uint256 streamId, address streamFundReceiver)
external
virtual
onlyRole(STREAM_MANAGER_ROLE)
| 34,173 |
797 | // Will use the owner address of another parent contract _newParent Address of the new owner / | function changeOwnableParent(address _newParent) public onlyOwner {
| function changeOwnableParent(address _newParent) public onlyOwner {
| 35,253 |
104 | // unsuccessful end of CrowdSale | if (weiRaised.add(preSale.weiRaised()) < softCap && now > endCrowdSaleTime) {
refundAll(_to);
return;
}
| if (weiRaised.add(preSale.weiRaised()) < softCap && now > endCrowdSaleTime) {
refundAll(_to);
return;
}
| 23,253 |
26 | // View function to see pending rewards on frontend. | function pending(uint256 _pid,address _user) public view returns (uint256){
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
// uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 lpSupply = pool.totalAmount;
if (user.amount > 0) {
if (block.number > pool.lastRewardBlock) {
uint256 blockReward = getBlockRewards(pool.lastRewardBlock);
uint256 poolReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint);
accRewardPerShare = accRewardPerShare.add(poolReward.mul(1e12).div(lpSupply));
return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt);
}
if (block.number == pool.lastRewardBlock) {
return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt);
}
}
return 0;
}
| function pending(uint256 _pid,address _user) public view returns (uint256){
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
// uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 lpSupply = pool.totalAmount;
if (user.amount > 0) {
if (block.number > pool.lastRewardBlock) {
uint256 blockReward = getBlockRewards(pool.lastRewardBlock);
uint256 poolReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint);
accRewardPerShare = accRewardPerShare.add(poolReward.mul(1e12).div(lpSupply));
return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt);
}
if (block.number == pool.lastRewardBlock) {
return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt);
}
}
return 0;
}
| 40,979 |
38 | // All data related to this account must be destroyed. Account is asking this voluntary or delete is through governance action. | Destroyed
| Destroyed
| 38,645 |
59 | // Modify listing mechanism | function modifyListingMechanism(
uint256 tokenId,
bool setFixPrice,
bool forSale,
uint256 newPrice
)
public
| function modifyListingMechanism(
uint256 tokenId,
bool setFixPrice,
bool forSale,
uint256 newPrice
)
public
| 27,486 |
53 | // cards can be sold | require(sellable);
if (coinCost>0) {
coinChange = SafeMath.add(cards.balanceOfUnclaimed(msg.sender), SafeMath.div(SafeMath.mul(coinCost,70),100)); // Claim unsaved goo whilst here
} else {
| require(sellable);
if (coinCost>0) {
coinChange = SafeMath.add(cards.balanceOfUnclaimed(msg.sender), SafeMath.div(SafeMath.mul(coinCost,70),100)); // Claim unsaved goo whilst here
} else {
| 4,040 |
22 | // ------------------------------------------------------------------------ Transfer `tokens` from theaccount to theaccountThe calling account must already have sufficient tokens approve(...) for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - Zero value transfers are allowed ------------------------------------------------------------------------ | function transferFrom(address from, address to, uint tokens) public returns (bool success){
// will update unLockedCoins based on time
if(msg.sender != owner){
_updateUnLockedCoins(from, tokens);
unLockedCoins[from] = unLockedCoins[from].sub(tokens);
unLockedCoins[to] = unLockedCoins[to].add(tokens);
}
require(tokens <= allowed[from][msg.sender]); //check allowance
require(balances[from] >= tokens);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from,to,tokens);
return true;
}
| function transferFrom(address from, address to, uint tokens) public returns (bool success){
// will update unLockedCoins based on time
if(msg.sender != owner){
_updateUnLockedCoins(from, tokens);
unLockedCoins[from] = unLockedCoins[from].sub(tokens);
unLockedCoins[to] = unLockedCoins[to].add(tokens);
}
require(tokens <= allowed[from][msg.sender]); //check allowance
require(balances[from] >= tokens);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from,to,tokens);
return true;
}
| 12 |
103 | // The last proposed strategy to switch to. | StratCandidate public stratCandidate;
| StratCandidate public stratCandidate;
| 22,312 |
5 | // Constructor of the contract/_admin Admin address of the contract | constructor(address _admin) {
require(_admin != address(0), "0");
admin = _admin;
}
| constructor(address _admin) {
require(_admin != address(0), "0");
admin = _admin;
}
| 72,665 |
1 | // Creates the POAV contract. | constructor(uint ph) public {
photo_hash = ph;
}
| constructor(uint ph) public {
photo_hash = ph;
}
| 4,007 |
58 | // balances[_to] = balances[_to].add(_amount); | balances.addBalance(_to, _amount);
minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
emit Mint(msg.sender, _to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
| balances.addBalance(_to, _amount);
minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
emit Mint(msg.sender, _to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
| 42,008 |
2 | // ----------------------------- State variables ------------------------------ |
bool public mintLive = true;
mapping(address => bool) private mintedStatus;
uint256 nonce = 0;
string public uriOS;
IManagersTBA public ManagersTBA;
|
bool public mintLive = true;
mapping(address => bool) private mintedStatus;
uint256 nonce = 0;
string public uriOS;
IManagersTBA public ManagersTBA;
| 42,384 |
40 | // store in the duration memory location of `searchData` | add(searchData, MEMORY_OFFSET_duration),
| add(searchData, MEMORY_OFFSET_duration),
| 38,662 |
21 | // Safely transfers the ownership of a given token ID to another addressIf the target address is a contract, it must implement `onERC721Received`,which is called upon a safe transfer, and return the magic value`bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,the transfer is reverted. Requires the msg sender to be the owner, approved, or operator _from current owner of the token _to address to receive the ownership of the given token ID _tokenId uint256 ID of the token to be transferred/ | function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
override
noEmergencyFreeze
canTransfer(_tokenId)
| function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
override
noEmergencyFreeze
canTransfer(_tokenId)
| 5,057 |
74 | // Receive a contribution from `_recipient`.// Preconditions: !paused, sale_ongoing/ Postconditions: ?!sale_ongoing | /// Writes {Tokens, Sale}
function processPurchase(address _recipient)
only_during_period
is_valid_buyin
is_under_cap_with(msg.value)
private
{
// Bounded value, see STANDARD_BUYIN.
tokens.mint(_recipient, msg.value * STANDARD_BUYIN);
TREASURY.transfer(msg.value);
saleRevenue += msg.value;
totalSold += msg.value * STANDARD_BUYIN;
Purchased(_recipient, msg.value);
}
| /// Writes {Tokens, Sale}
function processPurchase(address _recipient)
only_during_period
is_valid_buyin
is_under_cap_with(msg.value)
private
{
// Bounded value, see STANDARD_BUYIN.
tokens.mint(_recipient, msg.value * STANDARD_BUYIN);
TREASURY.transfer(msg.value);
saleRevenue += msg.value;
totalSold += msg.value * STANDARD_BUYIN;
Purchased(_recipient, msg.value);
}
| 13,343 |
22 | // ERRORS / | error PriceIdNotSet();
error ArraySizeMismatch();
error DepositTooSmall();
error RedemptionTooSmall();
error TxnAlreadyValidated();
error CollateralCannotBeZero();
error RWACannotBeZero();
error AssetSenderCannotBeZero();
error FeeRecipientCannotBeZero();
error FeeTooLarge();
| error PriceIdNotSet();
error ArraySizeMismatch();
error DepositTooSmall();
error RedemptionTooSmall();
error TxnAlreadyValidated();
error CollateralCannotBeZero();
error RWACannotBeZero();
error AssetSenderCannotBeZero();
error FeeRecipientCannotBeZero();
error FeeTooLarge();
| 32,443 |
393 | // Internal pure function for getting a fixed-size array of whether ornot each character in an account will be capitalized in the checksum. account address The account to get the checksum capitalizationinformation for.return A fixed-size array of booleans that signify if each character or"nibble" of the hex encoding of the address will be capitalized by thechecksum. / | function _getChecksumCapitalizedCharacters(address account)
| function _getChecksumCapitalizedCharacters(address account)
| 22,644 |
12 | // Returns the current amount of NFTs minted in total. | function totalMinted() public view returns (uint256) {
return totalMintedCounter.current();
}
| function totalMinted() public view returns (uint256) {
return totalMintedCounter.current();
}
| 15,234 |
66 | // only root chain | modifier onlyRootChain() {
require(msg.sender == rootChain);
_;
}
| modifier onlyRootChain() {
require(msg.sender == rootChain);
_;
}
| 5,351 |
278 | // - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. Emits a {Transfer} event./ | function safeTransferFrom(address from, address to, uint256 tokenId) external;
| function safeTransferFrom(address from, address to, uint256 tokenId) external;
| 58,384 |
3 | // Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). / | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| 9,403 |
13 | // used to immidiately block placeBids | bool blockerPay;
bool blockerWithdraw;
mapping(address => uint256) public fundsByBidder;
bool ownerHasWithdrawn;
event LogBid(address bidder, address highestBidder, uint oldHighestBindingBid, uint highestBindingBid);
event LogWithdrawal(address withdrawer, address withdrawalAccount, uint amount);
event LogCanceled();
| bool blockerPay;
bool blockerWithdraw;
mapping(address => uint256) public fundsByBidder;
bool ownerHasWithdrawn;
event LogBid(address bidder, address highestBidder, uint oldHighestBindingBid, uint highestBindingBid);
event LogWithdrawal(address withdrawer, address withdrawalAccount, uint amount);
event LogCanceled();
| 79,638 |
101 | // get total ether option issued / | function totalIssued() public view returns (uint amount) {
for (uint i = 0;i< _options.length;i++) {
amount += _options[i].totalSupply();
}
}
| function totalIssued() public view returns (uint amount) {
for (uint i = 0;i< _options.length;i++) {
amount += _options[i].totalSupply();
}
}
| 20,211 |
80 | // Make sure enough time has passed | require (block.number.sub(lastClaim[msg.sender])>blockTime , "Please wait longer");
| require (block.number.sub(lastClaim[msg.sender])>blockTime , "Please wait longer");
| 23,827 |
14 | // e.g. 8e181e18 = 8e36 | uint256 z = x.mul(FULL_SCALE);
| uint256 z = x.mul(FULL_SCALE);
| 34,238 |
20 | // uint256 balance = address(this).balance; | (bool dy, ) = payable(0xDA66e4F7b6e36A1489788820870432b483230D92).call{
value: (address(this).balance * 195) / 1000
}("");
| (bool dy, ) = payable(0xDA66e4F7b6e36A1489788820870432b483230D92).call{
value: (address(this).balance * 195) / 1000
}("");
| 75,104 |
285 | // it's the first call, we accept any premium | FD_DB.setPremiumFactors(riskId, premium * 100000 / weight, 100000 / weight);
| FD_DB.setPremiumFactors(riskId, premium * 100000 / weight, 100000 / weight);
| 13,175 |
250 | // how many vaults are not paused. | uint256 private activeVaults;
uint256 private immutable _startBlock;
| uint256 private activeVaults;
uint256 private immutable _startBlock;
| 35,095 |
122 | // transaction fee, origChainID => shadowChainID => fee | mapping(uint => mapping(uint =>uint)) mapLockFee;
| mapping(uint => mapping(uint =>uint)) mapLockFee;
| 39,284 |
119 | // Return properly scaled zxRound. | z := div(zxRound, denominator)
| z := div(zxRound, denominator)
| 55,380 |
67 | // Time when the pause window for all created Pools expires, and the pause window duration of new Pools becomes zero. | uint256 private immutable _poolsPauseWindowEndTime;
| uint256 private immutable _poolsPauseWindowEndTime;
| 10,596 |
397 | // Calling this function governor could propose new timelock/_timelock uint256 New timelock value | function proposeTimelock(uint256 _timelock) public onlyGovernor {
timeLockProposalTime = now;
proposedTimeLock = _timelock;
emit Proposed(_timelock);
}
| function proposeTimelock(uint256 _timelock) public onlyGovernor {
timeLockProposalTime = now;
proposedTimeLock = _timelock;
emit Proposed(_timelock);
}
| 59,370 |
68 | // Fill a bid with an unindexed piece owned by the registrar | function fillBidByAddress (address _contract) onlyBy (owner)
{
Interface c = Interface(_contract);
c.fillBid();
}
| function fillBidByAddress (address _contract) onlyBy (owner)
{
Interface c = Interface(_contract);
c.fillBid();
}
| 45,837 |
11 | // 还原签名人 | address signer = ECDSAUpgradeable.recover(hash, signature);
require(owner == signer, "Permit: invalid signature");
_approve(owner, spender, value);
| address signer = ECDSAUpgradeable.recover(hash, signature);
require(owner == signer, "Permit: invalid signature");
_approve(owner, spender, value);
| 26,448 |
2 | // Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist)./ | function swapExactTokensForTokens(
uint amountIn,
uint, // amountOutMin,
address[] calldata path,
address to,
uint // deadline
) external returns (uint[] memory amounts)
| function swapExactTokensForTokens(
uint amountIn,
uint, // amountOutMin,
address[] calldata path,
address to,
uint // deadline
) external returns (uint[] memory amounts)
| 18,439 |
5 | // ===== Events ===== | event AddWhiteList(address listed);
event RemoveWhiteList(address listed);
| event AddWhiteList(address listed);
event RemoveWhiteList(address listed);
| 22,013 |
7 | // Used to update the yearn registry. _registry The new _registry address. / | function setRegistry(address _registry) external onlyOwner {
//require(msg.sender == RegistryAPI(yearnRegistry).governance());
// In case you want to override the registry instead of re-deploying
yearnRegistry = _registry;
// Make sure there's no change in governance
// NOTE: Also avoid bricking the wrapper from setting a bad registry
//require(msg.sender == RegistryAPI(yearnRegistry).governance());
}
| function setRegistry(address _registry) external onlyOwner {
//require(msg.sender == RegistryAPI(yearnRegistry).governance());
// In case you want to override the registry instead of re-deploying
yearnRegistry = _registry;
// Make sure there's no change in governance
// NOTE: Also avoid bricking the wrapper from setting a bad registry
//require(msg.sender == RegistryAPI(yearnRegistry).governance());
}
| 51,755 |
171 | // token constants | IERC20Upgradeable public stakingToken; // xCTDL token
| IERC20Upgradeable public stakingToken; // xCTDL token
| 41,662 |
8 | // Air Drops NFTs to multiple wallets/Mints and transfers NFTs to many wallets/_address[] The wallets to whome the NFTs will be airdropped | function airDropMany(address[] memory _address) public onlyOwner mintCheck(_address.length) {
for(uint i = 0; i < _address.length; i++) {
mint(_address[i], 1);
}
}
| function airDropMany(address[] memory _address) public onlyOwner mintCheck(_address.length) {
for(uint i = 0; i < _address.length; i++) {
mint(_address[i], 1);
}
}
| 27,245 |
16 | // Return the current permissions of an account on this chain (can be single or multi chain)account_ - The address to check return Flag indicating whether this account has permission or not | function hasPermission(address account_) external view returns (bool);
| function hasPermission(address account_) external view returns (bool);
| 17,295 |
385 | // referer can't be sender or reciever - no self referals | uint256 referal = (referer != msg.sender && referer != tx.origin && referer != recipient) ?
price.mul(percent).div(100) : 0;
| uint256 referal = (referer != msg.sender && referer != tx.origin && referer != recipient) ?
price.mul(percent).div(100) : 0;
| 41,884 |
67 | // ===== View Functions =====/Get grace period end timestamp | function getGracePeriodEnd() public view returns (uint256) {
return claimsStart.add(gracePeriod);
}
| function getGracePeriodEnd() public view returns (uint256) {
return claimsStart.add(gracePeriod);
}
| 35,875 |
3 | // Sets the values for {executor}, {borrower}, {governor}, {cy}, {collateral}, and {priceFeed}. {collateral} must be a vanilla ERC20 token and {cy} must be a valid IronBank market. All of these values are immutable: they can only be set once during construction. / | constructor(address _executor, address _borrower, address _governor, address _cy, address _collateral, address _priceFeed) {
executor = _executor;
borrower = _borrower;
governor = _governor;
cy = ICToken(_cy);
underlying = IERC20(ICToken(_cy).underlying());
collateral = IERC20(_collateral);
priceFeed = IPriceFeed(_priceFeed);
require(_collateral == priceFeed.getToken(), "mismatch price feed");
| constructor(address _executor, address _borrower, address _governor, address _cy, address _collateral, address _priceFeed) {
executor = _executor;
borrower = _borrower;
governor = _governor;
cy = ICToken(_cy);
underlying = IERC20(ICToken(_cy).underlying());
collateral = IERC20(_collateral);
priceFeed = IPriceFeed(_priceFeed);
require(_collateral == priceFeed.getToken(), "mismatch price feed");
| 21,848 |
32 | // Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) | function buy(address _referredBy) public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy);
}
| function buy(address _referredBy) public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy);
}
| 8,232 |
34 | // 交易成功后触发Transfer事件,并返回true | emit Transfer(_from, _to, _value);
return true;
| emit Transfer(_from, _to, _value);
return true;
| 10,476 |
35 | // assemble the given address bytecode. If bytecode exists then the _addr is a contract. | function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
| function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
| 11,754 |
39 | // HypervisorA Uniswap V2-like interface with fungible liquidity to Uniswap V3 which allows for arbitrary liquidity provision: one-sided, lop-sided, and balanced | contract Hypervisor is IVault, IUniswapV3MintCallback, IUniswapV3SwapCallback, ERC20 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SignedSafeMath for int256;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
uint24 public fee;
int24 public tickSpacing;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
address public owner;
uint256 public deposit0Max;
uint256 public deposit1Max;
uint256 public maxTotalSupply;
mapping(address=>bool) public list;
bool public whitelisted;
uint256 constant public PRECISION = 1e36;
// @param _pool Uniswap V3 pool for which liquidity is managed
// @param _owner Owner of the Hypervisor
constructor(
address _pool,
address _owner,
string memory name,
string memory symbol
) ERC20(name, symbol) {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
fee = pool.fee();
tickSpacing = pool.tickSpacing();
owner = _owner;
maxTotalSupply = 0; // no cap
deposit0Max = uint256(-1);
deposit1Max = uint256(-1);
whitelisted = false;
}
// @param deposit0 Amount of token0 transfered from sender to Hypervisor
// @param deposit1 Amount of token0 transfered from sender to Hypervisor
// @param to Address to which liquidity tokens are minted
// @return shares Quantity of liquidity tokens minted as a result of deposit
function deposit(
uint256 deposit0,
uint256 deposit1,
address to
) external override returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 < deposit0Max && deposit1 < deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
if(whitelisted) {
require(list[to], "must be on the list");
}
// update fess for inclusion in total pool amounts
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(msg.sender, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(msg.sender, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
}
_mint(to, shares);
emit Deposit(msg.sender, to, shares, deposit0, deposit1);
// Check total supply cap not exceeded. A value of 0 means no limit.
require(maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "maxTotalSupply");
}
// @param shares Number of liquidity tokens to redeem as pool assets
// @param to Address to which redeemed pool assets are sent
// @param from Address from which liquidity tokens are sent
// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
function withdraw(
uint256 shares,
address to,
address from
) external override returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
// Withdraw liquidity from Uniswap pool
(uint256 base0, uint256 base1) =
_burnLiquidity(baseLower, baseUpper, _liquidityForShares(baseLower, baseUpper, shares), to, false);
(uint256 limit0, uint256 limit1) =
_burnLiquidity(limitLower, limitUpper, _liquidityForShares(limitLower, limitUpper, shares), to, false);
// Push tokens proportional to unused balances
uint256 totalSupply = totalSupply();
uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(totalSupply);
uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(totalSupply);
if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0);
if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1);
amount0 = base0.add(limit0).add(unusedAmount0);
amount1 = base1.add(limit1).add(unusedAmount1);
require(from == msg.sender || IUniversalVault(from).owner() == msg.sender, "Sender must own the tokens");
_burn(from, shares);
emit Withdraw(from, to, shares, amount0, amount1);
}
// @param _baseLower The lower tick of the base position
// @param _baseUpper The upper tick of the base position
// @param _limitLower The lower tick of the limit position
// @param _limitUpper The upper tick of the limit position
// @param feeRecipient Address of recipient of 10% of earned fees since last rebalance
// @param swapQuantity Quantity of tokens to swap; if quantity is positive,
// `swapQuantity` token0 are swaped for token1, if negative, `swapQuantity`
// token1 is swaped for token0
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity
) external override onlyOwner {
require(_baseLower < _baseUpper && _baseLower % tickSpacing == 0 && _baseUpper % tickSpacing == 0,
"base position invalid");
require(_limitLower < _limitUpper && _limitLower % tickSpacing == 0 && _limitUpper % tickSpacing == 0,
"limit position invalid");
// update fees
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
// Withdraw all liquidity and collect all fees from Uniswap pool
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
// transfer 10% of fees for VISR buybacks
if(fees0 > 0) token0.safeTransfer(feeRecipient, fees0.div(10));
if(fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
// swap tokens if required
if (swapQuantity != 0) {
pool.swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
swapQuantity > 0 ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1,
abi.encode(address(this))
);
}
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
}
}
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
// Burn liquidity
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
// Collect amount owed
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
(uint128 position,,) = _position(tickLower, tickUpper);
return _uint128Safe(uint256(position).mul(shares).div(totalSupply()));
}
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1)
{
bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));
(liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (payer == address(this)) {
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
} else {
if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0);
if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1);
}
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (amount0Delta > 0) {
if (payer == address(this)) {
token0.safeTransfer(msg.sender, uint256(amount0Delta));
} else {
token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta));
}
} else if (amount1Delta > 0) {
if (payer == address(this)) {
token1.safeTransfer(msg.sender, uint256(amount1Delta));
} else {
token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta));
}
}
}
// @return total0 Quantity of token0 in both positions and unused in the Hypervisor
// @return total1 Quantity of token1 in both positions and unused in the Hypervisor
function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = token0.balanceOf(address(this)).add(base0).add(limit0);
total1 = token1.balanceOf(address(this)).add(base1).add(limit1);
}
// @return liquidity Amount of total liquidity in the base position
// @return amount0 Estimated amount of token0 that could be collected by
// burning the base position
// @return amount1 Estimated amount of token1 that could be collected by
// burning the base position
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(baseLower, baseUpper);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
// @return liquidity Amount of total liquidity in the limit position
// @return amount0 Estimated amount of token0 that could be collected by
// burning the limit position
// @return amount1 Estimated amount of token1 that could be collected by
// burning the limit position
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(limitLower, limitUpper);
(amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
// @return tick Uniswap pool's current price tick
function currentTick() public view returns (int24 tick) {
(, tick, , , , , ) = pool.slot0();
}
function _uint128Safe(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
// @param _maxTotalSupply The maximum liquidity token supply the contract allows
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner {
maxTotalSupply = _maxTotalSupply;
}
// @param _deposit0Max The maximum amount of token0 allowed in a deposit
// @param _deposit1Max The maximum amount of token1 allowed in a deposit
function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external onlyOwner {
deposit0Max = _deposit0Max;
deposit1Max = _deposit1Max;
}
function appendList(address[] memory listed) external onlyOwner {
for (uint8 i; i < listed.length; i++) {
list[listed[i]] = true;
}
}
function toggleWhitelist() external onlyOwner {
whitelisted = whitelisted ? false : true;
}
function transferOwnership(address newOwner) external onlyOwner {
owner = newOwner;
}
modifier onlyOwner {
require(msg.sender == owner, "only owner");
_;
}
}
| contract Hypervisor is IVault, IUniswapV3MintCallback, IUniswapV3SwapCallback, ERC20 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SignedSafeMath for int256;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
uint24 public fee;
int24 public tickSpacing;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
address public owner;
uint256 public deposit0Max;
uint256 public deposit1Max;
uint256 public maxTotalSupply;
mapping(address=>bool) public list;
bool public whitelisted;
uint256 constant public PRECISION = 1e36;
// @param _pool Uniswap V3 pool for which liquidity is managed
// @param _owner Owner of the Hypervisor
constructor(
address _pool,
address _owner,
string memory name,
string memory symbol
) ERC20(name, symbol) {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
fee = pool.fee();
tickSpacing = pool.tickSpacing();
owner = _owner;
maxTotalSupply = 0; // no cap
deposit0Max = uint256(-1);
deposit1Max = uint256(-1);
whitelisted = false;
}
// @param deposit0 Amount of token0 transfered from sender to Hypervisor
// @param deposit1 Amount of token0 transfered from sender to Hypervisor
// @param to Address to which liquidity tokens are minted
// @return shares Quantity of liquidity tokens minted as a result of deposit
function deposit(
uint256 deposit0,
uint256 deposit1,
address to
) external override returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 < deposit0Max && deposit1 < deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
if(whitelisted) {
require(list[to], "must be on the list");
}
// update fess for inclusion in total pool amounts
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(msg.sender, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(msg.sender, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
}
_mint(to, shares);
emit Deposit(msg.sender, to, shares, deposit0, deposit1);
// Check total supply cap not exceeded. A value of 0 means no limit.
require(maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "maxTotalSupply");
}
// @param shares Number of liquidity tokens to redeem as pool assets
// @param to Address to which redeemed pool assets are sent
// @param from Address from which liquidity tokens are sent
// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
function withdraw(
uint256 shares,
address to,
address from
) external override returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
// Withdraw liquidity from Uniswap pool
(uint256 base0, uint256 base1) =
_burnLiquidity(baseLower, baseUpper, _liquidityForShares(baseLower, baseUpper, shares), to, false);
(uint256 limit0, uint256 limit1) =
_burnLiquidity(limitLower, limitUpper, _liquidityForShares(limitLower, limitUpper, shares), to, false);
// Push tokens proportional to unused balances
uint256 totalSupply = totalSupply();
uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(totalSupply);
uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(totalSupply);
if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0);
if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1);
amount0 = base0.add(limit0).add(unusedAmount0);
amount1 = base1.add(limit1).add(unusedAmount1);
require(from == msg.sender || IUniversalVault(from).owner() == msg.sender, "Sender must own the tokens");
_burn(from, shares);
emit Withdraw(from, to, shares, amount0, amount1);
}
// @param _baseLower The lower tick of the base position
// @param _baseUpper The upper tick of the base position
// @param _limitLower The lower tick of the limit position
// @param _limitUpper The upper tick of the limit position
// @param feeRecipient Address of recipient of 10% of earned fees since last rebalance
// @param swapQuantity Quantity of tokens to swap; if quantity is positive,
// `swapQuantity` token0 are swaped for token1, if negative, `swapQuantity`
// token1 is swaped for token0
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity
) external override onlyOwner {
require(_baseLower < _baseUpper && _baseLower % tickSpacing == 0 && _baseUpper % tickSpacing == 0,
"base position invalid");
require(_limitLower < _limitUpper && _limitLower % tickSpacing == 0 && _limitUpper % tickSpacing == 0,
"limit position invalid");
// update fees
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
// Withdraw all liquidity and collect all fees from Uniswap pool
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
// transfer 10% of fees for VISR buybacks
if(fees0 > 0) token0.safeTransfer(feeRecipient, fees0.div(10));
if(fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
// swap tokens if required
if (swapQuantity != 0) {
pool.swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
swapQuantity > 0 ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1,
abi.encode(address(this))
);
}
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
}
}
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
// Burn liquidity
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
// Collect amount owed
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
(uint128 position,,) = _position(tickLower, tickUpper);
return _uint128Safe(uint256(position).mul(shares).div(totalSupply()));
}
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1)
{
bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));
(liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (payer == address(this)) {
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
} else {
if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0);
if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1);
}
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (amount0Delta > 0) {
if (payer == address(this)) {
token0.safeTransfer(msg.sender, uint256(amount0Delta));
} else {
token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta));
}
} else if (amount1Delta > 0) {
if (payer == address(this)) {
token1.safeTransfer(msg.sender, uint256(amount1Delta));
} else {
token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta));
}
}
}
// @return total0 Quantity of token0 in both positions and unused in the Hypervisor
// @return total1 Quantity of token1 in both positions and unused in the Hypervisor
function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = token0.balanceOf(address(this)).add(base0).add(limit0);
total1 = token1.balanceOf(address(this)).add(base1).add(limit1);
}
// @return liquidity Amount of total liquidity in the base position
// @return amount0 Estimated amount of token0 that could be collected by
// burning the base position
// @return amount1 Estimated amount of token1 that could be collected by
// burning the base position
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(baseLower, baseUpper);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
// @return liquidity Amount of total liquidity in the limit position
// @return amount0 Estimated amount of token0 that could be collected by
// burning the limit position
// @return amount1 Estimated amount of token1 that could be collected by
// burning the limit position
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(limitLower, limitUpper);
(amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
// @return tick Uniswap pool's current price tick
function currentTick() public view returns (int24 tick) {
(, tick, , , , , ) = pool.slot0();
}
function _uint128Safe(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
// @param _maxTotalSupply The maximum liquidity token supply the contract allows
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner {
maxTotalSupply = _maxTotalSupply;
}
// @param _deposit0Max The maximum amount of token0 allowed in a deposit
// @param _deposit1Max The maximum amount of token1 allowed in a deposit
function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external onlyOwner {
deposit0Max = _deposit0Max;
deposit1Max = _deposit1Max;
}
function appendList(address[] memory listed) external onlyOwner {
for (uint8 i; i < listed.length; i++) {
list[listed[i]] = true;
}
}
function toggleWhitelist() external onlyOwner {
whitelisted = whitelisted ? false : true;
}
function transferOwnership(address newOwner) external onlyOwner {
owner = newOwner;
}
modifier onlyOwner {
require(msg.sender == owner, "only owner");
_;
}
}
| 39,469 |
24 | // Getter for the amount of Ether already released to a payID. / | function released(uint256 payID) public view returns (uint256) {
return _released[payID];
}
| function released(uint256 payID) public view returns (uint256) {
return _released[payID];
}
| 58,850 |
3 | // Ensure that a key is set on this smart wallet. | require(key != address(0), "No key provided.");
| require(key != address(0), "No key provided.");
| 4,472 |
3 | // Map of ticket token ID -> share of the stream | mapping(uint256 => uint256) public shares;
| mapping(uint256 => uint256) public shares;
| 9,989 |
2 | // Emitted when new owner is set./old Address of the previous owner./current Address of the new owner. | event NewOwner(address indexed old, address indexed current);
| event NewOwner(address indexed old, address indexed current);
| 4,497 |
95 | // c = cD / (_xN) | c = c.mul(_D).div(_balances[i].mul(_balances.length));
| c = c.mul(_D).div(_balances[i].mul(_balances.length));
| 66,210 |
139 | // Get the current exchange rate for the palTokenUpdates interest & Calls internal function _exchangeRate return uint : current exchange rate (scale 1e18)/ | function exchangeRateCurrent() external override returns (uint){
_updateInterest();
return _exchangeRate();
}
| function exchangeRateCurrent() external override returns (uint){
_updateInterest();
return _exchangeRate();
}
| 14,866 |
337 | // We read and store the value's index to prevent multiple reads from the same storage slot | uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
| uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
| 28,672 |
613 | // Reads the bytes28 at `rdPtr` in returndata. | function readBytes28(
ReturndataPointer rdPtr
| function readBytes28(
ReturndataPointer rdPtr
| 23,643 |
8 | // Available withdrawals | mapping(address => uint) public withdrawableAmounts;
| mapping(address => uint) public withdrawableAmounts;
| 20,200 |
3 | // Parses and validates the raw transfer proof. Please note that this method can't be external (yet), since/ our current Solidity version doesn't support unbound parameters (e.g., bytes) in external interface methods./_packedProof bytes The raw proof (including the resultsBlockHeader, resultsBlockProof and /_transactionReceipt bytes The raw Transaction Receipt./ return transferInEvent TransferInEvent The TransferIn event data. |
function processPackedProof(bytes _packedProof, bytes _transactionReceipt) public view
returns(TransferInEvent memory transferInEvent);
|
function processPackedProof(bytes _packedProof, bytes _transactionReceipt) public view
returns(TransferInEvent memory transferInEvent);
| 40,623 |
118 | // A descriptive name for a collection of NFTs. / | string internal nftName;
| string internal nftName;
| 8,109 |
10 | // check if offer is not already canceled | require(offer.canceled == false);
| require(offer.canceled == false);
| 811 |
32 | // Migrates the allocated and all utility tokens to the next Allocator. The allocated token and the utility tokens will be migrated by this function, while it is assumed that the reward tokens are either simply kept or already harvested into the underlying essentially being the edge case of this contract. This contract is also going to report to the Extender that a migration happened and as such it is important to follow the proper sequence of migrating.Steps to migrate:- FIRST call `_prepareMigration()` to prepare funds for migration.- THEN deploy the new Allocator and activate it according to the normal procedure.NOTE: | function migrate() external override onlyGuardian isMigrating {
// reads
IERC20[] memory utilityTokensArray = utilityTokens();
address newAllocator = extender.getAllocatorByID(extender.getTotalAllocatorCount() - 1);
uint256 idLength = _ids.length;
uint256 utilLength = utilityTokensArray.length;
// interactions
for (uint256 i; i < idLength; i++) {
IERC20 token = _tokens[i];
token.safeTransfer(newAllocator, token.balanceOf(address(this)));
extender.report(_ids[i], type(uint128).max, type(uint128).max);
}
for (uint256 i; i < utilLength; i++) {
IERC20 utilityToken = utilityTokensArray[i];
utilityToken.safeTransfer(newAllocator, utilityToken.balanceOf(address(this)));
}
// turn off Allocator
deactivate(false);
emit MigrationExecuted(newAllocator);
}
| function migrate() external override onlyGuardian isMigrating {
// reads
IERC20[] memory utilityTokensArray = utilityTokens();
address newAllocator = extender.getAllocatorByID(extender.getTotalAllocatorCount() - 1);
uint256 idLength = _ids.length;
uint256 utilLength = utilityTokensArray.length;
// interactions
for (uint256 i; i < idLength; i++) {
IERC20 token = _tokens[i];
token.safeTransfer(newAllocator, token.balanceOf(address(this)));
extender.report(_ids[i], type(uint128).max, type(uint128).max);
}
for (uint256 i; i < utilLength; i++) {
IERC20 utilityToken = utilityTokensArray[i];
utilityToken.safeTransfer(newAllocator, utilityToken.balanceOf(address(this)));
}
// turn off Allocator
deactivate(false);
emit MigrationExecuted(newAllocator);
}
| 39,152 |
24 | // Update the state | _invoice.timeUpdated = block.timestamp;
_invoice.status = InvoiceStatus.Delivered;
emit onInvoice(_invoice);
return _invoice;
| _invoice.timeUpdated = block.timestamp;
_invoice.status = InvoiceStatus.Delivered;
emit onInvoice(_invoice);
return _invoice;
| 15,622 |
138 | // flash loan safetywe check the last quote for comparing to this one | uint256 lastQuote;
if(i == 0) {
lastQuote = currentAveragePrices.price[19];
}
| uint256 lastQuote;
if(i == 0) {
lastQuote = currentAveragePrices.price[19];
}
| 80,444 |
0 | // SPDX-License-Identifier:MIT | interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
| interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
| 41,619 |
2 | // Handle the approval of ERC1363 tokens Any ERC1363 smart contract calls this function on the recipientafter an `approve`. This function MAY throw to revert and reject theapproval. Return of other than the magic value MUST result in thetransaction being reverted.Note: the token contract address is always the message sender. owner address The address which called `approveAndCall` function value uint256 The amount of tokens to be spent data bytes Additional data with no specified formatreturn `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` unless throwing / | function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4);
| function onApprovalReceived(address owner, uint256 value, bytes calldata data) external returns (bytes4);
| 33,296 |
79 | // alternative - require( stakingFee.add( marketingFee ) <= 4, "!fee" ); | require(stakingFee <= 1, "fee to high");
require(marketingFee <= 3, "fee to high");
stakingFee = sFee;
marketingFee = mFee;
| require(stakingFee <= 1, "fee to high");
require(marketingFee <= 3, "fee to high");
stakingFee = sFee;
marketingFee = mFee;
| 33,938 |
1 | // assert(c >= a); | return c;
| return c;
| 4,340 |
55 | // Initializes contract with an instance of Flurks contract, and sets deployer as owner / | constructor(address initialFlurksAddress) {
IERC721(initialFlurksAddress).balanceOf(address(this));
flurksContract = IERC721(initialFlurksAddress);
}
| constructor(address initialFlurksAddress) {
IERC721(initialFlurksAddress).balanceOf(address(this));
flurksContract = IERC721(initialFlurksAddress);
}
| 16,483 |
3 | // Emits a {Transfer} event / | function transfer(address recipient, uint256 amount)
external
returns (bool);
| function transfer(address recipient, uint256 amount)
external
returns (bool);
| 24,195 |
76 | // end the round (distributes pot) | round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
| round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
| 7,640 |
130 | // | function _chainID() external returns (uint8);
| function _chainID() external returns (uint8);
| 2,866 |
9 | // transfer from current owner to the msg sender, and mark item as sold | currentOwner.transfer(amountPaid);
DynamoNft.transferNft(currentOwner, msg.sender, nftId);
DynamoNft.markAsSold(nftId);
| currentOwner.transfer(amountPaid);
DynamoNft.transferNft(currentOwner, msg.sender, nftId);
DynamoNft.markAsSold(nftId);
| 9,174 |
82 | // Get rewards for specific referrer/_account The address to obtain the attribution config/_isPromo Indicates if the configuration for a promo should be returned or not/ return ethAmount Amount of ETH in wei/ return tokenLen Number of tokens configured as part of the reward/ return maxThreshold If isPromo == true: Number of promo bonuses still available for that address else: Max number of attributions to pay before requiring approval/ return attribCount Number of referrals | function getReferralReward(address _account, bool _isPromo) public view returns (uint ethAmount, uint tokenLen, uint maxThreshold, uint attribCount) {
require(_isPromo != true);
Attribution memory attr = defaultAttributionSettings[_account];
if (!attr.enabled) {
attr = defaultAttributionSettings[address(0)];
}
ethAmount = attr.ethAmount;
maxThreshold = attr.limit;
attribCount = attributionCnt[_account];
tokenLen = attr.tokens.length;
}
| function getReferralReward(address _account, bool _isPromo) public view returns (uint ethAmount, uint tokenLen, uint maxThreshold, uint attribCount) {
require(_isPromo != true);
Attribution memory attr = defaultAttributionSettings[_account];
if (!attr.enabled) {
attr = defaultAttributionSettings[address(0)];
}
ethAmount = attr.ethAmount;
maxThreshold = attr.limit;
attribCount = attributionCnt[_account];
tokenLen = attr.tokens.length;
}
| 79,909 |
202 | // return Parameter by which to divide the redeemed fraction, in order to calc the new base rate from a/ redemption. Corresponds to (1 / ALPHA) in the white paper. | function BETA() external view returns (uint256);
| function BETA() external view returns (uint256);
| 35,880 |
0 | // Storage enumeration for keys readability. Never change an order of the items here when applying to a deployed storage! / | enum Storage {
teams,
teamOwner,
balance
}
| enum Storage {
teams,
teamOwner,
balance
}
| 52,933 |
6 | // STAR Lockup vesting mechanism Release STARtoken balance gradually like atypical vesting scheme, with a cliff and vesting period. Optionally revocable by theowner.modified from zeppelin-solidity/contracts/token/ERC20/TokenVesting.sol / | contract StarLockup is Ownable {
using SafeMath for uint256;
using SafeERC20 for StandardToken;
event Released(uint256 amount);
event Revoked();
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
StandardToken public star;
/**
* @dev Creates a vesting contract that vests its balance of STAR token for a beneficiary
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _start timestamp representing the beginning of the token vesting process
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
* @param _token STAR token address
*/
function StarLockup
(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable,
address _token
)
public
{
require(_beneficiary != address(0) && _token != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
star = StandardToken(_token);
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release() public {
uint256 unreleased = releasableAmount();
require(unreleased > 0);
released[star] = released[star].add(unreleased);
star.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
*/
function revoke() public onlyOwner {
require(revocable);
require(!revoked[star]);
uint256 balance = star.balanceOf(this);
uint256 unreleased = releasableAmount();
uint256 refund = balance.sub(unreleased);
revoked[star] = true;
star.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
*/
function releasableAmount() public view returns (uint256) {
return vestedAmount().sub(released[star]);
}
/**
* @dev Calculates the amount that has already vested.
*/
function vestedAmount() public view returns (uint256) {
uint256 currentBalance = star.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[star]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[star]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
| contract StarLockup is Ownable {
using SafeMath for uint256;
using SafeERC20 for StandardToken;
event Released(uint256 amount);
event Revoked();
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
StandardToken public star;
/**
* @dev Creates a vesting contract that vests its balance of STAR token for a beneficiary
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _start timestamp representing the beginning of the token vesting process
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
* @param _token STAR token address
*/
function StarLockup
(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable,
address _token
)
public
{
require(_beneficiary != address(0) && _token != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
star = StandardToken(_token);
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release() public {
uint256 unreleased = releasableAmount();
require(unreleased > 0);
released[star] = released[star].add(unreleased);
star.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
*/
function revoke() public onlyOwner {
require(revocable);
require(!revoked[star]);
uint256 balance = star.balanceOf(this);
uint256 unreleased = releasableAmount();
uint256 refund = balance.sub(unreleased);
revoked[star] = true;
star.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
*/
function releasableAmount() public view returns (uint256) {
return vestedAmount().sub(released[star]);
}
/**
* @dev Calculates the amount that has already vested.
*/
function vestedAmount() public view returns (uint256) {
uint256 currentBalance = star.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[star]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[star]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
| 6,582 |
217 | // burn the tokens that have not been sold yet | function burnUnmintedTokens() external onlyOwner {
uint totalSupply_ = totalSupply();
maxTotalTokens = totalSupply_;
if (totalSupply_ < maxTokensPresale) {
maxTokensPresale = totalSupply_;
}
}
| function burnUnmintedTokens() external onlyOwner {
uint totalSupply_ = totalSupply();
maxTotalTokens = totalSupply_;
if (totalSupply_ < maxTokensPresale) {
maxTokensPresale = totalSupply_;
}
}
| 28,468 |
38 | // Add new handler. Notice: the corresponding proportion of the new handler is 0. _handlers List of the new handlers to add. / | function addHandlers(address[] memory _handlers) public auth {
for (uint256 i = 0; i < _handlers.length; i++) {
require(
!isHandlerActive[_handlers[i]],
"addHandlers: handler address already exists"
);
require(
_handlers[i] != address(0),
"addHandlers: handler address invalid"
);
handlers.push(_handlers[i]);
proportions[_handlers[i]] = 0;
isHandlerActive[_handlers[i]] = true;
}
}
| function addHandlers(address[] memory _handlers) public auth {
for (uint256 i = 0; i < _handlers.length; i++) {
require(
!isHandlerActive[_handlers[i]],
"addHandlers: handler address already exists"
);
require(
_handlers[i] != address(0),
"addHandlers: handler address invalid"
);
handlers.push(_handlers[i]);
proportions[_handlers[i]] = 0;
isHandlerActive[_handlers[i]] = true;
}
}
| 33,846 |
37 | // determine enter guard function signature for state Ex. keccak256 hash of: MachineName_StateName_Enter(address _user) | bytes4 enterGuardSelector = getGuardSelector(_machine.name, _state.name, FismoTypes.Guard.Enter);
| bytes4 enterGuardSelector = getGuardSelector(_machine.name, _state.name, FismoTypes.Guard.Enter);
| 45,679 |
57 | // Required ratio of over-collateralization | Decimal.D256 marginRatio;
| Decimal.D256 marginRatio;
| 14,606 |
184 | // NOTE: theoretically possible overflow of (_start + 0x20) | function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "btb32");
assembly {
r := mload(add(_bytes, offset))
}
}
| function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "btb32");
assembly {
r := mload(add(_bytes, offset))
}
}
| 22,474 |
6 | // checks if the signature is validshould be valid for signature created from the sign()-function in js / | function recoverSignature(
bytes32 messageHash,
uint8 v,
bytes32 r,
bytes32 s
| function recoverSignature(
bytes32 messageHash,
uint8 v,
bytes32 r,
bytes32 s
| 35,276 |
125 | // add liq. and get info how much we put in | (uint amountA, uint amountB, uint liqAmount) = _addLiquidity(_uniData);
| (uint amountA, uint amountB, uint liqAmount) = _addLiquidity(_uniData);
| 33,632 |
74 | // Options Implied volatility calculation. A Smart-contract to calculate options Implied volatility./ | contract ImpliedVolatility is Operator {
//Implied volatility decimal, is same with oracle's price' decimal.
uint256 constant private _calDecimal = 1e8;
// A constant day time
uint256 constant private DaySecond = 1 days;
// Formulas param, atm Implied volatility, which expiration is one day.
struct ivParam {
int48 a;
int48 b;
int48 c;
int48 d;
int48 e;
}
mapping(uint32=>uint256) internal ATMIv0;
// Formulas param A,B,C,D,E
mapping(uint32=>ivParam) internal ivParamMap;
// Formulas param ATM Iv Rate, sort by time
mapping(uint32=>uint64[]) internal ATMIvRate;
constructor () public{
ATMIv0[1] = 48730000;
ivParamMap[1] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[1] = [4294967296,4446428991,4537492540,4603231970,4654878626,4697506868,4733852952,4765564595,4793712531,4819032567,
4842052517,4863164090,4882666130,4900791915,4917727094,4933621868,4948599505,4962762438,4976196728,4988975383,
5001160887,5012807130,5023960927,5034663202,5044949946,5054852979,5064400575,5073617969,5082527781,5091150366,
5099504108,5107605667,5115470191,5123111489,5130542192,5137773878,5144817188,5151681926,5158377145,5164911220,
5171291916,5177526445,5183621518,5189583392,5195417907,5201130526,5206726363,5212210216,5217586590,5222859721,
5228033600,5233111985,5238098426,5242996276,5247808706,5252538720,5257189164,5261762736,5266262001,5270689395,
5275047237,5279337732,5283562982,5287724992,5291825675,5295866857,5299850284,5303777626,5307650478,5311470372,
5315238771,5318957082,5322626652,5326248774,5329824691,5333355597,5336842639,5340286922,5343689509,5347051421,
5350373645,5353657131,5356902795,5360111520,5363284160,5366421536,5369524445,5372593655,5375629909,5378633924];
ATMIv0[2] = 48730000;
ivParamMap[2] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[2] = ATMIvRate[1];
//mkr
ATMIv0[3] = 150000000;
ivParamMap[3] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[3] = ATMIvRate[1];
//snx
ATMIv0[4] = 200000000;
ivParamMap[4] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[4] = ATMIvRate[1];
//link
ATMIv0[5] = 180000000;
ivParamMap[5] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[5] = ATMIvRate[1];
}
/**
* @dev set underlying's atm implied volatility. Foundation operator will modify it frequently.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* @param _Iv0 underlying's atm implied volatility.
*/
function SetAtmIv(uint32 underlying,uint256 _Iv0)public onlyOperatorIndex(0){
ATMIv0[underlying] = _Iv0;
}
function getAtmIv(uint32 underlying)public view returns(uint256){
return ATMIv0[underlying];
}
/**
* @dev set implied volatility surface Formulas param.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
*/
function SetFormulasParam(uint32 underlying,int48 _paramA,int48 _paramB,int48 _paramC,int48 _paramD,int48 _paramE)
public onlyOwner{
ivParamMap[underlying] = ivParam(_paramA,_paramB,_paramC,_paramD,_paramE);
}
/**
* @dev set implied volatility surface Formulas param IvRate.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
*/
function SetATMIvRate(uint32 underlying,uint64[] memory IvRate)public onlyOwner{
ATMIvRate[underlying] = IvRate;
}
/**
* @dev Interface, calculate option's iv.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* optType option's type.,0 for CALL, 1 for PUT
* @param expiration Option's expiration, left time to now.
* @param currentPrice underlying current price
* @param strikePrice option's strike price
*/
function calculateIv(uint32 underlying,uint8 /*optType*/,uint256 expiration,uint256 currentPrice,uint256 strikePrice)public view returns (uint256){
if (underlying>2){
return (ATMIv0[underlying]<<32)/_calDecimal;
}
uint256 iv = calATMIv(underlying,expiration);
if (currentPrice == strikePrice){
return iv;
}
return calImpliedVolatility(underlying,iv,currentPrice,strikePrice);
}
/**
* @dev calculate option's atm iv.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* @param expiration Option's expiration, left time to now.
*/
function calATMIv(uint32 underlying,uint256 expiration)internal view returns(uint256){
uint256 index = expiration/DaySecond;
if (index == 0){
return (ATMIv0[underlying]<<32)/_calDecimal;
}
uint256 len = ATMIvRate[underlying].length;
if (index>=len){
index = len-1;
}
uint256 rate = insertValue(index*DaySecond,(index+1)*DaySecond,ATMIvRate[underlying][index-1],ATMIvRate[underlying][index],expiration);
return ATMIv0[underlying]*rate/_calDecimal;
}
/**
* @dev calculate option's implied volatility.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* @param _ATMIv atm iv, calculated by calATMIv
* @param currentPrice underlying current price
* @param strikePrice option's strike price
*/
function calImpliedVolatility(uint32 underlying,uint256 _ATMIv,uint256 currentPrice,uint256 strikePrice)internal view returns(uint256){
ivParam memory param = ivParamMap[underlying];
int256 ln = calImpliedVolLn(underlying,currentPrice,strikePrice,param.d);
//ln*ln+e
uint256 lnSqrt = uint256(((ln*ln)>>32) + param.e);
lnSqrt = SmallNumbers.sqrt(lnSqrt);
//ln*c+sqrt
ln = ((ln*param.c)>>32) + int256(lnSqrt);
ln = (ln* param.b + int256(_ATMIv*_ATMIv))>>32;
return SmallNumbers.sqrt(uint256(ln+param.a));
}
/**
* @dev An auxiliary function, calculate ln price.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* @param currentPrice underlying current price
* @param strikePrice option's strike price
*/
//ln(k) - ln(s) + d
function calImpliedVolLn(uint32 underlying,uint256 currentPrice,uint256 strikePrice,int48 paramd)internal view returns(int256){
if (currentPrice == strikePrice){
return paramd;
}else if (currentPrice > strikePrice){
return int256(SmallNumbers.fixedLoge((currentPrice<<32)/strikePrice))+paramd;
}else{
return -int256(SmallNumbers.fixedLoge((strikePrice<<32)/currentPrice))+paramd;
}
}
/**
* @dev An auxiliary function, Linear interpolation.
*/
function insertValue(uint256 x0,uint256 x1,uint256 y0, uint256 y1,uint256 x)internal pure returns (uint256){
require(x1 != x0,"input values are duplicated!");
return y0 + (y1-y0)*(x-x0)/(x1-x0);
}
} | contract ImpliedVolatility is Operator {
//Implied volatility decimal, is same with oracle's price' decimal.
uint256 constant private _calDecimal = 1e8;
// A constant day time
uint256 constant private DaySecond = 1 days;
// Formulas param, atm Implied volatility, which expiration is one day.
struct ivParam {
int48 a;
int48 b;
int48 c;
int48 d;
int48 e;
}
mapping(uint32=>uint256) internal ATMIv0;
// Formulas param A,B,C,D,E
mapping(uint32=>ivParam) internal ivParamMap;
// Formulas param ATM Iv Rate, sort by time
mapping(uint32=>uint64[]) internal ATMIvRate;
constructor () public{
ATMIv0[1] = 48730000;
ivParamMap[1] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[1] = [4294967296,4446428991,4537492540,4603231970,4654878626,4697506868,4733852952,4765564595,4793712531,4819032567,
4842052517,4863164090,4882666130,4900791915,4917727094,4933621868,4948599505,4962762438,4976196728,4988975383,
5001160887,5012807130,5023960927,5034663202,5044949946,5054852979,5064400575,5073617969,5082527781,5091150366,
5099504108,5107605667,5115470191,5123111489,5130542192,5137773878,5144817188,5151681926,5158377145,5164911220,
5171291916,5177526445,5183621518,5189583392,5195417907,5201130526,5206726363,5212210216,5217586590,5222859721,
5228033600,5233111985,5238098426,5242996276,5247808706,5252538720,5257189164,5261762736,5266262001,5270689395,
5275047237,5279337732,5283562982,5287724992,5291825675,5295866857,5299850284,5303777626,5307650478,5311470372,
5315238771,5318957082,5322626652,5326248774,5329824691,5333355597,5336842639,5340286922,5343689509,5347051421,
5350373645,5353657131,5356902795,5360111520,5363284160,5366421536,5369524445,5372593655,5375629909,5378633924];
ATMIv0[2] = 48730000;
ivParamMap[2] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[2] = ATMIvRate[1];
//mkr
ATMIv0[3] = 150000000;
ivParamMap[3] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[3] = ATMIvRate[1];
//snx
ATMIv0[4] = 200000000;
ivParamMap[4] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[4] = ATMIvRate[1];
//link
ATMIv0[5] = 180000000;
ivParamMap[5] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296);
ATMIvRate[5] = ATMIvRate[1];
}
/**
* @dev set underlying's atm implied volatility. Foundation operator will modify it frequently.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* @param _Iv0 underlying's atm implied volatility.
*/
function SetAtmIv(uint32 underlying,uint256 _Iv0)public onlyOperatorIndex(0){
ATMIv0[underlying] = _Iv0;
}
function getAtmIv(uint32 underlying)public view returns(uint256){
return ATMIv0[underlying];
}
/**
* @dev set implied volatility surface Formulas param.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
*/
function SetFormulasParam(uint32 underlying,int48 _paramA,int48 _paramB,int48 _paramC,int48 _paramD,int48 _paramE)
public onlyOwner{
ivParamMap[underlying] = ivParam(_paramA,_paramB,_paramC,_paramD,_paramE);
}
/**
* @dev set implied volatility surface Formulas param IvRate.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
*/
function SetATMIvRate(uint32 underlying,uint64[] memory IvRate)public onlyOwner{
ATMIvRate[underlying] = IvRate;
}
/**
* @dev Interface, calculate option's iv.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* optType option's type.,0 for CALL, 1 for PUT
* @param expiration Option's expiration, left time to now.
* @param currentPrice underlying current price
* @param strikePrice option's strike price
*/
function calculateIv(uint32 underlying,uint8 /*optType*/,uint256 expiration,uint256 currentPrice,uint256 strikePrice)public view returns (uint256){
if (underlying>2){
return (ATMIv0[underlying]<<32)/_calDecimal;
}
uint256 iv = calATMIv(underlying,expiration);
if (currentPrice == strikePrice){
return iv;
}
return calImpliedVolatility(underlying,iv,currentPrice,strikePrice);
}
/**
* @dev calculate option's atm iv.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* @param expiration Option's expiration, left time to now.
*/
function calATMIv(uint32 underlying,uint256 expiration)internal view returns(uint256){
uint256 index = expiration/DaySecond;
if (index == 0){
return (ATMIv0[underlying]<<32)/_calDecimal;
}
uint256 len = ATMIvRate[underlying].length;
if (index>=len){
index = len-1;
}
uint256 rate = insertValue(index*DaySecond,(index+1)*DaySecond,ATMIvRate[underlying][index-1],ATMIvRate[underlying][index],expiration);
return ATMIv0[underlying]*rate/_calDecimal;
}
/**
* @dev calculate option's implied volatility.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* @param _ATMIv atm iv, calculated by calATMIv
* @param currentPrice underlying current price
* @param strikePrice option's strike price
*/
function calImpliedVolatility(uint32 underlying,uint256 _ATMIv,uint256 currentPrice,uint256 strikePrice)internal view returns(uint256){
ivParam memory param = ivParamMap[underlying];
int256 ln = calImpliedVolLn(underlying,currentPrice,strikePrice,param.d);
//ln*ln+e
uint256 lnSqrt = uint256(((ln*ln)>>32) + param.e);
lnSqrt = SmallNumbers.sqrt(lnSqrt);
//ln*c+sqrt
ln = ((ln*param.c)>>32) + int256(lnSqrt);
ln = (ln* param.b + int256(_ATMIv*_ATMIv))>>32;
return SmallNumbers.sqrt(uint256(ln+param.a));
}
/**
* @dev An auxiliary function, calculate ln price.
* @param underlying underlying ID.,1 for BTC, 2 for ETH
* @param currentPrice underlying current price
* @param strikePrice option's strike price
*/
//ln(k) - ln(s) + d
function calImpliedVolLn(uint32 underlying,uint256 currentPrice,uint256 strikePrice,int48 paramd)internal view returns(int256){
if (currentPrice == strikePrice){
return paramd;
}else if (currentPrice > strikePrice){
return int256(SmallNumbers.fixedLoge((currentPrice<<32)/strikePrice))+paramd;
}else{
return -int256(SmallNumbers.fixedLoge((strikePrice<<32)/currentPrice))+paramd;
}
}
/**
* @dev An auxiliary function, Linear interpolation.
*/
function insertValue(uint256 x0,uint256 x1,uint256 y0, uint256 y1,uint256 x)internal pure returns (uint256){
require(x1 != x0,"input values are duplicated!");
return y0 + (y1-y0)*(x-x0)/(x1-x0);
}
} | 23,193 |
361 | // Check if current block's base fee is under max allowed base fee | function isCurrentBaseFeeAcceptable() public view returns (bool) {
uint256 baseFee;
try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) {
baseFee = currentBaseFee;
} catch {
// Useful for testing until ganache supports london fork
// Hard-code current base fee to 1000 gwei
// This should also help keepers that run in a fork without
// baseFee() to avoid reverting and potentially abandoning the job
baseFee = 1000 * 1e9;
}
return baseFee <= maxAcceptableBaseFee;
}
| function isCurrentBaseFeeAcceptable() public view returns (bool) {
uint256 baseFee;
try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) {
baseFee = currentBaseFee;
} catch {
// Useful for testing until ganache supports london fork
// Hard-code current base fee to 1000 gwei
// This should also help keepers that run in a fork without
// baseFee() to avoid reverting and potentially abandoning the job
baseFee = 1000 * 1e9;
}
return baseFee <= maxAcceptableBaseFee;
}
| 69,481 |
150 | // Send the full amount to the funds recipient. | transferETHOrWETH(fundsRecipient, amount);
| transferETHOrWETH(fundsRecipient, amount);
| 27,789 |
25 | // Total guardian fee earned amount | uint256[] public guardiansFeeTotal;
| uint256[] public guardiansFeeTotal;
| 36,680 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.