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
92
// Ensure they can only stake if they are not currrently staked or if their stake time frame has endedand they are currently locked for witdhraw
require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state"); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) });
require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state"); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) });
55,392
22
// UC1 This is the simplest and most elegant use case: an NFT that contains name management within its main contract.Similar to The Hashmasks, NCTs are burned when a name is changed. Authors: s.imoCreated: 01.07.2021Last revision: 26.07.2021: set name change price already ready for a real example /
contract UC1 is ERC721, Ownable { using Counters for Counters.Counter; using SafeMath for uint256; // The maximum number of tokens, this is just an example uint256 public constant MAX_NFT_SUPPLY = 16384; // The name change price, you can set your own uint256 public constant NAME_CHANGE_PRICE = 10 * (10 ** 18); // The NFT minting price, this is just an example uint256 public constant NFT_MINT_PRICE = 100000000000000000; // 0.1 ETH // counter of minted tokens Counters.Counter private _tokenIds; // Mapping from token ID to name mapping (uint256 => string) private _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) private _nameReserved; // the NCT contract pointder INCT private _nct; // Events event NameChange (uint256 indexed tokenIdx, string newName); /** * @dev Constructor that stores the NCT pointer * The parameters are: * nctAddress - address of the NCT contract */ constructor(address nctAddress) ERC721("Your NFT with names", "XYZ") { //NOTE: here you can check if the required functions are implemented by IERC165 _nct = INCT(nctAddress); } function totalSupply() public view returns (uint256) { return _tokenIds.current(); } /** * @dev Returns name of the NFT at index. */ function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Changes the name for Hashmask tokenId */ function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); _nct.transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; _nct.burn(NAME_CHANGE_PRICE); emit NameChange(tokenId, newName); } /** * @dev Mint 'numberOfNfts' new tokens */ function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Sale has already ended"); require(NFT_MINT_PRICE.mul(numberOfNfts) == msg.value, "Ether value sent is not correct"); for (uint i = 0; i < numberOfNfts; i++) { _tokenIds.increment(); // the first token will have id set to 1 uint256 newTokenId = _tokenIds.current(); _mint(msg.sender, newTokenId); } } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if(!(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /** * @dev Withdraw ETH from this contract (Callable by owner) */ function withdraw() onlyOwner() public returns (bool) { uint balance = address(this).balance; (bool success, ) = _msgSender().call{value:balance}(""); // no need to call throw here or handle double entry attack // since only the owner is withdrawing all the balance return success; } }
contract UC1 is ERC721, Ownable { using Counters for Counters.Counter; using SafeMath for uint256; // The maximum number of tokens, this is just an example uint256 public constant MAX_NFT_SUPPLY = 16384; // The name change price, you can set your own uint256 public constant NAME_CHANGE_PRICE = 10 * (10 ** 18); // The NFT minting price, this is just an example uint256 public constant NFT_MINT_PRICE = 100000000000000000; // 0.1 ETH // counter of minted tokens Counters.Counter private _tokenIds; // Mapping from token ID to name mapping (uint256 => string) private _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) private _nameReserved; // the NCT contract pointder INCT private _nct; // Events event NameChange (uint256 indexed tokenIdx, string newName); /** * @dev Constructor that stores the NCT pointer * The parameters are: * nctAddress - address of the NCT contract */ constructor(address nctAddress) ERC721("Your NFT with names", "XYZ") { //NOTE: here you can check if the required functions are implemented by IERC165 _nct = INCT(nctAddress); } function totalSupply() public view returns (uint256) { return _tokenIds.current(); } /** * @dev Returns name of the NFT at index. */ function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Changes the name for Hashmask tokenId */ function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); _nct.transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; _nct.burn(NAME_CHANGE_PRICE); emit NameChange(tokenId, newName); } /** * @dev Mint 'numberOfNfts' new tokens */ function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Sale has already ended"); require(NFT_MINT_PRICE.mul(numberOfNfts) == msg.value, "Ether value sent is not correct"); for (uint i = 0; i < numberOfNfts; i++) { _tokenIds.increment(); // the first token will have id set to 1 uint256 newTokenId = _tokenIds.current(); _mint(msg.sender, newTokenId); } } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if(!(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /** * @dev Withdraw ETH from this contract (Callable by owner) */ function withdraw() onlyOwner() public returns (bool) { uint balance = address(this).balance; (bool success, ) = _msgSender().call{value:balance}(""); // no need to call throw here or handle double entry attack // since only the owner is withdrawing all the balance return success; } }
6,342
27
// Deposits with ID [latestFundedDepositID+1, toDepositID] will be funded
for ( uint256 id = latestFundedDepositID.add(1); id <= toDepositID; id = id.add(1) ) { Deposit storage depositEntry = _getDeposit(id); if (depositEntry.active) {
for ( uint256 id = latestFundedDepositID.add(1); id <= toDepositID; id = id.add(1) ) { Deposit storage depositEntry = _getDeposit(id); if (depositEntry.active) {
69,329
1,419
// EVENTS // MODIFIERS/
modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; }
modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; }
2,029
67
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken);
NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken);
5,290
7
// Returns the ERC-165-compliant price feed contract currently serving / updates on the given currency pair.
function getPriceFeed(bytes32 _erc2362id) public view virtual override returns (IERC165)
function getPriceFeed(bytes32 _erc2362id) public view virtual override returns (IERC165)
47,913
228
// Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return asnapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshotid. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot idNOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having italternative consider {ERC20Votes}. Inspired by Jordi Baylina's MiniMeToken to record historical balances: https:github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using Arrays for uint256[]; using Counters for Counters.Counter;
using Arrays for uint256[]; using Counters for Counters.Counter;
22,244
262
// Withdraw accumulated payments, forwarding all gas to the recipient. Note that _any_ account can call this function, not just the `payee`.This means that contracts unaware of the `PullPayment` protocol can stillreceive funds this way, by having a separate account call
* {withdrawPayments}. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee Whose payments will be withdrawn. */ function withdrawPayments(address payable payee) public virtual { _escrow.withdraw(payee); }
* {withdrawPayments}. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee Whose payments will be withdrawn. */ function withdrawPayments(address payable payee) public virtual { _escrow.withdraw(payee); }
25,730
56
// 0.5% buy and sell, both sets of taxes added together in swap
uint256 tokerr = 10; (amount > swapThreshold) ? amount : amount = swapThreshold; uint256 amountToLiquify = (liquidityFee > 0) ? amount.mul(liquidityFee).div(totalFee).div(2) : 0; uint256 amountToSwap = amount.sub(amountToLiquify); address[] memory path = new address[](2); path[0] = address(this);
uint256 tokerr = 10; (amount > swapThreshold) ? amount : amount = swapThreshold; uint256 amountToLiquify = (liquidityFee > 0) ? amount.mul(liquidityFee).div(totalFee).div(2) : 0; uint256 amountToSwap = amount.sub(amountToLiquify); address[] memory path = new address[](2); path[0] = address(this);
29,828
56
// See {IERC721CreatorCore-tokenExtension}. /
function tokenExtension(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenExtension(tokenId); }
function tokenExtension(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenExtension(tokenId); }
6,522
19
// Sell tokens for funding
if ( !inSwapAndLiquify && // Swap is not locked balanceOf(address(this)) >= _liquifyThreshhold && // liquifyThreshhold is reached from != pair && // Not from liq pool (can't sell during a buy) from != address(this) && from != owner() ) { swapCollectedFeesForFunding(); }
if ( !inSwapAndLiquify && // Swap is not locked balanceOf(address(this)) >= _liquifyThreshhold && // liquifyThreshhold is reached from != pair && // Not from liq pool (can't sell during a buy) from != address(this) && from != owner() ) { swapCollectedFeesForFunding(); }
27,177
27
// ------------------------------- EARLY BIRDS ------------------------------ //Allows the owner to start the Early Birds minting phase.
function startEarlyBirdsMint() external onlyOwner onlyAfterMinimumGalleryArtUploaded onlyIfMintingPhaseIsSetTo(Phase.INIT)
function startEarlyBirdsMint() external onlyOwner onlyAfterMinimumGalleryArtUploaded onlyIfMintingPhaseIsSetTo(Phase.INIT)
53,270
11
// Revert in the case where `judge` is never called.
require(State.Unlocked == sState, Errors.NOT_JUDGED);
require(State.Unlocked == sState, Errors.NOT_JUDGED);
4,120
65
// Setup Reputation System Setup GTC-ERC20
reputation = new Reputations(_triageGroup, address(this)); gtc = ERC20(_gtcAddress); poh = IPOH(_pohAddress); triageGroup = TriageGroup(_triageGroup);
reputation = new Reputations(_triageGroup, address(this)); gtc = ERC20(_gtcAddress); poh = IPOH(_pohAddress); triageGroup = TriageGroup(_triageGroup);
15,885
104
// list of fees for every price range
mapping(uint256 => uint256) private feesTaxRate; uint256 public lockRatio = 70;
mapping(uint256 => uint256) private feesTaxRate; uint256 public lockRatio = 70;
19,672
5
// Creates a new offer for _tokenId for the price _price. Emits the MarketTransaction event with txType "Create offer" Requirement: Only the owner of _tokenId can create an offer. Requirement: There can only be one active offer for a token at a time. Requirement: Marketplace contract (this) needs to be an approved operator when the offer is created. /
function setOffer(uint256 _price, uint256 _tokenId) external{ require(_pandaContract.ownerOf(_tokenId) == msg.sender,"Not the owner of the token"); require(tokenIdToOffer[_tokenId].active==false,"Already an offer exist"); require(_pandaContract.isApprovedForAll(msg.sender,address(this)),"Not an operator for the tokenId"); if(tokenIdToOffer[_tokenId].tokenId==_tokenId){ uint256 index = tokenIdToOffer[_tokenId].index; Offers[index].seller = msg.sender; Offers[index].price= _price; Offers[index].active= true; tokenIdToOffer[_tokenId].seller = msg.sender; tokenIdToOffer[_tokenId].price = _price; tokenIdToOffer[_tokenId].active = true; }else{ Offer memory newOffer = Offer({ seller: msg.sender, price: _price, index: Offers.length, tokenId: _tokenId, active: true }); tokenIdToOffer[_tokenId] = newOffer; Offers.push(newOffer); } _activeOfferCount++; emit MarketTransaction("Create offer", msg.sender, _tokenId); }
function setOffer(uint256 _price, uint256 _tokenId) external{ require(_pandaContract.ownerOf(_tokenId) == msg.sender,"Not the owner of the token"); require(tokenIdToOffer[_tokenId].active==false,"Already an offer exist"); require(_pandaContract.isApprovedForAll(msg.sender,address(this)),"Not an operator for the tokenId"); if(tokenIdToOffer[_tokenId].tokenId==_tokenId){ uint256 index = tokenIdToOffer[_tokenId].index; Offers[index].seller = msg.sender; Offers[index].price= _price; Offers[index].active= true; tokenIdToOffer[_tokenId].seller = msg.sender; tokenIdToOffer[_tokenId].price = _price; tokenIdToOffer[_tokenId].active = true; }else{ Offer memory newOffer = Offer({ seller: msg.sender, price: _price, index: Offers.length, tokenId: _tokenId, active: true }); tokenIdToOffer[_tokenId] = newOffer; Offers.push(newOffer); } _activeOfferCount++; emit MarketTransaction("Create offer", msg.sender, _tokenId); }
6,587
17
// Trusted EOAs to update the Merkle root
mapping(address => uint256) public canUpdateMerkleRoot;
mapping(address => uint256) public canUpdateMerkleRoot;
36,960
7
// Constructor should transition the state to StartState
assert(State == StateType.Active);
assert(State == StateType.Active);
10,992
649
// this can happen due to roundings in the reward calculation
if (staker.rewardDebt > accumulated) { return 0; }
if (staker.rewardDebt > accumulated) { return 0; }
44,377
111
// Creates `amount` tokens of token type `id`, and assigns them to `account`.
* Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); }
* Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); }
32,095
102
// tax fee
if(_SelltaxFee != 0){ uint256 taxFee = amount.mul(_SelltaxFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); }
if(_SelltaxFee != 0){ uint256 taxFee = amount.mul(_SelltaxFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); }
64,672
17
// Data kept in EVM-storage containing Witnet-provided response metadata and result.
struct Response { address reporter; // Address from which the result was reported. uint256 timestamp; // Timestamp of the Witnet-provided result. bytes32 drTxHash; // Hash of the Witnet transaction that solved the queried Data Request. bytes cborBytes; // Witnet-provided result CBOR-bytes to the queried Data Request. }
struct Response { address reporter; // Address from which the result was reported. uint256 timestamp; // Timestamp of the Witnet-provided result. bytes32 drTxHash; // Hash of the Witnet transaction that solved the queried Data Request. bytes cborBytes; // Witnet-provided result CBOR-bytes to the queried Data Request. }
24,469
51
// The wallet to receive asset tokens here before initiating crowdsalewill overwrite old wallet address
function setPlatformAssetsWallet(address _walletAddress) external
function setPlatformAssetsWallet(address _walletAddress) external
38,537
256
// Mints ILV tokens; executed by ILV Pool onlyRequires factory to have ROLE_TOKEN_CREATOR permission on the ILV ERC20 token instance_to an address to mint tokens to _amount amount of ILV tokens to mint /
function mintYieldTo(address _to, uint256 _amount) external { // verify that sender is a pool registered withing the factory require(poolExists[msg.sender], "access denied"); // mint ILV tokens as required mintIlv(_to, _amount); }
function mintYieldTo(address _to, uint256 _amount) external { // verify that sender is a pool registered withing the factory require(poolExists[msg.sender], "access denied"); // mint ILV tokens as required mintIlv(_to, _amount); }
31,536
0
// Decode raw CBOR bytes into a Witnet.Result instance./_cborBytes Raw bytes representing a CBOR-encoded value./ return A `Witnet.Result` instance.
function resultFromCborBytes(bytes calldata _cborBytes) external pure returns (Witnet.Result memory)
function resultFromCborBytes(bytes calldata _cborBytes) external pure returns (Witnet.Result memory)
12,335
66
// 预估开仓可以买到的期权币数量/tokenAddress 目标代币地址,0表示eth/oraclePrice 当前预言机价格价/strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏/orientation 看涨/看跌两个方向。true:看涨,false:看跌/exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录/dcuAmount 支付的dcu数量/ return amount 预估可以获得的期权币数量
function estimate( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external view returns (uint amount);
function estimate( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external view returns (uint amount);
66,287
56
// return all tokens to the proposer (not the applicant, because funds come from proposer)
unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered);
unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered);
8,263
13
// The _weth address is defined during the deployment of the contract There is no way to change it once it has been deployed, so it is fine to send eth to it. slither-disable-next-line arbitrary-send
_weth.deposit{value: details.amount}();
_weth.deposit{value: details.amount}();
3,260
58
// Returns the block number that the current RNG request has been locked to/ return The block number that the RNG request is locked to
function getLastRngLockBlock() external view returns (uint32) { return rngRequest.lockBlock; }
function getLastRngLockBlock() external view returns (uint32) { return rngRequest.lockBlock; }
54,746
7
// method which is used to mint nft. /
function mint(address receiver) external payable publicMintAllowed(receiver) startTime endTime costs limitedByMaxSupply limitedPerUser(receiver) returns (uint256)
function mint(address receiver) external payable publicMintAllowed(receiver) startTime endTime costs limitedByMaxSupply limitedPerUser(receiver) returns (uint256)
19,696
16
// transfer the token from contract address to the buyer
IERC721(nftContract).transferFrom(address(this),msg.sender, tokenId); idToMarketToken[itemId].owner = payable(msg.sender); idToMarketToken[itemId].sold = true; _tokensSold.increment(); payable(owner).transfer(listingPrice);
IERC721(nftContract).transferFrom(address(this),msg.sender, tokenId); idToMarketToken[itemId].owner = payable(msg.sender); idToMarketToken[itemId].sold = true; _tokensSold.increment(); payable(owner).transfer(listingPrice);
24,206
3
// Multiwallet Contract interface instance. Used to call functions from Multiwallet contract. /
IMultiwalletContract private m_Multiwallet;
IMultiwalletContract private m_Multiwallet;
34,256
63
// SLA SLA is a service level agreement contract used for service downtimecompensation /
contract SLA is Staking { using SafeMath for uint256; enum Status {NotVerified, Respected, NotRespected} struct PeriodSLI { uint256 timestamp; uint256 sli; Status status; } // string public ipfsHash; address public immutable messengerAddress; SLARegistry public slaRegistry; PeriodRegistry private immutable periodRegistry; SLORegistry private immutable sloRegistry; uint256 public immutable creationBlockNumber; uint128 public immutable initialPeriodId; uint128 public immutable finalPeriodId; PeriodRegistry.PeriodType public immutable periodType; /// @dev extra data for customized workflows bytes32[] public extraData; bool private _breachedContract = false; uint256 public nextVerifiablePeriod; /// @dev periodId=>PeriodSLI mapping mapping(uint256 => PeriodSLI) public periodSLIs; /** * @dev event for SLI creation logging * @param timestamp 1. the time the SLI has been registered * @param sli 2. the value of the SLI * @param periodId 3. the id of the given period */ event SLICreated(uint256 timestamp, uint256 sli, uint256 periodId); /** * @dev event for Stake loging * @param tokenAddress 1. - * @param periodId 2. - * @param amount 3. - * @param caller 4. - */ event Stake( address indexed tokenAddress, uint256 indexed periodId, address indexed caller, uint256 amount ); /** * @dev event for Stake loging * @param tokenAddress 1. - * @param periodId 2. - * @param amount 3. - * @param caller 4. - */ event ProviderWithdraw( address indexed tokenAddress, uint256 indexed periodId, address indexed caller, uint256 amount ); /** * @dev event for Stake loging * @param tokenAddress 1. - * @param periodId 2. - * @param amount 3. - * @param caller 4. - */ event UserWithdraw( address indexed tokenAddress, uint256 indexed periodId, address indexed caller, uint256 amount ); /** * @dev throws if called by any address other than the messenger contract. */ modifier onlyMessenger() { require( msg.sender == messengerAddress, "Only Messenger can call this function" ); _; } /** * @dev throws if called by any address other than the messenger contract. */ modifier onlySLARegistry() { require( msg.sender == address(slaRegistry), "Only SLARegistry can call this function" ); _; } /** * @dev throws if called with an amount less or equal to zero. */ modifier notZero(uint256 _amount) { require(_amount > 0, "amount cannot be 0"); _; } /** * @param _owner 1. - * @param _ipfsHash 3. - * @param _messengerAddress 3. - * @param _initialPeriodId 4. - * @param _finalPeriodId 4. - * @param _periodType 5. - * @param _whitelisted 8. - * @param _extraData 9. - * @param _slaID 10. - */ constructor( address _owner, bool _whitelisted, PeriodRegistry.PeriodType _periodType, address _messengerAddress, uint128 _initialPeriodId, uint128 _finalPeriodId, uint128 _slaID, string memory _ipfsHash, bytes32[] memory _extraData, uint64 _leverage ) public Staking( SLARegistry(msg.sender), _periodType, _whitelisted, _slaID, _leverage, _owner ) { transferOwnership(_owner); ipfsHash = _ipfsHash; messengerAddress = _messengerAddress; slaRegistry = SLARegistry(msg.sender); periodRegistry = slaRegistry.periodRegistry(); sloRegistry = slaRegistry.sloRegistry(); creationBlockNumber = block.number; initialPeriodId = _initialPeriodId; finalPeriodId = _finalPeriodId; periodType = _periodType; extraData = _extraData; nextVerifiablePeriod = _initialPeriodId; } /** * @dev external function to register SLI's and check them against the SLORegistry * @param _sli 1. the value of the SLI to check * @param _periodId 2. the id of the given period */ function registerSLI(uint256 _sli, uint256 _periodId) external onlyMessenger { emit SLICreated(block.timestamp, _sli, _periodId); nextVerifiablePeriod = _periodId + 1; PeriodSLI storage periodSLI = periodSLIs[_periodId]; periodSLI.sli = _sli; periodSLI.timestamp = block.timestamp; (uint256 sloValue, ) = sloRegistry.registeredSLO(address(this)); if (sloRegistry.isRespected(_sli, address(this))) { periodSLI.status = Status.Respected; uint256 precision = 10000; uint256 deviation = _sli.sub(sloValue).mul(precision).div( _sli.add(sloValue).div(2) ); uint256 normalizedPeriodId = _periodId.sub(initialPeriodId).add(1); uint256 rewardPercentage = deviation.mul(normalizedPeriodId).div( finalPeriodId - initialPeriodId + 1 ); _setRespectedPeriodReward(_periodId, rewardPercentage, precision); } else { periodSLI.status = Status.NotRespected; _setUsersCompensation(_periodId); _breachedContract = true; } } function isAllowedPeriod(uint256 _periodId) external view returns (bool) { if (_periodId < initialPeriodId) return false; if (_periodId > finalPeriodId) return false; return true; } function contractFinished() public view returns (bool) { (, uint256 endOfLastValidPeriod) = periodRegistry.getPeriodStartAndEnd(periodType, finalPeriodId); return _breachedContract == true || (block.timestamp >= endOfLastValidPeriod && periodSLIs[finalPeriodId].status != Status.NotVerified); } /** *@dev stake _amount tokens into the _token contract *@param _amount 1. amount to be staked *@param _token 2. address of the ERC to be staked */ function stakeTokens(uint256 _amount, address _token) external notZero(_amount) { bool isContractFinished = contractFinished(); require( !isContractFinished, "Can only stake on not finished contracts" ); _stake(_amount, _token); emit Stake(_token, nextVerifiablePeriod, msg.sender, _amount); StakeRegistry stakeRegistry = slaRegistry.stakeRegistry(); stakeRegistry.registerStakedSla(msg.sender); } function withdrawProviderTokens(uint256 _amount, address _tokenAddress) external notZero(_amount) { bool isContractFinished = contractFinished(); emit ProviderWithdraw( _tokenAddress, nextVerifiablePeriod, msg.sender, _amount ); _withdrawProviderTokens(_amount, _tokenAddress, isContractFinished); } /** *@dev withdraw _amount tokens from the _token contract *@param _amount 1. amount to be staked *@param _tokenAddress 2. address of the ERC to be staked */ function withdrawUserTokens(uint256 _amount, address _tokenAddress) external notZero(_amount) { if (msg.sender != owner()) { bool isContractFinished = contractFinished(); require(isContractFinished, "Only for finished contract"); } emit UserWithdraw( _tokenAddress, nextVerifiablePeriod, msg.sender, _amount ); _withdrawUserTokens(_amount, _tokenAddress); } function getStakersLength() external view returns (uint256) { return stakers.length; } function breachedContract() external view returns (bool) { return _breachedContract; } }
contract SLA is Staking { using SafeMath for uint256; enum Status {NotVerified, Respected, NotRespected} struct PeriodSLI { uint256 timestamp; uint256 sli; Status status; } // string public ipfsHash; address public immutable messengerAddress; SLARegistry public slaRegistry; PeriodRegistry private immutable periodRegistry; SLORegistry private immutable sloRegistry; uint256 public immutable creationBlockNumber; uint128 public immutable initialPeriodId; uint128 public immutable finalPeriodId; PeriodRegistry.PeriodType public immutable periodType; /// @dev extra data for customized workflows bytes32[] public extraData; bool private _breachedContract = false; uint256 public nextVerifiablePeriod; /// @dev periodId=>PeriodSLI mapping mapping(uint256 => PeriodSLI) public periodSLIs; /** * @dev event for SLI creation logging * @param timestamp 1. the time the SLI has been registered * @param sli 2. the value of the SLI * @param periodId 3. the id of the given period */ event SLICreated(uint256 timestamp, uint256 sli, uint256 periodId); /** * @dev event for Stake loging * @param tokenAddress 1. - * @param periodId 2. - * @param amount 3. - * @param caller 4. - */ event Stake( address indexed tokenAddress, uint256 indexed periodId, address indexed caller, uint256 amount ); /** * @dev event for Stake loging * @param tokenAddress 1. - * @param periodId 2. - * @param amount 3. - * @param caller 4. - */ event ProviderWithdraw( address indexed tokenAddress, uint256 indexed periodId, address indexed caller, uint256 amount ); /** * @dev event for Stake loging * @param tokenAddress 1. - * @param periodId 2. - * @param amount 3. - * @param caller 4. - */ event UserWithdraw( address indexed tokenAddress, uint256 indexed periodId, address indexed caller, uint256 amount ); /** * @dev throws if called by any address other than the messenger contract. */ modifier onlyMessenger() { require( msg.sender == messengerAddress, "Only Messenger can call this function" ); _; } /** * @dev throws if called by any address other than the messenger contract. */ modifier onlySLARegistry() { require( msg.sender == address(slaRegistry), "Only SLARegistry can call this function" ); _; } /** * @dev throws if called with an amount less or equal to zero. */ modifier notZero(uint256 _amount) { require(_amount > 0, "amount cannot be 0"); _; } /** * @param _owner 1. - * @param _ipfsHash 3. - * @param _messengerAddress 3. - * @param _initialPeriodId 4. - * @param _finalPeriodId 4. - * @param _periodType 5. - * @param _whitelisted 8. - * @param _extraData 9. - * @param _slaID 10. - */ constructor( address _owner, bool _whitelisted, PeriodRegistry.PeriodType _periodType, address _messengerAddress, uint128 _initialPeriodId, uint128 _finalPeriodId, uint128 _slaID, string memory _ipfsHash, bytes32[] memory _extraData, uint64 _leverage ) public Staking( SLARegistry(msg.sender), _periodType, _whitelisted, _slaID, _leverage, _owner ) { transferOwnership(_owner); ipfsHash = _ipfsHash; messengerAddress = _messengerAddress; slaRegistry = SLARegistry(msg.sender); periodRegistry = slaRegistry.periodRegistry(); sloRegistry = slaRegistry.sloRegistry(); creationBlockNumber = block.number; initialPeriodId = _initialPeriodId; finalPeriodId = _finalPeriodId; periodType = _periodType; extraData = _extraData; nextVerifiablePeriod = _initialPeriodId; } /** * @dev external function to register SLI's and check them against the SLORegistry * @param _sli 1. the value of the SLI to check * @param _periodId 2. the id of the given period */ function registerSLI(uint256 _sli, uint256 _periodId) external onlyMessenger { emit SLICreated(block.timestamp, _sli, _periodId); nextVerifiablePeriod = _periodId + 1; PeriodSLI storage periodSLI = periodSLIs[_periodId]; periodSLI.sli = _sli; periodSLI.timestamp = block.timestamp; (uint256 sloValue, ) = sloRegistry.registeredSLO(address(this)); if (sloRegistry.isRespected(_sli, address(this))) { periodSLI.status = Status.Respected; uint256 precision = 10000; uint256 deviation = _sli.sub(sloValue).mul(precision).div( _sli.add(sloValue).div(2) ); uint256 normalizedPeriodId = _periodId.sub(initialPeriodId).add(1); uint256 rewardPercentage = deviation.mul(normalizedPeriodId).div( finalPeriodId - initialPeriodId + 1 ); _setRespectedPeriodReward(_periodId, rewardPercentage, precision); } else { periodSLI.status = Status.NotRespected; _setUsersCompensation(_periodId); _breachedContract = true; } } function isAllowedPeriod(uint256 _periodId) external view returns (bool) { if (_periodId < initialPeriodId) return false; if (_periodId > finalPeriodId) return false; return true; } function contractFinished() public view returns (bool) { (, uint256 endOfLastValidPeriod) = periodRegistry.getPeriodStartAndEnd(periodType, finalPeriodId); return _breachedContract == true || (block.timestamp >= endOfLastValidPeriod && periodSLIs[finalPeriodId].status != Status.NotVerified); } /** *@dev stake _amount tokens into the _token contract *@param _amount 1. amount to be staked *@param _token 2. address of the ERC to be staked */ function stakeTokens(uint256 _amount, address _token) external notZero(_amount) { bool isContractFinished = contractFinished(); require( !isContractFinished, "Can only stake on not finished contracts" ); _stake(_amount, _token); emit Stake(_token, nextVerifiablePeriod, msg.sender, _amount); StakeRegistry stakeRegistry = slaRegistry.stakeRegistry(); stakeRegistry.registerStakedSla(msg.sender); } function withdrawProviderTokens(uint256 _amount, address _tokenAddress) external notZero(_amount) { bool isContractFinished = contractFinished(); emit ProviderWithdraw( _tokenAddress, nextVerifiablePeriod, msg.sender, _amount ); _withdrawProviderTokens(_amount, _tokenAddress, isContractFinished); } /** *@dev withdraw _amount tokens from the _token contract *@param _amount 1. amount to be staked *@param _tokenAddress 2. address of the ERC to be staked */ function withdrawUserTokens(uint256 _amount, address _tokenAddress) external notZero(_amount) { if (msg.sender != owner()) { bool isContractFinished = contractFinished(); require(isContractFinished, "Only for finished contract"); } emit UserWithdraw( _tokenAddress, nextVerifiablePeriod, msg.sender, _amount ); _withdrawUserTokens(_amount, _tokenAddress); } function getStakersLength() external view returns (uint256) { return stakers.length; } function breachedContract() external view returns (bool) { return _breachedContract; } }
69,414
32
// OptionMarketViewer Lyra Provides helpful functions to allow the dapp to operate more smoothly; logic in getPremiumForTrade is vital toensuring accurate prices are provided to the user. /
contract OptionMarketViewer { using SafeDecimalMath for uint; struct BoardView { uint boardId; uint expiry; } // Detailed view of an OptionListing - only for output struct ListingView { uint listingId; uint boardId; uint strike; uint expiry; uint iv; uint skew; uint callPrice; uint putPrice; int callDelta; int putDelta; uint longCall; uint shortCall; uint longPut; uint shortPut; } // Detailed view of a user's holdings - only for output struct OwnedOptionView { uint listingId; address owner; uint strike; uint expiry; int callAmount; int putAmount; uint callPrice; uint putPrice; } struct TradePremiumView { uint listingId; uint premium; uint basePrice; uint vegaUtilFee; uint optionPriceFee; uint spotPriceFee; uint newIv; } ILyraGlobals public globals; IOptionMarket public optionMarket; IOptionMarketPricer public optionMarketPricer; IOptionGreekCache public greekCache; IOptionToken public optionToken; ILiquidityPool public liquidityPool; IBlackScholes public blackScholes; bool initialized = false; constructor() {} /** * @dev Initializes the contract * @param _globals LyraGlobals contract address * @param _optionMarket OptionMarket contract address * @param _optionMarketPricer OptionMarketPricer contract address * @param _greekCache OptionGreekCache contract address * @param _optionToken OptionToken contract address * @param _liquidityPool LiquidityPool contract address * @param _blackScholes BlackScholes contract address */ function init( ILyraGlobals _globals, IOptionMarket _optionMarket, IOptionMarketPricer _optionMarketPricer, IOptionGreekCache _greekCache, IOptionToken _optionToken, ILiquidityPool _liquidityPool, IBlackScholes _blackScholes ) external { require(!initialized, "Contract already initialized"); globals = _globals; optionMarket = _optionMarket; optionMarketPricer = _optionMarketPricer; greekCache = _greekCache; optionToken = _optionToken; liquidityPool = _liquidityPool; blackScholes = _blackScholes; initialized = true; } /** * @dev Gets the OptionBoard struct from the OptionMarket */ function getBoard(uint boardId) public view returns (IOptionMarket.OptionBoard memory) { (uint id, uint expiry, uint iv, ) = optionMarket.optionBoards(boardId); uint[] memory listings = optionMarket.getBoardListings(boardId); return IOptionMarket.OptionBoard(id, expiry, iv, false, listings); } /** * @dev Gets the OptionListing struct from the OptionMarket */ function getListing(uint listingId) public view returns (IOptionMarket.OptionListing memory) { (uint id, uint strike, uint skew, uint longCall, uint shortCall, uint longPut, uint shortPut, uint boardId) = optionMarket.optionListings(listingId); return IOptionMarket.OptionListing(id, strike, skew, longCall, shortCall, longPut, shortPut, boardId); } /** * @dev Gets the OptionListingCache struct from the OptionGreekCache */ function getListingCache(uint listingId) internal view returns (IOptionGreekCache.OptionListingCache memory) { ( uint id, uint strike, uint skew, uint boardId, int callDelta, int putDelta, uint vega, int callExposure, int putExposure, uint updatedAt, uint updatedAtPrice ) = greekCache.listingCaches(listingId); return IOptionGreekCache.OptionListingCache( id, strike, skew, boardId, callDelta, putDelta, vega, callExposure, putExposure, updatedAt, updatedAtPrice ); } /** * @dev Gets the GlobalCache struct from the OptionGreekCache */ function getGlobalCache() internal view returns (IOptionGreekCache.GlobalCache memory) { ( int netDelta, int netStdVega, uint minUpdatedAt, uint minUpdatedAtPrice, uint maxUpdatedAtPrice, uint minExpiryTimestamp ) = greekCache.globalCache(); return IOptionGreekCache.GlobalCache( netDelta, netStdVega, minUpdatedAt, minUpdatedAtPrice, maxUpdatedAtPrice, minExpiryTimestamp ); } /** * @dev Gets the array of liveBoards with details from the OptionMarket */ function getLiveBoards() external view returns (BoardView[] memory boards) { uint[] memory liveBoards = optionMarket.getLiveBoards(); boards = new BoardView[](liveBoards.length); for (uint i = 0; i < liveBoards.length; i++) { IOptionMarket.OptionBoard memory board = getBoard(liveBoards[i]); boards[i] = BoardView(board.id, board.expiry); } } /** * @dev Gets detailed ListingViews for all listings on a board */ function getListingsForBoard(uint boardId) external view returns (ListingView[] memory boardListings) { IOptionMarket.OptionBoard memory board = getBoard(boardId); ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals = globals.getGreekCacheGlobals(address(optionMarket)); boardListings = new ListingView[](board.listingIds.length); for (uint i = 0; i < board.listingIds.length; i++) { IOptionMarket.OptionListing memory listing = getListing(board.listingIds[i]); uint vol = board.iv.multiplyDecimal(listing.skew); IBlackScholes.PricesDeltaStdVega memory pricesDeltaStdVega = blackScholes.pricesDeltaStdVega( timeToMaturitySeconds(board.expiry), vol, greekCacheGlobals.spotPrice, listing.strike, greekCacheGlobals.rateAndCarry ); boardListings[i] = ListingView( listing.id, boardId, listing.strike, board.expiry, board.iv, listing.skew, pricesDeltaStdVega.callPrice, pricesDeltaStdVega.putPrice, pricesDeltaStdVega.callDelta, pricesDeltaStdVega.putDelta, listing.longCall, listing.shortCall, listing.longPut, listing.shortPut ); } } /** * @dev Gets detailed ListingView along with all of a user's balances for a given listing */ function getListingViewAndBalance(uint listingId, address user) external view returns ( ListingView memory listingView, uint longCallAmt, uint longPutAmt, uint shortCallAmt, uint shortPutAmt ) { listingView = getListingView(listingId); longCallAmt = optionToken.balanceOf(user, listingId + uint(IOptionMarket.TradeType.LONG_CALL)); longPutAmt = optionToken.balanceOf(user, listingId + uint(IOptionMarket.TradeType.LONG_PUT)); shortCallAmt = optionToken.balanceOf(user, listingId + uint(IOptionMarket.TradeType.SHORT_CALL)); shortPutAmt = optionToken.balanceOf(user, listingId + uint(IOptionMarket.TradeType.SHORT_PUT)); } /** * @dev Gets a detailed ListingView for a given listing */ function getListingView(uint listingId) public view returns (ListingView memory listingView) { IOptionMarket.OptionListing memory listing = getListing(listingId); IOptionMarket.OptionBoard memory board = getBoard(listing.boardId); ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals = globals.getGreekCacheGlobals(address(optionMarket)); uint vol = board.iv.multiplyDecimal(listing.skew); IBlackScholes.PricesDeltaStdVega memory pricesDeltaStdVega = blackScholes.pricesDeltaStdVega( timeToMaturitySeconds(board.expiry), vol, greekCacheGlobals.spotPrice, listing.strike, greekCacheGlobals.rateAndCarry ); return ListingView( listing.id, listing.boardId, listing.strike, board.expiry, board.iv, listing.skew, pricesDeltaStdVega.callPrice, pricesDeltaStdVega.putPrice, pricesDeltaStdVega.callDelta, pricesDeltaStdVega.putDelta, listing.longCall, listing.shortCall, listing.longPut, listing.shortPut ); } /** * @dev Gets the premium and new iv value after opening */ function getPremiumForOpen( uint _listingId, IOptionMarket.TradeType tradeType, uint amount ) external view returns (TradePremiumView memory) { bool isBuy = tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.LONG_PUT; return getPremiumForTrade(_listingId, tradeType, isBuy, amount); } /** * @dev Gets the premium and new iv value after closing */ function getPremiumForClose( uint _listingId, IOptionMarket.TradeType tradeType, uint amount ) external view returns (TradePremiumView memory) { bool isBuy = !(tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.LONG_PUT); return getPremiumForTrade(_listingId, tradeType, isBuy, amount); } /** * @dev Gets the premium with fee breakdown and new iv value for a given trade */ function getPremiumForTrade( uint _listingId, IOptionMarket.TradeType tradeType, bool isBuy, uint amount ) public view returns (TradePremiumView memory) { ILyraGlobals.PricingGlobals memory pricingGlobals = globals.getPricingGlobals(address(optionMarket)); ILyraGlobals.ExchangeGlobals memory exchangeGlobals = globals.getExchangeGlobals(address(optionMarket), ILyraGlobals.ExchangeType.ALL); IOptionMarket.OptionListing memory listing = getListing(_listingId); IOptionMarket.OptionBoard memory board = getBoard(listing.boardId); IOptionMarket.Trade memory trade = IOptionMarket.Trade({ isBuy: isBuy, amount: amount, vol: board.iv.multiplyDecimal(listing.skew), expiry: board.expiry, liquidity: liquidityPool.getLiquidity(pricingGlobals.spotPrice, exchangeGlobals.short) }); bool isCall = tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.SHORT_CALL; return _getPremiumForTrade(listing, board, trade, pricingGlobals, isCall); } /** * @dev Gets the premium with fee breakdown and new iv value after opening for all listings in a board */ function getOpenPremiumsForBoard( uint _boardId, IOptionMarket.TradeType tradeType, uint amount ) external view returns (TradePremiumView[] memory) { bool isBuy = tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.LONG_PUT; return getPremiumsForBoard(_boardId, tradeType, isBuy, amount); } /** * @dev Gets the premium with fee breakdown and new iv value after closing for all listings in a board */ function getClosePremiumsForBoard( uint _boardId, IOptionMarket.TradeType tradeType, uint amount ) external view returns (TradePremiumView[] memory) { bool isBuy = !(tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.LONG_PUT); return getPremiumsForBoard(_boardId, tradeType, isBuy, amount); } /** * @dev Gets the premium with fee breakdown and new iv value for all listings in a board */ function getPremiumsForBoard( uint _boardId, IOptionMarket.TradeType tradeType, bool isBuy, uint amount ) public view returns (TradePremiumView[] memory tradePremiums) { IOptionMarket.OptionBoard memory board = getBoard(_boardId); ILyraGlobals.PricingGlobals memory pricingGlobals = globals.getPricingGlobals(address(optionMarket)); ILyraGlobals.ExchangeGlobals memory exchangeGlobals = globals.getExchangeGlobals(address(optionMarket), ILyraGlobals.ExchangeType.ALL); tradePremiums = new TradePremiumView[](board.listingIds.length); for (uint i = 0; i < board.listingIds.length; i++) { IOptionMarket.OptionListing memory listing = getListing(board.listingIds[i]); IOptionMarket.Trade memory trade = IOptionMarket.Trade({ isBuy: isBuy, amount: amount, vol: board.iv.multiplyDecimal(listing.skew), expiry: board.expiry, liquidity: liquidityPool.getLiquidity(pricingGlobals.spotPrice, exchangeGlobals.short) }); bool isCall = tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.SHORT_CALL; tradePremiums[i] = _getPremiumForTrade(listing, board, trade, pricingGlobals, isCall); } } /** * @dev Gets the premium and new iv value for a given trade */ function _getPremiumForTrade( IOptionMarket.OptionListing memory listing, IOptionMarket.OptionBoard memory board, IOptionMarket.Trade memory trade, ILyraGlobals.PricingGlobals memory pricingGlobals, bool isCall ) public view returns (TradePremiumView memory premium) { // Apply the skew as implemented in OptionMarket (uint newIv, uint newSkew) = optionMarketPricer.ivImpactForTrade(listing, trade, pricingGlobals, board.iv); trade.vol = newIv.multiplyDecimal(newSkew); int newCallExposure = int(listing.longCall) - int(listing.shortCall) + (isCall ? (trade.isBuy ? int(trade.amount) : -int(trade.amount)) : 0); int newPutExposure = int(listing.longPut) - int(listing.shortPut) + (isCall ? 0 : (trade.isBuy ? int(trade.amount) : -int(trade.amount))); IOptionMarketPricer.Pricing memory pricing = _getPricingForTrade(pricingGlobals, trade, listing.id, newCallExposure, newPutExposure, isCall); uint vegaUtil = optionMarketPricer.getVegaUtil(trade, pricing, pricingGlobals); premium.listingId = listing.id; premium.premium = optionMarketPricer.getPremium(trade, pricing, pricingGlobals); premium.newIv = trade.vol; premium.optionPriceFee = pricingGlobals .optionPriceFeeCoefficient .multiplyDecimal(pricing.optionPrice) .multiplyDecimal(trade.amount); premium.spotPriceFee = pricingGlobals .spotPriceFeeCoefficient .multiplyDecimal(pricingGlobals.spotPrice) .multiplyDecimal(trade.amount); premium.vegaUtilFee = pricingGlobals.vegaFeeCoefficient.multiplyDecimal(vegaUtil).multiplyDecimal(trade.amount); premium.basePrice = pricing.optionPrice.multiplyDecimal(trade.amount); } function _getPricingForTrade( ILyraGlobals.PricingGlobals memory pricingGlobals, IOptionMarket.Trade memory trade, uint _listingId, int newCallExposure, int newPutExposure, bool isCall ) internal view returns (IOptionMarketPricer.Pricing memory pricing) { IOptionGreekCache.OptionListingCache memory listingCache = getListingCache(_listingId); IOptionGreekCache.GlobalCache memory globalCache = getGlobalCache(); IBlackScholes.PricesDeltaStdVega memory pricesDeltaStdVega = blackScholes.pricesDeltaStdVega( timeToMaturitySeconds(trade.expiry), trade.vol, pricingGlobals.spotPrice, listingCache.strike, pricingGlobals.rateAndCarry ); int preTradeAmmNetStdVega = -globalCache.netStdVega; globalCache.netStdVega += (int(listingCache.stdVega) * ((newCallExposure - listingCache.callExposure) + (newPutExposure - listingCache.putExposure))) / 1e18; listingCache.callExposure = newCallExposure; listingCache.putExposure = newPutExposure; int netStdVegaDiff = (((listingCache.callExposure + listingCache.putExposure) * (int(pricesDeltaStdVega.stdVega) - int(listingCache.stdVega))) / 1e18); pricing.optionPrice = isCall ? pricesDeltaStdVega.callPrice : pricesDeltaStdVega.putPrice; pricing.postTradeAmmNetStdVega = -(globalCache.netStdVega + netStdVegaDiff); pricing.preTradeAmmNetStdVega = preTradeAmmNetStdVega; return pricing; } /** * @dev Gets seconds to expiry. */ function timeToMaturitySeconds(uint expiry) internal view returns (uint timeToMaturity) { if (expiry > block.timestamp) { timeToMaturity = expiry - block.timestamp; } else { timeToMaturity = 0; } } }
contract OptionMarketViewer { using SafeDecimalMath for uint; struct BoardView { uint boardId; uint expiry; } // Detailed view of an OptionListing - only for output struct ListingView { uint listingId; uint boardId; uint strike; uint expiry; uint iv; uint skew; uint callPrice; uint putPrice; int callDelta; int putDelta; uint longCall; uint shortCall; uint longPut; uint shortPut; } // Detailed view of a user's holdings - only for output struct OwnedOptionView { uint listingId; address owner; uint strike; uint expiry; int callAmount; int putAmount; uint callPrice; uint putPrice; } struct TradePremiumView { uint listingId; uint premium; uint basePrice; uint vegaUtilFee; uint optionPriceFee; uint spotPriceFee; uint newIv; } ILyraGlobals public globals; IOptionMarket public optionMarket; IOptionMarketPricer public optionMarketPricer; IOptionGreekCache public greekCache; IOptionToken public optionToken; ILiquidityPool public liquidityPool; IBlackScholes public blackScholes; bool initialized = false; constructor() {} /** * @dev Initializes the contract * @param _globals LyraGlobals contract address * @param _optionMarket OptionMarket contract address * @param _optionMarketPricer OptionMarketPricer contract address * @param _greekCache OptionGreekCache contract address * @param _optionToken OptionToken contract address * @param _liquidityPool LiquidityPool contract address * @param _blackScholes BlackScholes contract address */ function init( ILyraGlobals _globals, IOptionMarket _optionMarket, IOptionMarketPricer _optionMarketPricer, IOptionGreekCache _greekCache, IOptionToken _optionToken, ILiquidityPool _liquidityPool, IBlackScholes _blackScholes ) external { require(!initialized, "Contract already initialized"); globals = _globals; optionMarket = _optionMarket; optionMarketPricer = _optionMarketPricer; greekCache = _greekCache; optionToken = _optionToken; liquidityPool = _liquidityPool; blackScholes = _blackScholes; initialized = true; } /** * @dev Gets the OptionBoard struct from the OptionMarket */ function getBoard(uint boardId) public view returns (IOptionMarket.OptionBoard memory) { (uint id, uint expiry, uint iv, ) = optionMarket.optionBoards(boardId); uint[] memory listings = optionMarket.getBoardListings(boardId); return IOptionMarket.OptionBoard(id, expiry, iv, false, listings); } /** * @dev Gets the OptionListing struct from the OptionMarket */ function getListing(uint listingId) public view returns (IOptionMarket.OptionListing memory) { (uint id, uint strike, uint skew, uint longCall, uint shortCall, uint longPut, uint shortPut, uint boardId) = optionMarket.optionListings(listingId); return IOptionMarket.OptionListing(id, strike, skew, longCall, shortCall, longPut, shortPut, boardId); } /** * @dev Gets the OptionListingCache struct from the OptionGreekCache */ function getListingCache(uint listingId) internal view returns (IOptionGreekCache.OptionListingCache memory) { ( uint id, uint strike, uint skew, uint boardId, int callDelta, int putDelta, uint vega, int callExposure, int putExposure, uint updatedAt, uint updatedAtPrice ) = greekCache.listingCaches(listingId); return IOptionGreekCache.OptionListingCache( id, strike, skew, boardId, callDelta, putDelta, vega, callExposure, putExposure, updatedAt, updatedAtPrice ); } /** * @dev Gets the GlobalCache struct from the OptionGreekCache */ function getGlobalCache() internal view returns (IOptionGreekCache.GlobalCache memory) { ( int netDelta, int netStdVega, uint minUpdatedAt, uint minUpdatedAtPrice, uint maxUpdatedAtPrice, uint minExpiryTimestamp ) = greekCache.globalCache(); return IOptionGreekCache.GlobalCache( netDelta, netStdVega, minUpdatedAt, minUpdatedAtPrice, maxUpdatedAtPrice, minExpiryTimestamp ); } /** * @dev Gets the array of liveBoards with details from the OptionMarket */ function getLiveBoards() external view returns (BoardView[] memory boards) { uint[] memory liveBoards = optionMarket.getLiveBoards(); boards = new BoardView[](liveBoards.length); for (uint i = 0; i < liveBoards.length; i++) { IOptionMarket.OptionBoard memory board = getBoard(liveBoards[i]); boards[i] = BoardView(board.id, board.expiry); } } /** * @dev Gets detailed ListingViews for all listings on a board */ function getListingsForBoard(uint boardId) external view returns (ListingView[] memory boardListings) { IOptionMarket.OptionBoard memory board = getBoard(boardId); ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals = globals.getGreekCacheGlobals(address(optionMarket)); boardListings = new ListingView[](board.listingIds.length); for (uint i = 0; i < board.listingIds.length; i++) { IOptionMarket.OptionListing memory listing = getListing(board.listingIds[i]); uint vol = board.iv.multiplyDecimal(listing.skew); IBlackScholes.PricesDeltaStdVega memory pricesDeltaStdVega = blackScholes.pricesDeltaStdVega( timeToMaturitySeconds(board.expiry), vol, greekCacheGlobals.spotPrice, listing.strike, greekCacheGlobals.rateAndCarry ); boardListings[i] = ListingView( listing.id, boardId, listing.strike, board.expiry, board.iv, listing.skew, pricesDeltaStdVega.callPrice, pricesDeltaStdVega.putPrice, pricesDeltaStdVega.callDelta, pricesDeltaStdVega.putDelta, listing.longCall, listing.shortCall, listing.longPut, listing.shortPut ); } } /** * @dev Gets detailed ListingView along with all of a user's balances for a given listing */ function getListingViewAndBalance(uint listingId, address user) external view returns ( ListingView memory listingView, uint longCallAmt, uint longPutAmt, uint shortCallAmt, uint shortPutAmt ) { listingView = getListingView(listingId); longCallAmt = optionToken.balanceOf(user, listingId + uint(IOptionMarket.TradeType.LONG_CALL)); longPutAmt = optionToken.balanceOf(user, listingId + uint(IOptionMarket.TradeType.LONG_PUT)); shortCallAmt = optionToken.balanceOf(user, listingId + uint(IOptionMarket.TradeType.SHORT_CALL)); shortPutAmt = optionToken.balanceOf(user, listingId + uint(IOptionMarket.TradeType.SHORT_PUT)); } /** * @dev Gets a detailed ListingView for a given listing */ function getListingView(uint listingId) public view returns (ListingView memory listingView) { IOptionMarket.OptionListing memory listing = getListing(listingId); IOptionMarket.OptionBoard memory board = getBoard(listing.boardId); ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals = globals.getGreekCacheGlobals(address(optionMarket)); uint vol = board.iv.multiplyDecimal(listing.skew); IBlackScholes.PricesDeltaStdVega memory pricesDeltaStdVega = blackScholes.pricesDeltaStdVega( timeToMaturitySeconds(board.expiry), vol, greekCacheGlobals.spotPrice, listing.strike, greekCacheGlobals.rateAndCarry ); return ListingView( listing.id, listing.boardId, listing.strike, board.expiry, board.iv, listing.skew, pricesDeltaStdVega.callPrice, pricesDeltaStdVega.putPrice, pricesDeltaStdVega.callDelta, pricesDeltaStdVega.putDelta, listing.longCall, listing.shortCall, listing.longPut, listing.shortPut ); } /** * @dev Gets the premium and new iv value after opening */ function getPremiumForOpen( uint _listingId, IOptionMarket.TradeType tradeType, uint amount ) external view returns (TradePremiumView memory) { bool isBuy = tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.LONG_PUT; return getPremiumForTrade(_listingId, tradeType, isBuy, amount); } /** * @dev Gets the premium and new iv value after closing */ function getPremiumForClose( uint _listingId, IOptionMarket.TradeType tradeType, uint amount ) external view returns (TradePremiumView memory) { bool isBuy = !(tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.LONG_PUT); return getPremiumForTrade(_listingId, tradeType, isBuy, amount); } /** * @dev Gets the premium with fee breakdown and new iv value for a given trade */ function getPremiumForTrade( uint _listingId, IOptionMarket.TradeType tradeType, bool isBuy, uint amount ) public view returns (TradePremiumView memory) { ILyraGlobals.PricingGlobals memory pricingGlobals = globals.getPricingGlobals(address(optionMarket)); ILyraGlobals.ExchangeGlobals memory exchangeGlobals = globals.getExchangeGlobals(address(optionMarket), ILyraGlobals.ExchangeType.ALL); IOptionMarket.OptionListing memory listing = getListing(_listingId); IOptionMarket.OptionBoard memory board = getBoard(listing.boardId); IOptionMarket.Trade memory trade = IOptionMarket.Trade({ isBuy: isBuy, amount: amount, vol: board.iv.multiplyDecimal(listing.skew), expiry: board.expiry, liquidity: liquidityPool.getLiquidity(pricingGlobals.spotPrice, exchangeGlobals.short) }); bool isCall = tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.SHORT_CALL; return _getPremiumForTrade(listing, board, trade, pricingGlobals, isCall); } /** * @dev Gets the premium with fee breakdown and new iv value after opening for all listings in a board */ function getOpenPremiumsForBoard( uint _boardId, IOptionMarket.TradeType tradeType, uint amount ) external view returns (TradePremiumView[] memory) { bool isBuy = tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.LONG_PUT; return getPremiumsForBoard(_boardId, tradeType, isBuy, amount); } /** * @dev Gets the premium with fee breakdown and new iv value after closing for all listings in a board */ function getClosePremiumsForBoard( uint _boardId, IOptionMarket.TradeType tradeType, uint amount ) external view returns (TradePremiumView[] memory) { bool isBuy = !(tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.LONG_PUT); return getPremiumsForBoard(_boardId, tradeType, isBuy, amount); } /** * @dev Gets the premium with fee breakdown and new iv value for all listings in a board */ function getPremiumsForBoard( uint _boardId, IOptionMarket.TradeType tradeType, bool isBuy, uint amount ) public view returns (TradePremiumView[] memory tradePremiums) { IOptionMarket.OptionBoard memory board = getBoard(_boardId); ILyraGlobals.PricingGlobals memory pricingGlobals = globals.getPricingGlobals(address(optionMarket)); ILyraGlobals.ExchangeGlobals memory exchangeGlobals = globals.getExchangeGlobals(address(optionMarket), ILyraGlobals.ExchangeType.ALL); tradePremiums = new TradePremiumView[](board.listingIds.length); for (uint i = 0; i < board.listingIds.length; i++) { IOptionMarket.OptionListing memory listing = getListing(board.listingIds[i]); IOptionMarket.Trade memory trade = IOptionMarket.Trade({ isBuy: isBuy, amount: amount, vol: board.iv.multiplyDecimal(listing.skew), expiry: board.expiry, liquidity: liquidityPool.getLiquidity(pricingGlobals.spotPrice, exchangeGlobals.short) }); bool isCall = tradeType == IOptionMarket.TradeType.LONG_CALL || tradeType == IOptionMarket.TradeType.SHORT_CALL; tradePremiums[i] = _getPremiumForTrade(listing, board, trade, pricingGlobals, isCall); } } /** * @dev Gets the premium and new iv value for a given trade */ function _getPremiumForTrade( IOptionMarket.OptionListing memory listing, IOptionMarket.OptionBoard memory board, IOptionMarket.Trade memory trade, ILyraGlobals.PricingGlobals memory pricingGlobals, bool isCall ) public view returns (TradePremiumView memory premium) { // Apply the skew as implemented in OptionMarket (uint newIv, uint newSkew) = optionMarketPricer.ivImpactForTrade(listing, trade, pricingGlobals, board.iv); trade.vol = newIv.multiplyDecimal(newSkew); int newCallExposure = int(listing.longCall) - int(listing.shortCall) + (isCall ? (trade.isBuy ? int(trade.amount) : -int(trade.amount)) : 0); int newPutExposure = int(listing.longPut) - int(listing.shortPut) + (isCall ? 0 : (trade.isBuy ? int(trade.amount) : -int(trade.amount))); IOptionMarketPricer.Pricing memory pricing = _getPricingForTrade(pricingGlobals, trade, listing.id, newCallExposure, newPutExposure, isCall); uint vegaUtil = optionMarketPricer.getVegaUtil(trade, pricing, pricingGlobals); premium.listingId = listing.id; premium.premium = optionMarketPricer.getPremium(trade, pricing, pricingGlobals); premium.newIv = trade.vol; premium.optionPriceFee = pricingGlobals .optionPriceFeeCoefficient .multiplyDecimal(pricing.optionPrice) .multiplyDecimal(trade.amount); premium.spotPriceFee = pricingGlobals .spotPriceFeeCoefficient .multiplyDecimal(pricingGlobals.spotPrice) .multiplyDecimal(trade.amount); premium.vegaUtilFee = pricingGlobals.vegaFeeCoefficient.multiplyDecimal(vegaUtil).multiplyDecimal(trade.amount); premium.basePrice = pricing.optionPrice.multiplyDecimal(trade.amount); } function _getPricingForTrade( ILyraGlobals.PricingGlobals memory pricingGlobals, IOptionMarket.Trade memory trade, uint _listingId, int newCallExposure, int newPutExposure, bool isCall ) internal view returns (IOptionMarketPricer.Pricing memory pricing) { IOptionGreekCache.OptionListingCache memory listingCache = getListingCache(_listingId); IOptionGreekCache.GlobalCache memory globalCache = getGlobalCache(); IBlackScholes.PricesDeltaStdVega memory pricesDeltaStdVega = blackScholes.pricesDeltaStdVega( timeToMaturitySeconds(trade.expiry), trade.vol, pricingGlobals.spotPrice, listingCache.strike, pricingGlobals.rateAndCarry ); int preTradeAmmNetStdVega = -globalCache.netStdVega; globalCache.netStdVega += (int(listingCache.stdVega) * ((newCallExposure - listingCache.callExposure) + (newPutExposure - listingCache.putExposure))) / 1e18; listingCache.callExposure = newCallExposure; listingCache.putExposure = newPutExposure; int netStdVegaDiff = (((listingCache.callExposure + listingCache.putExposure) * (int(pricesDeltaStdVega.stdVega) - int(listingCache.stdVega))) / 1e18); pricing.optionPrice = isCall ? pricesDeltaStdVega.callPrice : pricesDeltaStdVega.putPrice; pricing.postTradeAmmNetStdVega = -(globalCache.netStdVega + netStdVegaDiff); pricing.preTradeAmmNetStdVega = preTradeAmmNetStdVega; return pricing; } /** * @dev Gets seconds to expiry. */ function timeToMaturitySeconds(uint expiry) internal view returns (uint timeToMaturity) { if (expiry > block.timestamp) { timeToMaturity = expiry - block.timestamp; } else { timeToMaturity = 0; } } }
26,683
28
// Swap BUIDL for ETH and USDC in UniswapV2
uniswapV2( stateHolder, tokenAmountToSwapForEtherInV2, tokenAmountToSwapForUSDCInV2, tokenToSwap, dfoWalletAddress );
uniswapV2( stateHolder, tokenAmountToSwapForEtherInV2, tokenAmountToSwapForUSDCInV2, tokenToSwap, dfoWalletAddress );
35,637
5
// receiveApproval服务合约指示代币合约将代币从发送者的账户转移到服务合约的账户(通过调用服务合约的 /
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
23,768
18
// accumulated instrumental since vesting inception
uint256 accumulatedInstrumental = block .number .sub(vest.start) .mul(vest.instrumentalPerBlock) .mul(getBoost(vid, volume, proof)) .add(vest.initialRewards) .mul(userShare); uint256 maxAccumulatedInstrumental = accumulatedInstrumental > maxRewards ? maxRewards
uint256 accumulatedInstrumental = block .number .sub(vest.start) .mul(vest.instrumentalPerBlock) .mul(getBoost(vid, volume, proof)) .add(vest.initialRewards) .mul(userShare); uint256 maxAccumulatedInstrumental = accumulatedInstrumental > maxRewards ? maxRewards
63,863
259
// calculate amount based on ETH/USD ratefor example 2e1736900 / 60 = 1231e180.2 eth buys 123 tokens if Ether price is $369 and token price is 60 cents /
uint tokenAmount;
uint tokenAmount;
43,224
67
// Sets deltas to a receiver from now to `timeEnd`/receiverAddr The address of the receiver/amtPerSecDelta Change of the per-second receiving rate/timeEnd The timestamp from which the delta stops taking effect
function setReceiverDeltaFromNow( address receiverAddr, int128 amtPerSecDelta, uint64 timeEnd
function setReceiverDeltaFromNow( address receiverAddr, int128 amtPerSecDelta, uint64 timeEnd
1,267
117
// add liquidity
swapAndLiquify(contractTokenBalance);
swapAndLiquify(contractTokenBalance);
2,748
4
// s {string} name - the name of the contract Addresss {address} newAddress
function addAddress(string name, address newAddress) public onlyOwner { bytes32 contAddId = stringToBytes32(name); uint nowInMilliseconds = now * 1000; if (contractsAddress[contAddId].id == 0x0) { ContractAddress memory newContractAddress; newContractAddress.id = contAddId; newContractAddress.name = name; newContractAddress.at = newAddress;
function addAddress(string name, address newAddress) public onlyOwner { bytes32 contAddId = stringToBytes32(name); uint nowInMilliseconds = now * 1000; if (contractsAddress[contAddId].id == 0x0) { ContractAddress memory newContractAddress; newContractAddress.id = contAddId; newContractAddress.name = name; newContractAddress.at = newAddress;
28,472
20
// structure for liver disease
struct liver{ string diseases; }
struct liver{ string diseases; }
14,503
586
// Libertas-7.04 MKR - 0xE1eBfFa01883EF2b4A9f59b587fFf1a5B44dbb2f
MKR.transfer(LIBERTAS, 7.04 ether); // note: ether is a keyword helper, only MKR is transferred here
MKR.transfer(LIBERTAS, 7.04 ether); // note: ether is a keyword helper, only MKR is transferred here
14,213
2
// This event tracks pool creations from this factory/pool the address of the pool/bondToken The token of the bond token in this pool
event CCPoolCreated(address indexed pool, address indexed bondToken);
event CCPoolCreated(address indexed pool, address indexed bondToken);
72,227
167
// We use this function when withdraw right from pool. No transfer because after that we burn this amount from contract.
function withdrawAllStateUpdateByPool(address holder) external nonReentrant returns (uint256)
function withdrawAllStateUpdateByPool(address holder) external nonReentrant returns (uint256)
6,317
191
// safe math not needed hereapr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR); uint256 wantCallCost = _callCostToWant(callCost); return (wantCallCost.mul(profitFactor) < profitIncrease);
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR); uint256 wantCallCost = _callCostToWant(callCost); return (wantCallCost.mul(profitFactor) < profitIncrease);
3,144
9
// dispatchTransferFrom errors /
string constant ASSET_PROXY_DOES_NOT_EXIST = "ASSET_PROXY_DOES_NOT_EXIST"; // No assetProxy registered at given id. string constant TRANSFER_FAILED = "TRANSFER_FAILED"; // Asset transfer unsuccesful.
string constant ASSET_PROXY_DOES_NOT_EXIST = "ASSET_PROXY_DOES_NOT_EXIST"; // No assetProxy registered at given id. string constant TRANSFER_FAILED = "TRANSFER_FAILED"; // Asset transfer unsuccesful.
49,721
57
// Adds a bytes value to the request with a given key name self The initialized request _key The name of the key _value The bytes value to add /
function addBytes(Request memory self, string memory _key, bytes memory _value) internal pure
function addBytes(Request memory self, string memory _key, bytes memory _value) internal pure
18,509
94
// notice total UBXT rewards for distribution
uint256 totalUBXTReward;
uint256 totalUBXTReward;
6,575
35
// Implementation template Do something
} else if (sig == bytes4(keccak256(bytes("handlerFunction_2()")))) {
} else if (sig == bytes4(keccak256(bytes("handlerFunction_2()")))) {
3,867
22
// Compound pending fees/ return baseToken0Owed Pending fees of base token0/ return baseToken1Owed Pending fees of base token1/ return limitToken0Owed Pending fees of limit token0/ return limitToken1Owed Pending fees of limit token1
function compound() external onlyOwner returns ( uint128 baseToken0Owed, uint128 baseToken1Owed, uint128 limitToken0Owed, uint128 limitToken1Owed, uint256[4] memory inMin
function compound() external onlyOwner returns ( uint128 baseToken0Owed, uint128 baseToken1Owed, uint128 limitToken0Owed, uint128 limitToken1Owed, uint256[4] memory inMin
77,738
68
// triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event NewSmartToken(address _token);
event NewSmartToken(address _token);
28,847
103
// Transfers ownership of the contract to a new account (`_candidate`).Can only be called by the new owner. /
function updateOwner() public { require(_candidate != address(0), "PerpFiOwnableUpgrade: candidate is zero address"); require(_candidate == _msgSender(), "PerpFiOwnableUpgrade: not the new owner"); emit OwnershipTransferred(_owner, _candidate); _owner = _candidate; _candidate = address(0); }
function updateOwner() public { require(_candidate != address(0), "PerpFiOwnableUpgrade: candidate is zero address"); require(_candidate == _msgSender(), "PerpFiOwnableUpgrade: not the new owner"); emit OwnershipTransferred(_owner, _candidate); _owner = _candidate; _candidate = address(0); }
27,090
486
// Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address platformFeeRecipient, uint16 platformFeeBps);
function getPlatformFeeInfo() external view returns (address platformFeeRecipient, uint16 platformFeeBps);
71,877
25
// if the canonical super token address exists, revert with custom error
if (canonicalSuperTokenAddress != address(0)) { revert SUPER_TOKEN_FACTORY_ALREADY_EXISTS(); }
if (canonicalSuperTokenAddress != address(0)) { revert SUPER_TOKEN_FACTORY_ALREADY_EXISTS(); }
11,207
14
// ============ External ============ //Reads value of oracle and coerces return to uint256 then applies price multiplier returns Chainlink oracle price in uint256 /
function read() external view returns (uint256)
function read() external view returns (uint256)
21,381
48
// Determine the amount to repay.
uint256 repayAmount = getRepayAmount(amount); address bank = FlashLender(lender).bank();
uint256 repayAmount = getRepayAmount(amount); address bank = FlashLender(lender).bank();
68,330
82
// Aprove an allowance for admin account
adminAddress = 0xe0509bB3921aacc433108D403f020a7c2f92e936; approve(adminAddress, ADMIN_ALLOWANCE); participantCapTier1 = 100 ether; participantCapTier2 = 100 ether; poolAddressCapTier1 = 2000 ether; poolAddressCapTier2 = 2000 ether; weiRaised = 0; startTimePresale = 0;
adminAddress = 0xe0509bB3921aacc433108D403f020a7c2f92e936; approve(adminAddress, ADMIN_ALLOWANCE); participantCapTier1 = 100 ether; participantCapTier2 = 100 ether; poolAddressCapTier1 = 2000 ether; poolAddressCapTier2 = 2000 ether; weiRaised = 0; startTimePresale = 0;
9,331
14
// Get the factory's ownership of Option.Should be the amount it can still mint.NOTE: Called by `canMint` /
function balanceOf( address _owner, uint256 _optionId
function balanceOf( address _owner, uint256 _optionId
9,411
109
// called by providers
function migrateProvider(address _newProvider) external onlyAllowed { JointProvider newProvider = JointProvider(_newProvider); if (newProvider.want() == tokenA) { providerA = newProvider; } else if (newProvider.want() == tokenB) { providerB = newProvider; } else { revert("Unsupported token"); } }
function migrateProvider(address _newProvider) external onlyAllowed { JointProvider newProvider = JointProvider(_newProvider); if (newProvider.want() == tokenA) { providerA = newProvider; } else if (newProvider.want() == tokenB) { providerB = newProvider; } else { revert("Unsupported token"); } }
46,875
123
// https:docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress( name, string(abi.encodePacked("Resolver missing target: ", name)) ); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); }
contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress( name, string(abi.encodePacked("Resolver missing target: ", name)) ); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); }
4,854
101
// Official record of token balances for each account /
mapping(address => uint256) internal accountTokens;
mapping(address => uint256) internal accountTokens;
787
59
// Voting power of an address
mapping(address => uint256) votePower;
mapping(address => uint256) votePower;
41,336
538
// Get total delegation from a given address _delegator - delegator address /
function getTotalDelegatorStake(address _delegator) external view returns (uint256)
function getTotalDelegatorStake(address _delegator) external view returns (uint256)
38,590
8
// {TransparentUpgradeableProxy-upgradeToAndCall}.Requirements:- This contract must be the admin of `proxy`. /
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data);
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data);
33,217
483
// Returns the linear interpolation between two market rates. The formula is/ slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity)/ interpolatedRate = slope(assetMaturity - shortMarket.maturity) + shortMarket.oracleRate
function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity
function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity
64,989
76
// NToken合约
interface INest_NToken { // 更改映射 function changeMapping (address voteFactory) external; }
interface INest_NToken { // 更改映射 function changeMapping (address voteFactory) external; }
6,270
69
// Address of methodologist which serves as providing methodology for the index
address public methodologist;
address public methodologist;
2,277
287
// Calculate how much the tokens cost. Overpayed purchases don't receive a return.
uint256 cost = uint256(_tokenAmount).mul(rate);
uint256 cost = uint256(_tokenAmount).mul(rate);
8,223
203
// Change delegation for `delegator` to `delegatee`.
* Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); }
* Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); }
4,287
86
// OK, check 3
function swapBack() internal swapping { uint256 dynamicLiquidityFee = isOverLiquified(targetLiquidity, targetLiquidityDenominator) ? 0 : liquidityFee; uint256 tokensToSell = swapThreshold.div(rate); uint256 amountToLiquify = tokensToSell.div(totalFee).mul(dynamicLiquidityFee).div(2); uint256 amountToSwap = tokensToSell.sub(amountToLiquify); address[] memory path = new address[](2); path[0] = address(this); path[1] = WBNB; uint256 balanceBefore = address(this).balance; router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); uint256 amountBNB = address(this).balance.sub(balanceBefore); uint256 totalBNBFee = totalFee.sub(dynamicLiquidityFee.div(2)); uint256 amountBNBLiquidity = amountBNB.mul(dynamicLiquidityFee).div(totalBNBFee).div(2); uint256 amountBNBReflection = amountBNB.mul(reflectionFee).div(totalBNBFee); uint256 amountBNBMarketing = amountBNB.mul(marketingFee).div(totalBNBFee); uint256 amountBNBDev = amountBNB.mul(devFee).div(totalBNBFee); try distributor.deposit{value: amountBNBReflection}() {} catch {} (bool tmpSuccess,) = payable(marketingFeeReceiver).call{value: amountBNBMarketing, gas: 30000}(""); (tmpSuccess,) = payable(devFeeReceiver).call{value: amountBNBDev, gas: 30000}(""); // only to supress warning msg tmpSuccess = false; if(amountToLiquify > 0){ router.addLiquidityETH{value: amountBNBLiquidity}( address(this), amountToLiquify, 0, 0, autoLiquidityReceiver, block.timestamp ); emit AutoLiquify(amountBNBLiquidity, amountToLiquify.div(rate)); } }
function swapBack() internal swapping { uint256 dynamicLiquidityFee = isOverLiquified(targetLiquidity, targetLiquidityDenominator) ? 0 : liquidityFee; uint256 tokensToSell = swapThreshold.div(rate); uint256 amountToLiquify = tokensToSell.div(totalFee).mul(dynamicLiquidityFee).div(2); uint256 amountToSwap = tokensToSell.sub(amountToLiquify); address[] memory path = new address[](2); path[0] = address(this); path[1] = WBNB; uint256 balanceBefore = address(this).balance; router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); uint256 amountBNB = address(this).balance.sub(balanceBefore); uint256 totalBNBFee = totalFee.sub(dynamicLiquidityFee.div(2)); uint256 amountBNBLiquidity = amountBNB.mul(dynamicLiquidityFee).div(totalBNBFee).div(2); uint256 amountBNBReflection = amountBNB.mul(reflectionFee).div(totalBNBFee); uint256 amountBNBMarketing = amountBNB.mul(marketingFee).div(totalBNBFee); uint256 amountBNBDev = amountBNB.mul(devFee).div(totalBNBFee); try distributor.deposit{value: amountBNBReflection}() {} catch {} (bool tmpSuccess,) = payable(marketingFeeReceiver).call{value: amountBNBMarketing, gas: 30000}(""); (tmpSuccess,) = payable(devFeeReceiver).call{value: amountBNBDev, gas: 30000}(""); // only to supress warning msg tmpSuccess = false; if(amountToLiquify > 0){ router.addLiquidityETH{value: amountBNBLiquidity}( address(this), amountToLiquify, 0, 0, autoLiquidityReceiver, block.timestamp ); emit AutoLiquify(amountBNBLiquidity, amountToLiquify.div(rate)); } }
18,241
2
// emitted when the owner updates the edition override for secondary royalty
event EditionRoyaltyPercentageUpdated( uint256 indexed _editionId, uint256 _percentage );
event EditionRoyaltyPercentageUpdated( uint256 indexed _editionId, uint256 _percentage );
40,251
5
// Function to activate emergency pause. This should stop buying activity on all offeringsOnly Emergency Multisig wallet should be able to call this /
function emergencyPause() onlyEmergencyMultisig public { isEmergencyPaused = true; }
function emergencyPause() onlyEmergencyMultisig public { isEmergencyPaused = true; }
7,434
25
// Transfer `amount_` tokens from _msgSender() (msg.sender) to `recipient_` Requirements: - `recipient` cannot be the zero address.- the caller must have a balance of at least `amount`. /
function transfer(address recipient_, uint256 amount_) public returns (bool) { _transfer(_msgSender(), recipient_, amount_); return true; }
function transfer(address recipient_, uint256 amount_) public returns (bool) { _transfer(_msgSender(), recipient_, amount_); return true; }
4,289
94
// Partitioning a subset of outcomes for the condition in this branch. For example, for a condition with three outcomes A, B, and C, this branch allows the splitting of a position $:(A|C) to positions $:(A) and $:(C).
_burn( msg.sender, CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, fullIndexSet ^ freeIndexSet)), amount );
_burn( msg.sender, CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, fullIndexSet ^ freeIndexSet)), amount );
24,241
1
// truncation ErrorIn Solidity, a loss of accuracy may occur when a longer integer is cast to a shorter one.
require(balances[msg.sender] + uint32(msg.value) >= balances[msg.sender]); balances[msg.sender] += uint32(msg.value);
require(balances[msg.sender] + uint32(msg.value) >= balances[msg.sender]); balances[msg.sender] += uint32(msg.value);
51,033
291
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
5,681
21
// each eMode category may or may not have a custom oracle to override the individual assets price oracles
address priceSource; string label;
address priceSource; string label;
22,056
44
// Now have AMPL so send reward to caller and rest to fee distributor
uint256 reward = _getReward(info); // Reward rate for this borrowable uint256 rewardAmount = gremlinBalanceChange.mul(reward).div(REWARD_SCALE); if (rewardAmount > 0) { AMPL.safeTransfer(to, rewardAmount); }
uint256 reward = _getReward(info); // Reward rate for this borrowable uint256 rewardAmount = gremlinBalanceChange.mul(reward).div(REWARD_SCALE); if (rewardAmount > 0) { AMPL.safeTransfer(to, rewardAmount); }
16,148
61
// Offers to direct listings cannot be made directly in native tokens.
newOffer.currency = _currency == CurrencyTransferLib.NATIVE_TOKEN ? nativeTokenWrapper : _currency; newOffer.quantityWanted = getSafeQuantity(targetListing.tokenType, _quantityWanted); handleOffer(targetListing, newOffer);
newOffer.currency = _currency == CurrencyTransferLib.NATIVE_TOKEN ? nativeTokenWrapper : _currency; newOffer.quantityWanted = getSafeQuantity(targetListing.tokenType, _quantityWanted); handleOffer(targetListing, newOffer);
4,086
8
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
29,008
108
// duration of the vesting period in seconds
uint256 duration;
uint256 duration;
68,163
44
// Returns the length of a null-terminated bytes32 string. self The value to find the length of.return The length of the string, from 0 to 32. /
function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (uint(self) & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (uint(self) & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (uint(self) & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (uint(self) & 0xff == 0) { ret += 1; } return 32 - ret; }
function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (uint(self) & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (uint(self) & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (uint(self) & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (uint(self) & 0xff == 0) { ret += 1; } return 32 - ret; }
2,346
34
// Fetch the user's balance return balance The user's balance/
function fetchMyBalance() external view
function fetchMyBalance() external view
28,720
312
// Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission managerGrant `_entity` the ability to perform actions requiring `_role` on `_app`_entity Address of the whitelisted entity that will be able to perform the role_app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)_role Identifier for the group of actions in app given access to perform_params Permission parameters/
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role)
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role)
49,072
31
// Store the function selector of `HexLengthInsufficient()`.
mstore(0x00, 0x2194895a)
mstore(0x00, 0x2194895a)
13,056
1
// ============ Function to Receive ETH ============
receive() external payable { totalReceived += msg.value; montageFee = msg.value * shareDetails[4] / totalShares; _transfer(marketWallet, montageFee); montageFee = 0; emit FeeReceived(address(this), msg.value); }
receive() external payable { totalReceived += msg.value; montageFee = msg.value * shareDetails[4] / totalShares; _transfer(marketWallet, montageFee); montageFee = 0; emit FeeReceived(address(this), msg.value); }
5,412
1
// Normal execution
uint constant NO_ERROR = 0;
uint constant NO_ERROR = 0;
52,018
154
// calculate amount of SDA available for claim by depositor_depositor address return pendingPayout_ uint /
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = ISSDA(sSDA).balanceForGons(_bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = 0; } }
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = ISSDA(sSDA).balanceForGons(_bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = 0; } }
48,463
48
// _owner The owner whose space tokens we are interested in./This method MUST NEVER be called by smart contract code. First, it's fairly/expensive (it walks the entire Persons array looking for persons belonging to owner),/but it also returns a dynamic array, which is only supported for web3 calls, and/not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPersons = totalSupply(); uint256 resultIndex = 0; uint256 personId; for (personId = 0; personId <= totalPersons; personId++) { if (personIndexToOwner[personId] == _owner) { result[resultIndex] = personId; resultIndex++; } } return result; } }
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPersons = totalSupply(); uint256 resultIndex = 0; uint256 personId; for (personId = 0; personId <= totalPersons; personId++) { if (personIndexToOwner[personId] == _owner) { result[resultIndex] = personId; resultIndex++; } } return result; } }
3,447
22
// ERC20 backwards compatible transferFrom/_from The address holding the tokens being transferred/_to The address of the recipient/_amount The number of tokens to be transferred/ return `true`, if the transfer can't be done, it should fail.
function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(_from, _to, _amount, "", msg.sender, "", false); return true; }
function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(_from, _to, _amount, "", msg.sender, "", false); return true; }
15,221
30
// Request subscription owner transfer. subId - ID of the subscription newOwner - proposed new owner of the subscription /
function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;
function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;
50,617
185
// Transfer WETH from the buyer to the seller.
_transferERC20TokensFrom(WETH, msg.sender, sellOrder.maker, erc20FillAmount); if (ethAvailable > 0) { if (ethAvailable < totalFeesPaid) {
_transferERC20TokensFrom(WETH, msg.sender, sellOrder.maker, erc20FillAmount); if (ethAvailable > 0) { if (ethAvailable < totalFeesPaid) {
43,229
167
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
34,831
1
// --- Tolerances ---/Scale used to define percentages. Percentages are defined as tolerance / scale
uint256 public constant scale = 1000;
uint256 public constant scale = 1000;
72,012
395
// round 50
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
49,264
60
// function is used to make a rental offer for a specific user for a given NFT.
function makeNFTRentOfferForUser( uint256 tokenId, uint256 _price, uint256 _percentage, uint256 _time, address user
function makeNFTRentOfferForUser( uint256 tokenId, uint256 _price, uint256 _percentage, uint256 _time, address user
20,922
82
// apply a bonus if any (10SET)
uint256 tokensWithoutBonus = limitedInvestValue.mul(price).div(1 ether); uint256 tokensWithBonus = tokensWithoutBonus; if (milestone.bonus > 0) { tokensWithBonus = tokensWithoutBonus.add(tokensWithoutBonus.mul(milestone.bonus).div(percentRate)); }
uint256 tokensWithoutBonus = limitedInvestValue.mul(price).div(1 ether); uint256 tokensWithBonus = tokensWithoutBonus; if (milestone.bonus > 0) { tokensWithBonus = tokensWithoutBonus.add(tokensWithoutBonus.mul(milestone.bonus).div(percentRate)); }
50,480
48
// Internal functions
function _balanceProportion(int24 _tickLower, int24 _tickUpper) internal { PoolVariables.Info memory _cache; _cache.amount0Desired = token0.balanceOf(address(this)); _cache.amount1Desired = token1.balanceOf(address(this)); //Get Max Liquidity for Amounts we own. _cache.liquidity = pool.liquidityForAmounts( _cache.amount0Desired, _cache.amount1Desired, _tickLower, _tickUpper ); //Get correct amounts of each token for the liquidity we have. (_cache.amount0, _cache.amount1) = pool.amountsForLiquidity( _cache.liquidity, _tickLower, _tickUpper ); //Determine Trade Direction bool _zeroForOne; if (_cache.amount1Desired == 0) { _zeroForOne = true; } else { _zeroForOne = PoolVariables.amountsDirection( _cache.amount0Desired, _cache.amount1Desired, _cache.amount0, _cache.amount1 ); } //Determine Amount to swap uint256 _amountSpecified = _zeroForOne ? (_cache.amount0Desired.sub(_cache.amount0).div(2)) : (_cache.amount1Desired.sub(_cache.amount1).div(2)); if (_amountSpecified > 0) { //Determine Token to swap address _inputToken = _zeroForOne ? address(token0) : address(token1); IERC20(_inputToken).safeApprove(univ3Router, 0); IERC20(_inputToken).safeApprove(univ3Router, _amountSpecified); //Swap the token imbalanced ISwapRouter(univ3Router).exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: _inputToken, tokenOut: _zeroForOne ? address(token1) : address(token0), fee: pool.fee(), recipient: address(this), amountIn: _amountSpecified, amountOutMinimum: 0, sqrtPriceLimitX96: 0 }) ); } }
function _balanceProportion(int24 _tickLower, int24 _tickUpper) internal { PoolVariables.Info memory _cache; _cache.amount0Desired = token0.balanceOf(address(this)); _cache.amount1Desired = token1.balanceOf(address(this)); //Get Max Liquidity for Amounts we own. _cache.liquidity = pool.liquidityForAmounts( _cache.amount0Desired, _cache.amount1Desired, _tickLower, _tickUpper ); //Get correct amounts of each token for the liquidity we have. (_cache.amount0, _cache.amount1) = pool.amountsForLiquidity( _cache.liquidity, _tickLower, _tickUpper ); //Determine Trade Direction bool _zeroForOne; if (_cache.amount1Desired == 0) { _zeroForOne = true; } else { _zeroForOne = PoolVariables.amountsDirection( _cache.amount0Desired, _cache.amount1Desired, _cache.amount0, _cache.amount1 ); } //Determine Amount to swap uint256 _amountSpecified = _zeroForOne ? (_cache.amount0Desired.sub(_cache.amount0).div(2)) : (_cache.amount1Desired.sub(_cache.amount1).div(2)); if (_amountSpecified > 0) { //Determine Token to swap address _inputToken = _zeroForOne ? address(token0) : address(token1); IERC20(_inputToken).safeApprove(univ3Router, 0); IERC20(_inputToken).safeApprove(univ3Router, _amountSpecified); //Swap the token imbalanced ISwapRouter(univ3Router).exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: _inputToken, tokenOut: _zeroForOne ? address(token1) : address(token0), fee: pool.fee(), recipient: address(this), amountIn: _amountSpecified, amountOutMinimum: 0, sqrtPriceLimitX96: 0 }) ); } }
22,406
34
// Withdraw all ERC20 compatible tokens token ERC20 The address of the token contract /
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); TokenWithdraw(token, amount, sendTo); }
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); TokenWithdraw(token, amount, sendTo); }
33,528