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
19
// Function to check the amount of tokens that an owner allowed to a spender. _owner address The address which owns the funds. _spender address The address which will spend the funds.return A uint256 specifying the amount of tokens still available for the spender. /
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
52,554
4
// check return/returns
function getCampaigns() public view returns (Campaign[] memory) { Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns); for (uint i=0; i<numberOfCampaigns; i++) { Campaign storage item = campaigns[i]; // memory or storage ??, campaigns is of type storage, so, item will also be type of storage allCampaigns[i] = item; } return allCampaigns; }
function getCampaigns() public view returns (Campaign[] memory) { Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns); for (uint i=0; i<numberOfCampaigns; i++) { Campaign storage item = campaigns[i]; // memory or storage ??, campaigns is of type storage, so, item will also be type of storage allCampaigns[i] = item; } return allCampaigns; }
5,816
1
// MINTING LIMITS /
function allowedMintCount(address minter) public view returns (uint256) { return MINT_LIMIT_PER_WALLET - mintCountMap[minter]; }
function allowedMintCount(address minter) public view returns (uint256) { return MINT_LIMIT_PER_WALLET - mintCountMap[minter]; }
1,312
5
// We offset the load address by 21 byte (operation byte + 20 address bytes)
let value := mload(add(transactions, add(i, 0x15)))
let value := mload(add(transactions, add(i, 0x15)))
26,413
21
// head
rarities[7] = [243]; aliases[7] = [1];
rarities[7] = [243]; aliases[7] = [1];
31,701
32
// Based on the OpenZepplin ERC721 implementation, licensed under MIT
contract NFTImplementation is NFTState, Context, IERC721, IERC721Metadata, ERC165 { using Address for address; using Strings for uint256; function initialize( string memory name_, string memory symbol_, address owner_, uint16 chainId_, bytes32 nativeContract_ ) initializer public { _state.name = name_; _state.symbol = symbol_; _state.owner = owner_; _state.chainId = chainId_; _state.nativeContract = nativeContract_; } function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner_) public view override returns (uint256) { require(owner_ != address(0), "ERC721: balance query for the zero address"); return _state.balances[owner_]; } function ownerOf(uint256 tokenId) public view override returns (address) { address owner_ = _state.owners[tokenId]; require(owner_ != address(0), "ERC721: owner query for nonexistent token"); return owner_; } function name() public view override returns (string memory) { return _state.name; } function symbol() public view override returns (string memory) { return _state.symbol; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _state.tokenURIs[tokenId]; } function chainId() public view returns (uint16) { return _state.chainId; } function nativeContract() public view returns (bytes32) { return _state.nativeContract; } function owner() public view returns (address) { return _state.owner; } function approve(address to, uint256 tokenId) public override { address owner_ = NFTImplementation.ownerOf(tokenId); require(to != owner_, "ERC721: approval to current owner"); require( _msgSender() == owner_ || isApprovedForAll(owner_, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _state.tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721: approve to caller"); _state.operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner_, address operator) public view override returns (bool) { return _state.operatorApprovals[owner_][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view returns (bool) { return _state.owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner_ = NFTImplementation.ownerOf(tokenId); return (spender == owner_ || getApproved(tokenId) == spender || isApprovedForAll(owner_, spender)); } function mint(address to, uint256 tokenId, string memory uri) public onlyOwner { _mint(to, tokenId, uri); } function _mint(address to, uint256 tokenId, string memory uri) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _state.balances[to] += 1; _state.owners[tokenId] = to; _state.tokenURIs[tokenId] = uri; emit Transfer(address(0), to, tokenId); } function burn(uint256 tokenId) public onlyOwner { _burn(tokenId); } function _burn(uint256 tokenId) internal { address owner_ = NFTImplementation.ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); _state.balances[owner_] -= 1; delete _state.owners[tokenId]; emit Transfer(owner_, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal { require(NFTImplementation.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _state.balances[from] -= 1; _state.balances[to] += 1; _state.owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal { _state.tokenApprovals[tokenId] = to; emit Approval(NFTImplementation.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } modifier onlyOwner() { require(owner() == _msgSender(), "caller is not the owner"); _; } modifier initializer() { require( !_state.initialized, "Already initialized" ); _state.initialized = true; _; } }
contract NFTImplementation is NFTState, Context, IERC721, IERC721Metadata, ERC165 { using Address for address; using Strings for uint256; function initialize( string memory name_, string memory symbol_, address owner_, uint16 chainId_, bytes32 nativeContract_ ) initializer public { _state.name = name_; _state.symbol = symbol_; _state.owner = owner_; _state.chainId = chainId_; _state.nativeContract = nativeContract_; } function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner_) public view override returns (uint256) { require(owner_ != address(0), "ERC721: balance query for the zero address"); return _state.balances[owner_]; } function ownerOf(uint256 tokenId) public view override returns (address) { address owner_ = _state.owners[tokenId]; require(owner_ != address(0), "ERC721: owner query for nonexistent token"); return owner_; } function name() public view override returns (string memory) { return _state.name; } function symbol() public view override returns (string memory) { return _state.symbol; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _state.tokenURIs[tokenId]; } function chainId() public view returns (uint16) { return _state.chainId; } function nativeContract() public view returns (bytes32) { return _state.nativeContract; } function owner() public view returns (address) { return _state.owner; } function approve(address to, uint256 tokenId) public override { address owner_ = NFTImplementation.ownerOf(tokenId); require(to != owner_, "ERC721: approval to current owner"); require( _msgSender() == owner_ || isApprovedForAll(owner_, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _state.tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721: approve to caller"); _state.operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner_, address operator) public view override returns (bool) { return _state.operatorApprovals[owner_][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view returns (bool) { return _state.owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner_ = NFTImplementation.ownerOf(tokenId); return (spender == owner_ || getApproved(tokenId) == spender || isApprovedForAll(owner_, spender)); } function mint(address to, uint256 tokenId, string memory uri) public onlyOwner { _mint(to, tokenId, uri); } function _mint(address to, uint256 tokenId, string memory uri) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _state.balances[to] += 1; _state.owners[tokenId] = to; _state.tokenURIs[tokenId] = uri; emit Transfer(address(0), to, tokenId); } function burn(uint256 tokenId) public onlyOwner { _burn(tokenId); } function _burn(uint256 tokenId) internal { address owner_ = NFTImplementation.ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); _state.balances[owner_] -= 1; delete _state.owners[tokenId]; emit Transfer(owner_, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal { require(NFTImplementation.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _state.balances[from] -= 1; _state.balances[to] += 1; _state.owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal { _state.tokenApprovals[tokenId] = to; emit Approval(NFTImplementation.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } modifier onlyOwner() { require(owner() == _msgSender(), "caller is not the owner"); _; } modifier initializer() { require( !_state.initialized, "Already initialized" ); _state.initialized = true; _; } }
74,663
0
// How many seconds the user has to wait between initiating the transaction and finalizing the transaction. This cannot be changed.
uint delay; address added_by; uint time_added; address removed_by; uint time_removed;
uint delay; address added_by; uint time_added; address removed_by; uint time_removed;
14,584
30
// Only fall back when the sender is not the admin. /
function _willFallback() virtual override internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); //super._willFallback(); }
function _willFallback() virtual override internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); //super._willFallback(); }
741
137
// uint256 oddEth = wethAmount.sub(totalEthSwap); if (oddEth > 0) { weth.withdraw(oddEth); msg.sender.transfer(oddEth); emit OddEth(msg.sender, oddEth); }
return (poolAmountOut, 0);
return (poolAmountOut, 0);
34,483
62
// Internal transfer, can only be called by this contractfrom The sender of the tokens. to The recipient of the tokens. valueThe number of tokens to send. /
function _transfer(address from, address to, uint256 value) internal returns (bool) { require(isAuthorised(to), "Target of transfer has not passed KYC"); require(from != address(0x0), "Cannot send tokens from null address"); require(to != address(0x0), "Cannot transfer tokens to null"); require(balances[from] >= value, "Insufficient funds"); // Quick exit for zero, but allow it in case this transfer is part of a chain. if(value == 0) return true; // Perform the transfer. balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); // Any tokens sent to to owner are implicitly burned. if (to == owner) { _burn(to, value); } emit Transfer(from, to, value); return true; }
function _transfer(address from, address to, uint256 value) internal returns (bool) { require(isAuthorised(to), "Target of transfer has not passed KYC"); require(from != address(0x0), "Cannot send tokens from null address"); require(to != address(0x0), "Cannot transfer tokens to null"); require(balances[from] >= value, "Insufficient funds"); // Quick exit for zero, but allow it in case this transfer is part of a chain. if(value == 0) return true; // Perform the transfer. balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); // Any tokens sent to to owner are implicitly burned. if (to == owner) { _burn(to, value); } emit Transfer(from, to, value); return true; }
7,207
26
// LiquidationTriggerSimple Manages triggering of liquidation process /
abstract contract LiquidationTriggerBase { using SafeMath for uint; uint public constant DENOMINATOR_1E5 = 1e5; uint public constant DENOMINATOR_1E2 = 1e2; // vault manager parameters contract VaultManagerParameters public immutable vaultManagerParameters; uint public immutable oracleType; // Vault contract Vault public immutable vault; /** * @dev Trigger when liquidations are initiated **/ event LiquidationTriggered(address indexed token, address indexed user); /** * @param _vaultManagerParameters The address of the contract with vault manager parameters * @param _oracleType The id of the oracle type **/ constructor(address _vaultManagerParameters, uint _oracleType) internal { vaultManagerParameters = VaultManagerParameters(_vaultManagerParameters); vault = Vault(VaultManagerParameters(_vaultManagerParameters).vaultParameters().vault()); oracleType = _oracleType; } /** * @dev Triggers liquidation of a position * @param asset The address of the main collateral token of a position * @param user The owner of a position **/ function triggerLiquidation(address asset, address user) external virtual {} /** * @dev Determines whether a position is liquidatable * @param asset The address of the main collateral token of a position * @param user The owner of a position * @param collateralUsdValue USD value of the collateral * @return boolean value, whether a position is liquidatable **/ function isLiquidatablePosition( address asset, address user, uint collateralUsdValue ) public virtual view returns (bool); /** * @dev Calculates position's utilization ratio * @param collateralUsdValue USD value of collateral * @param debt USDP borrowed * @return utilization ratio of a position **/ function UR(uint collateralUsdValue, uint debt) public virtual pure returns (uint); }
abstract contract LiquidationTriggerBase { using SafeMath for uint; uint public constant DENOMINATOR_1E5 = 1e5; uint public constant DENOMINATOR_1E2 = 1e2; // vault manager parameters contract VaultManagerParameters public immutable vaultManagerParameters; uint public immutable oracleType; // Vault contract Vault public immutable vault; /** * @dev Trigger when liquidations are initiated **/ event LiquidationTriggered(address indexed token, address indexed user); /** * @param _vaultManagerParameters The address of the contract with vault manager parameters * @param _oracleType The id of the oracle type **/ constructor(address _vaultManagerParameters, uint _oracleType) internal { vaultManagerParameters = VaultManagerParameters(_vaultManagerParameters); vault = Vault(VaultManagerParameters(_vaultManagerParameters).vaultParameters().vault()); oracleType = _oracleType; } /** * @dev Triggers liquidation of a position * @param asset The address of the main collateral token of a position * @param user The owner of a position **/ function triggerLiquidation(address asset, address user) external virtual {} /** * @dev Determines whether a position is liquidatable * @param asset The address of the main collateral token of a position * @param user The owner of a position * @param collateralUsdValue USD value of the collateral * @return boolean value, whether a position is liquidatable **/ function isLiquidatablePosition( address asset, address user, uint collateralUsdValue ) public virtual view returns (bool); /** * @dev Calculates position's utilization ratio * @param collateralUsdValue USD value of collateral * @param debt USDP borrowed * @return utilization ratio of a position **/ function UR(uint collateralUsdValue, uint debt) public virtual pure returns (uint); }
60,789
5
// 0,000000000000001
mapping(uint256 => ItemData) public items; uint256 itemIndex; event SupplyChainStep( uint256 _itemIndex, uint256 _step, address _itemAddress ); function createItem(string memory _identifier, uint256 _itemPrice)
mapping(uint256 => ItemData) public items; uint256 itemIndex; event SupplyChainStep( uint256 _itemIndex, uint256 _step, address _itemAddress ); function createItem(string memory _identifier, uint256 _itemPrice)
30,660
4
// ========================================================================================= //User-facing// ========================================================================================= //Mint xAssetCLR tokens by sending amount of inputAsset tokensamount of the other asset is auto-calculated /
function mint(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused()
function mint(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused()
56,172
521
// Returns the address of a valid Uniswap V3 Pool/factory The contract address of the Uniswap V3 factory/tokenA The contract address of either token0 or token1/tokenB The contract address of the other token/fee The fee collected upon every swap in the pool, denominated in hundredths of a bip/ return pool The V3 pool contract address
function verifyCallback( address factory, address tokenA, address tokenB, uint24 fee
function verifyCallback( address factory, address tokenA, address tokenB, uint24 fee
24,127
15
// 1. verify price and not address(0)
require(payAmount >= amount, "Price issue");
require(payAmount >= amount, "Price issue");
608
14
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
27,524
272
// Internal function to submit evidence for a dispute_disputeManager Dispute manager to be used_disputeId Id of the dispute in the Court_submitter Address of the account submitting the evidence_evidence Data submitted for the evidence related to the dispute/
function _submitEvidence(IDisputeManager _disputeManager, uint256 _disputeId, address _submitter, bytes memory _evidence) internal { IArbitrable subject = IArbitrable(msg.sender); _disputeManager.submitEvidence(subject, _disputeId, _submitter, _evidence); }
function _submitEvidence(IDisputeManager _disputeManager, uint256 _disputeId, address _submitter, bytes memory _evidence) internal { IArbitrable subject = IArbitrable(msg.sender); _disputeManager.submitEvidence(subject, _disputeId, _submitter, _evidence); }
69,032
103
// 40 = 2.5%
uint8 private lpRewardDivisor = 40;
uint8 private lpRewardDivisor = 40;
16,797
111
// Assert that amount of tokens to be withdrawn is less than amount of tokens unlocked
require(amountOfTokens < getAmountOfTokensUnlockedForWithdrawal(block.timestamp));
require(amountOfTokens < getAmountOfTokensUnlockedForWithdrawal(block.timestamp));
49,422
6
// EVENTS // CONSTRUCTOR & INITIALIZATION // Initializes the contract with immutable variables _weth is the Wrapped Ether contract _usdc is the USDC contract _wsteth is the LDO contract _ldo is the LDO contract _oTokenFactory is the contract address for minting new opyn option types (strikes, asset, expiry) _gammaController is the contract address for opyn actions _marginPool is the contract address for providing collateral to opyn _gnosisEasyAuction is the contract address that facilitates gnosis auctions _crvPool is the steth/eth crv stables pool /
constructor( address _weth, address _usdc, address _wsteth, address _ldo, address _oTokenFactory, address _gammaController, address _marginPool,
constructor( address _weth, address _usdc, address _wsteth, address _ldo, address _oTokenFactory, address _gammaController, address _marginPool,
71,048
38
// Base exchange rate is set to 1 ETH = 325000 MNT.
uint256 public constant BASE_RATE = 325000;
uint256 public constant BASE_RATE = 325000;
3,161
7
// Start a new period needs corresponding permissions for sender /
function startNewPeriod() public virtual override nextPeriodAvailable periodsActive nonReentrant { require(hasRole(CONTROLLER_ROLE, msg.sender), "ERR_CALLER"); _switchPeriod(); // Rate IBTRates[getCurrentPeriodIndex()] = getIBTRate(); // Stream scaledTotals[getCurrentPeriodIndex()] = ibt.balanceOf(address(this)); }
function startNewPeriod() public virtual override nextPeriodAvailable periodsActive nonReentrant { require(hasRole(CONTROLLER_ROLE, msg.sender), "ERR_CALLER"); _switchPeriod(); // Rate IBTRates[getCurrentPeriodIndex()] = getIBTRate(); // Stream scaledTotals[getCurrentPeriodIndex()] = ibt.balanceOf(address(this)); }
36,567
111
// Emits a {Contribution} event. Parameters:- `amount` is amount to contribute/
function contributeToken(uint256 amount) external nonReentrant whenNotPaused { require(WETH != address(contributionToken), "invalid token"); uint256 cAmount = contributeInternal(amount); contributionToken.safeTransferFrom(msg.sender, address(this), cAmount); emit Contribution(msg.sender, cAmount); }
function contributeToken(uint256 amount) external nonReentrant whenNotPaused { require(WETH != address(contributionToken), "invalid token"); uint256 cAmount = contributeInternal(amount); contributionToken.safeTransferFrom(msg.sender, address(this), cAmount); emit Contribution(msg.sender, cAmount); }
41,719
210
// Setter for arbitrationFeePerJuror._arbitrationFeePerJuror The fee which will be paid to each juror. /
function setArbitrationFeePerJuror(uint _arbitrationFeePerJuror) public onlyGovernor { arbitrationFeePerJuror = _arbitrationFeePerJuror; }
function setArbitrationFeePerJuror(uint _arbitrationFeePerJuror) public onlyGovernor { arbitrationFeePerJuror = _arbitrationFeePerJuror; }
76,125
12
// prevent price submission from being revealed twice
delete epochVoterHash[_epochId][_voter]; revealedPrices[_epochId][_voter] = _price;
delete epochVoterHash[_epochId][_voter]; revealedPrices[_epochId][_voter] = _price;
27,316
85
// Refund the highest bidder.
_refundHighestBid(listingId, listing);
_refundHighestBid(listingId, listing);
30,914
0
// Interface to NFT contract
interface wrappedcompanion{ ////Interface to RCVR function balanceOf(address owner) external view returns (uint256); function tokenURI(uint256 tokenId ) external view returns (string memory); function getArtApproval(uint _tokennumber,address _wallet)external view returns(bool); function ownerOf(uint256 tokenId) external view returns (address); }
interface wrappedcompanion{ ////Interface to RCVR function balanceOf(address owner) external view returns (uint256); function tokenURI(uint256 tokenId ) external view returns (string memory); function getArtApproval(uint _tokennumber,address _wallet)external view returns(bool); function ownerOf(uint256 tokenId) external view returns (address); }
52,893
4
// Remove oneself as a member of the community.
function leaveCommunity() public virtual { // Roles will check membership. renounceMembership(COMMUNITY_ROLE_ID); }
function leaveCommunity() public virtual { // Roles will check membership. renounceMembership(COMMUNITY_ROLE_ID); }
7,720
76
// freeze system' balance
function systemFreeze(uint256 _value, uint256 _unfreezeTime) internal { uint256 unfreezeIndex = uint256(_unfreezeTime.parseTimestamp().year) * 10000 + uint256(_unfreezeTime.parseTimestamp().month) * 100 + uint256(_unfreezeTime.parseTimestamp().day); balances[owner] = balances[owner].sub(_value); frozenRecords[unfreezeIndex] = FrozenRecord({value: _value, unfreezeIndex: unfreezeIndex});
function systemFreeze(uint256 _value, uint256 _unfreezeTime) internal { uint256 unfreezeIndex = uint256(_unfreezeTime.parseTimestamp().year) * 10000 + uint256(_unfreezeTime.parseTimestamp().month) * 100 + uint256(_unfreezeTime.parseTimestamp().day); balances[owner] = balances[owner].sub(_value); frozenRecords[unfreezeIndex] = FrozenRecord({value: _value, unfreezeIndex: unfreezeIndex});
63,575
19
// call the staking smart contract to init the epoch
epochs[epochId] = _getPoolSize(epochId);
epochs[epochId] = _getPoolSize(epochId);
48,069
66
// See OpenZeppelin ReentrancyGuard implementation
uint256 constant _NOT_ENTERED = 1; uint256 constant _ENTERED = 2; event PendingGovernorshipTransfer( address indexed previousGovernor, address indexed newGovernor ); event GovernorshipTransferred( address indexed previousGovernor,
uint256 constant _NOT_ENTERED = 1; uint256 constant _ENTERED = 2; event PendingGovernorshipTransfer( address indexed previousGovernor, address indexed newGovernor ); event GovernorshipTransferred( address indexed previousGovernor,
5,146
73
// Change game interval./
function toogleInterval() internal { uint256 interval = getCurrentInterval(); gameStartedAt += interval; isFristInterval = !isFristInterval; }
function toogleInterval() internal { uint256 interval = getCurrentInterval(); gameStartedAt += interval; isFristInterval = !isFristInterval; }
2,564
3,552
// 1778
entry "rememberingly" : ENG_ADVERB
entry "rememberingly" : ENG_ADVERB
22,614
17
// This event will be emitted every time the implementation gets upgradedversion representing the version name of the upgraded implementationimplementation representing the address of the upgraded implementation/
event Upgraded(string version, address indexed implementation);
event Upgraded(string version, address indexed implementation);
40,690
37
// troves can only be created after the token owner has been set. This is a safety check not security
require(address(tokenOwner_cached) != address(0x0), "66c10 the token owner must be set"); require(tokenOwner_cached.owner() == address(this), "66c10 the token owner's owner must be the trove factory");
require(address(tokenOwner_cached) != address(0x0), "66c10 the token owner must be set"); require(tokenOwner_cached.owner() == address(this), "66c10 the token owner's owner must be the trove factory");
20,525
26
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IVoteToken} from "contracts/governance/interface/IVoteToken.sol";
function stake(uint256 amount) external; function unstake(uint256 amount) external; function cooldown() external; function withdraw(uint256 amount) external; function claim() external;
function stake(uint256 amount) external; function unstake(uint256 amount) external; function cooldown() external; function withdraw(uint256 amount) external; function claim() external;
13,692
7
// Approve the MasterContract to transfer these BoringCryptoTokenScanner
lpToken.approve(address(chef), balance);
lpToken.approve(address(chef), balance);
50,306
67
// check that msg.value is higher than 0, don't really want to have to deal with minus in case the network breaks this somehow
if(allowedPaymentMethod(_payment_method) && canAcceptPayment(msg.value) ) { uint256 contributed_value = msg.value; uint256 amountOverCap = getValueOverCurrentCap(contributed_value); if ( amountOverCap > 0 ) {
if(allowedPaymentMethod(_payment_method) && canAcceptPayment(msg.value) ) { uint256 contributed_value = msg.value; uint256 amountOverCap = getValueOverCurrentCap(contributed_value); if ( amountOverCap > 0 ) {
50,019
4
// returns `2 ^ f` by calculating `e ^ (fln(2))`, where `e` is Euler's number:- Rewrite the input as a sum of binary exponents and a single residual r, as small as possible- The exponentiation of each binary exponent is given (pre-calculated)- The exponentiation of r is calculated via Taylor series for e^x, where x = r- The exponentiation of the input is calculated by multiplying the intermediate results above- For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4e^1e^0.5e^0.021692859 /
function exp2(Fraction memory f) internal pure returns (Fraction memory) { uint256 x = MathEx.mulDivF(LN2, f.n, f.d); uint256 y; uint256 z; uint256 n; if (x >= (ONE << 4)) { revert Overflow(); } unchecked { z = y = x % (ONE >> 3); // get the input modulo 2^(-3) z = (z * y) / ONE; n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / ONE; n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / ONE; n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / ONE; n += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / ONE; n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / ONE; n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / ONE; n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / ONE; n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / ONE; n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / ONE; n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / ONE; n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / ONE; n += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / ONE; n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / ONE; n += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / ONE; n += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / ONE; n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / ONE; n += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / ONE; n += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / ONE; n += z * 0x0000000000000001; // add y^20 * (20! / 20!) n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & (ONE >> 3)) != 0) n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^(2^-3) if ((x & (ONE >> 2)) != 0) n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^(2^-2) if ((x & (ONE >> 1)) != 0) n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^(2^-1) if ((x & (ONE << 0)) != 0) n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^(2^+0) if ((x & (ONE << 1)) != 0) n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^(2^+1) if ((x & (ONE << 2)) != 0) n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^(2^+2) if ((x & (ONE << 3)) != 0) n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^(2^+3) } return Fraction({ n: n, d: ONE }); }
function exp2(Fraction memory f) internal pure returns (Fraction memory) { uint256 x = MathEx.mulDivF(LN2, f.n, f.d); uint256 y; uint256 z; uint256 n; if (x >= (ONE << 4)) { revert Overflow(); } unchecked { z = y = x % (ONE >> 3); // get the input modulo 2^(-3) z = (z * y) / ONE; n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / ONE; n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / ONE; n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / ONE; n += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / ONE; n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / ONE; n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / ONE; n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / ONE; n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / ONE; n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / ONE; n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / ONE; n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / ONE; n += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / ONE; n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / ONE; n += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / ONE; n += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / ONE; n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / ONE; n += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / ONE; n += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / ONE; n += z * 0x0000000000000001; // add y^20 * (20! / 20!) n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & (ONE >> 3)) != 0) n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^(2^-3) if ((x & (ONE >> 2)) != 0) n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^(2^-2) if ((x & (ONE >> 1)) != 0) n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^(2^-1) if ((x & (ONE << 0)) != 0) n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^(2^+0) if ((x & (ONE << 1)) != 0) n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^(2^+1) if ((x & (ONE << 2)) != 0) n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^(2^+2) if ((x & (ONE << 3)) != 0) n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^(2^+3) } return Fraction({ n: n, d: ONE }); }
22,940
57
// only do real calculations if the windup time is over
uint256 realStart = start.add(batch.windup); if ( block.timestamp > realStart ) {
uint256 realStart = start.add(batch.windup); if ( block.timestamp > realStart ) {
35,608
7
// The block number when VXL mining starts.
uint256 public START_BLOCK;
uint256 public START_BLOCK;
16,711
8
// uint basePrice = 0.0005 ether;
uint basePrice = 0 ether; return basePrice + (totalSupply * 0.000001 ether);
uint basePrice = 0 ether; return basePrice + (totalSupply * 0.000001 ether);
17,573
110
// 2^x = 2^(floor(x))2^(x-floor(x)) ^^^^^^^^^^^^^^ is a bit shift of ceil(x) so Taylor expand on z = x-floor(x), z in [0, 1)
int shift; int z; if (x >= 0) { shift = x / int(ONE); z = x % int(ONE); }
int shift; int z; if (x >= 0) { shift = x / int(ONE); z = x % int(ONE); }
20,465
23
// Check if staker's balance is enough
require( _amount < ftgToken.balanceOf(msg.sender), "Insufficient FTG Balance" );
require( _amount < ftgToken.balanceOf(msg.sender), "Insufficient FTG Balance" );
37,498
11
// Get percentage of a total value totalAmount value equal to 100% of total quantity percentage percentage as integer i.e. 3 == 3% /
function getPercentageOf(uint256 totalAmount, uint256 percentage) public view returns(uint256)
function getPercentageOf(uint256 totalAmount, uint256 percentage) public view returns(uint256)
28,454
9
// Terminate flag
bool public terminated;
bool public terminated;
4,878
4
// Override to remove check that block exists /
function isDeposit(uint256 blockNum) public view returns (bool) { return blockNum % childBlockInterval != 0; }
function isDeposit(uint256 blockNum) public view returns (bool) { return blockNum % childBlockInterval != 0; }
23,259
38
// CelerIM Facet/LI.FI (https:li.fi)/Provides functionality for bridging tokens and data through CBridge/ @custom:version 1.0.1
contract CelerIMFacet is ILiFi, ReentrancyGuard, SwapperV2, Validatable { /// Storage /// /// @dev The contract address of the cBridge Message Bus IMessageBus private immutable cBridgeMessageBus; /// @dev The contract address of the RelayerCelerIM RelayerCelerIM private immutable relayer; /// @dev The contract address of the Celer Flow USDC address private immutable cfUSDC; /// Types /// /// @param maxSlippage The max slippage accepted, given as percentage in point (pip). /// @param nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice. /// @param callTo The address of the contract to be called at destination. /// @param callData The encoded calldata with below data /// bytes32 transactionId, /// LibSwap.SwapData[] memory swapData, /// address receiver, /// address refundAddress /// @param messageBusFee The fee to be paid to CBridge message bus for relaying the message /// @param bridgeType Defines the bridge operation type (must be one of the values of CBridge library MsgDataTypes.BridgeSendType) struct CelerIMData { uint32 maxSlippage; uint64 nonce; bytes callTo; bytes callData; uint256 messageBusFee; MsgDataTypes.BridgeSendType bridgeType; } /// Constructor /// /// @notice Initialize the contract. /// @param _messageBus The contract address of the cBridge Message Bus /// @param _relayer The contract address of the RelayerCelerIM /// @param _cfUSDC The contract address of the Celer Flow USDC constructor( IMessageBus _messageBus, RelayerCelerIM _relayer, address _cfUSDC ) { cBridgeMessageBus = _messageBus; relayer = _relayer; cfUSDC = _cfUSDC; } /// External Methods /// /// @notice Bridges tokens via CBridge /// @param _bridgeData The core information needed for bridging /// @param _celerIMData Data specific to CelerIM function startBridgeTokensViaCelerIM( ILiFi.BridgeData memory _bridgeData, CelerIMData calldata _celerIMData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) doesNotContainSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) { validateDestinationCallFlag(_bridgeData, _celerIMData); if (!LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { // Transfer ERC20 tokens directly to relayer IERC20 asset = _getRightAsset(_bridgeData.sendingAssetId); // Deposit ERC20 token uint256 prevBalance = asset.balanceOf(address(relayer)); SafeERC20.safeTransferFrom( asset, msg.sender, address(relayer), _bridgeData.minAmount ); if ( asset.balanceOf(address(relayer)) - prevBalance != _bridgeData.minAmount ) { revert InvalidAmount(); } } _startBridge(_bridgeData, _celerIMData); } /// @notice Performs a swap before bridging via CBridge /// @param _bridgeData The core information needed for bridging /// @param _swapData An array of swap related data for performing swaps before bridging /// @param _celerIMData Data specific to CelerIM function swapAndStartBridgeTokensViaCelerIM( ILiFi.BridgeData memory _bridgeData, LibSwap.SwapData[] calldata _swapData, CelerIMData calldata _celerIMData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) containsSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) { validateDestinationCallFlag(_bridgeData, _celerIMData); _bridgeData.minAmount = _depositAndSwap( _bridgeData.transactionId, _bridgeData.minAmount, _swapData, payable(msg.sender), _celerIMData.messageBusFee ); if (!LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { // Transfer ERC20 tokens directly to relayer IERC20 asset = _getRightAsset(_bridgeData.sendingAssetId); // Deposit ERC20 token uint256 prevBalance = asset.balanceOf(address(relayer)); SafeERC20.safeTransfer( asset, address(relayer), _bridgeData.minAmount ); if ( asset.balanceOf(address(relayer)) - prevBalance != _bridgeData.minAmount ) { revert InvalidAmount(); } } _startBridge(_bridgeData, _celerIMData); } /// Private Methods /// /// @dev Contains the business logic for the bridge via CBridge /// @param _bridgeData The core information needed for bridging /// @param _celerIMData Data specific to CBridge function _startBridge( ILiFi.BridgeData memory _bridgeData, CelerIMData calldata _celerIMData ) private { // Assuming messageBusFee is pre-calculated off-chain and available in _celerIMData // Determine correct native asset amount to be forwarded (if so) and send funds to relayer uint256 msgValue = LibAsset.isNativeAsset(_bridgeData.sendingAssetId) ? _bridgeData.minAmount : 0; // Check if transaction contains a destination call if (!_bridgeData.hasDestinationCall) { // Case 'no': Simple bridge transfer - Send to receiver relayer.sendTokenTransfer{ value: msgValue }( _bridgeData, _celerIMData ); } else { // Case 'yes': Bridge + Destination call - Send to relayer // save address of original recipient address receiver = _bridgeData.receiver; // Set relayer as a receiver _bridgeData.receiver = address(relayer); // send token transfer (bytes32 transferId, address bridgeAddress) = relayer .sendTokenTransfer{ value: msgValue }( _bridgeData, _celerIMData ); // Call message bus via relayer incl messageBusFee relayer.forwardSendMessageWithTransfer{ value: _celerIMData.messageBusFee }( _bridgeData.receiver, uint64(_bridgeData.destinationChainId), bridgeAddress, transferId, _celerIMData.callData ); // Reset receiver of bridge data for event emission _bridgeData.receiver = receiver; } // emit LiFi event emit LiFiTransferStarted(_bridgeData); } /// @dev Get right asset to transfer to relayer. /// @param _sendingAssetId The address of asset to bridge. /// @return _asset The address of asset to transfer to relayer. function _getRightAsset( address _sendingAssetId ) private returns (IERC20 _asset) { if (_sendingAssetId == cfUSDC) { // special case for cfUSDC token _asset = IERC20(CelerToken(_sendingAssetId).canonical()); } else { // any other ERC20 token _asset = IERC20(_sendingAssetId); } } function validateDestinationCallFlag( ILiFi.BridgeData memory _bridgeData, CelerIMData calldata _celerIMData ) private pure { if ( (_celerIMData.callData.length > 0) != _bridgeData.hasDestinationCall ) { revert InformationMismatch(); } } }
contract CelerIMFacet is ILiFi, ReentrancyGuard, SwapperV2, Validatable { /// Storage /// /// @dev The contract address of the cBridge Message Bus IMessageBus private immutable cBridgeMessageBus; /// @dev The contract address of the RelayerCelerIM RelayerCelerIM private immutable relayer; /// @dev The contract address of the Celer Flow USDC address private immutable cfUSDC; /// Types /// /// @param maxSlippage The max slippage accepted, given as percentage in point (pip). /// @param nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice. /// @param callTo The address of the contract to be called at destination. /// @param callData The encoded calldata with below data /// bytes32 transactionId, /// LibSwap.SwapData[] memory swapData, /// address receiver, /// address refundAddress /// @param messageBusFee The fee to be paid to CBridge message bus for relaying the message /// @param bridgeType Defines the bridge operation type (must be one of the values of CBridge library MsgDataTypes.BridgeSendType) struct CelerIMData { uint32 maxSlippage; uint64 nonce; bytes callTo; bytes callData; uint256 messageBusFee; MsgDataTypes.BridgeSendType bridgeType; } /// Constructor /// /// @notice Initialize the contract. /// @param _messageBus The contract address of the cBridge Message Bus /// @param _relayer The contract address of the RelayerCelerIM /// @param _cfUSDC The contract address of the Celer Flow USDC constructor( IMessageBus _messageBus, RelayerCelerIM _relayer, address _cfUSDC ) { cBridgeMessageBus = _messageBus; relayer = _relayer; cfUSDC = _cfUSDC; } /// External Methods /// /// @notice Bridges tokens via CBridge /// @param _bridgeData The core information needed for bridging /// @param _celerIMData Data specific to CelerIM function startBridgeTokensViaCelerIM( ILiFi.BridgeData memory _bridgeData, CelerIMData calldata _celerIMData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) doesNotContainSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) { validateDestinationCallFlag(_bridgeData, _celerIMData); if (!LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { // Transfer ERC20 tokens directly to relayer IERC20 asset = _getRightAsset(_bridgeData.sendingAssetId); // Deposit ERC20 token uint256 prevBalance = asset.balanceOf(address(relayer)); SafeERC20.safeTransferFrom( asset, msg.sender, address(relayer), _bridgeData.minAmount ); if ( asset.balanceOf(address(relayer)) - prevBalance != _bridgeData.minAmount ) { revert InvalidAmount(); } } _startBridge(_bridgeData, _celerIMData); } /// @notice Performs a swap before bridging via CBridge /// @param _bridgeData The core information needed for bridging /// @param _swapData An array of swap related data for performing swaps before bridging /// @param _celerIMData Data specific to CelerIM function swapAndStartBridgeTokensViaCelerIM( ILiFi.BridgeData memory _bridgeData, LibSwap.SwapData[] calldata _swapData, CelerIMData calldata _celerIMData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) containsSourceSwaps(_bridgeData) validateBridgeData(_bridgeData) { validateDestinationCallFlag(_bridgeData, _celerIMData); _bridgeData.minAmount = _depositAndSwap( _bridgeData.transactionId, _bridgeData.minAmount, _swapData, payable(msg.sender), _celerIMData.messageBusFee ); if (!LibAsset.isNativeAsset(_bridgeData.sendingAssetId)) { // Transfer ERC20 tokens directly to relayer IERC20 asset = _getRightAsset(_bridgeData.sendingAssetId); // Deposit ERC20 token uint256 prevBalance = asset.balanceOf(address(relayer)); SafeERC20.safeTransfer( asset, address(relayer), _bridgeData.minAmount ); if ( asset.balanceOf(address(relayer)) - prevBalance != _bridgeData.minAmount ) { revert InvalidAmount(); } } _startBridge(_bridgeData, _celerIMData); } /// Private Methods /// /// @dev Contains the business logic for the bridge via CBridge /// @param _bridgeData The core information needed for bridging /// @param _celerIMData Data specific to CBridge function _startBridge( ILiFi.BridgeData memory _bridgeData, CelerIMData calldata _celerIMData ) private { // Assuming messageBusFee is pre-calculated off-chain and available in _celerIMData // Determine correct native asset amount to be forwarded (if so) and send funds to relayer uint256 msgValue = LibAsset.isNativeAsset(_bridgeData.sendingAssetId) ? _bridgeData.minAmount : 0; // Check if transaction contains a destination call if (!_bridgeData.hasDestinationCall) { // Case 'no': Simple bridge transfer - Send to receiver relayer.sendTokenTransfer{ value: msgValue }( _bridgeData, _celerIMData ); } else { // Case 'yes': Bridge + Destination call - Send to relayer // save address of original recipient address receiver = _bridgeData.receiver; // Set relayer as a receiver _bridgeData.receiver = address(relayer); // send token transfer (bytes32 transferId, address bridgeAddress) = relayer .sendTokenTransfer{ value: msgValue }( _bridgeData, _celerIMData ); // Call message bus via relayer incl messageBusFee relayer.forwardSendMessageWithTransfer{ value: _celerIMData.messageBusFee }( _bridgeData.receiver, uint64(_bridgeData.destinationChainId), bridgeAddress, transferId, _celerIMData.callData ); // Reset receiver of bridge data for event emission _bridgeData.receiver = receiver; } // emit LiFi event emit LiFiTransferStarted(_bridgeData); } /// @dev Get right asset to transfer to relayer. /// @param _sendingAssetId The address of asset to bridge. /// @return _asset The address of asset to transfer to relayer. function _getRightAsset( address _sendingAssetId ) private returns (IERC20 _asset) { if (_sendingAssetId == cfUSDC) { // special case for cfUSDC token _asset = IERC20(CelerToken(_sendingAssetId).canonical()); } else { // any other ERC20 token _asset = IERC20(_sendingAssetId); } } function validateDestinationCallFlag( ILiFi.BridgeData memory _bridgeData, CelerIMData calldata _celerIMData ) private pure { if ( (_celerIMData.callData.length > 0) != _bridgeData.hasDestinationCall ) { revert InformationMismatch(); } } }
21,573
106
// The current and previous epoch
Epoch public currentEpoch; Epoch public previousEpoch;
Epoch public currentEpoch; Epoch public previousEpoch;
38,081
16
// Sets the system surplus buffer from 500k Dai to 2mm Dai
VowAbstract(MCD_VOW).file("hump", 2 * MILLION * RAD);
VowAbstract(MCD_VOW).file("hump", 2 * MILLION * RAD);
45,510
9
// require(_operator == deviceAgentAddress, "You are not authorized to register devices.");
roleMapping[_contract][uint(RBAC.OWNER)].add(_operator); roleMapping[_contract][uint(RBAC.DEVICEAGENT)].add(_deviceAgent);
roleMapping[_contract][uint(RBAC.OWNER)].add(_operator); roleMapping[_contract][uint(RBAC.DEVICEAGENT)].add(_deviceAgent);
25,155
26
// Mapping from withdrawal
mapping(uint8 => uint32) public withdrawalMode;
mapping(uint8 => uint32) public withdrawalMode;
21,821
5
// Lock the Swipe in the contract
swipe.transferFrom(msg.sender, address(this), _amount);
swipe.transferFrom(msg.sender, address(this), _amount);
56,332
4
// return The fee amount that will be collected from `value` when/ value is transferred to the contract
function calculateAnticSellFee(uint256 value) external view returns (uint256);
function calculateAnticSellFee(uint256 value) external view returns (uint256);
16,280
96
// get correct cbor output length
uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types }
uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types }
49,406
229
// Helper methods for integration with SaverExchange
contract ExchangeHelper is ConstantAddressesExchange { using SafeERC20 for ERC20; address public constant ZRX_ALLOWLIST_ADDR = 0x019739e288973F92bDD3c1d87178E206E51fd911; /// @notice Swaps 2 tokens on the Saver Exchange /// @dev ETH is sent with Weth address /// @param _data [amount, minPrice, exchangeType, 0xPrice] /// @param _src Token address of the source token /// @param _dest Token address of the destination token /// @param _exchangeAddress Address of 0x exchange that should be called /// @param _callData data to call 0x exchange with function swap(uint[4] memory _data, address _src, address _dest, address _exchangeAddress, bytes memory _callData) internal returns (uint) { address wrapper; uint price; // [tokensReturned, tokensLeft] uint[2] memory tokens; bool success; // tokensLeft is equal to amount at the beginning tokens[1] = _data[0]; _src = wethToKyberEth(_src); _dest = wethToKyberEth(_dest); // use this to avoid stack too deep error address[3] memory orderAddresses = [_exchangeAddress, _src, _dest]; // if _data[2] == 4 use 0x if possible if (_data[2] == 4) { if (orderAddresses[1] != KYBER_ETH_ADDRESS) { ERC20(orderAddresses[1]).approve(address(ERC20_PROXY_0X), _data[0]); } (success, tokens[0], ) = takeOrder(orderAddresses, _callData, address(this).balance, _data[0]); // if specifically 4, then require it to be successfull require(success && tokens[0] > 0, "0x transaction failed"); } if (tokens[0] == 0) { (wrapper, price) = SaverExchangeInterface(SAVER_EXCHANGE_ADDRESS).getBestPrice(_data[0], orderAddresses[1], orderAddresses[2], _data[2]); require(price > _data[1] || _data[3] > _data[1], "Slippage hit"); // handle 0x exchange, if equal price, try 0x to use less gas if (_data[3] >= price) { if (orderAddresses[1] != KYBER_ETH_ADDRESS) { ERC20(orderAddresses[1]).approve(address(ERC20_PROXY_0X), _data[0]); } // when selling eth its possible that some eth isn't sold and it is returned back (success, tokens[0], tokens[1]) = takeOrder(orderAddresses, _callData, address(this).balance, _data[0]); } // if there are more tokens left, try to sell them on other exchanges if (tokens[1] > 0) { // as it stands today, this can happend only when selling ETH if (tokens[1] != _data[0]) { (wrapper, price) = SaverExchangeInterface(SAVER_EXCHANGE_ADDRESS).getBestPrice(tokens[1], orderAddresses[1], orderAddresses[2], _data[2]); } require(price > _data[1], "Slippage hit onchain price"); if (orderAddresses[1] == KYBER_ETH_ADDRESS) { uint tRet; (tRet,) = ExchangeInterface(wrapper).swapEtherToToken{value: tokens[1]}(tokens[1], orderAddresses[2], uint(-1)); tokens[0] += tRet; } else { ERC20(orderAddresses[1]).safeTransfer(wrapper, tokens[1]); if (orderAddresses[2] == KYBER_ETH_ADDRESS) { tokens[0] += ExchangeInterface(wrapper).swapTokenToEther(orderAddresses[1], tokens[1], uint(-1)); } else { tokens[0] += ExchangeInterface(wrapper).swapTokenToToken(orderAddresses[1], orderAddresses[2], tokens[1]); } } } } return tokens[0]; } // @notice Takes order from 0x and returns bool indicating if it is successful // @param _addresses [exchange, src, dst] // @param _data Data to send with call // @param _value Value to send with call // @param _amount Amount to sell function takeOrder(address[3] memory _addresses, bytes memory _data, uint _value, uint _amount) private returns(bool, uint, uint) { bool success; if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_addresses[0])) { (success, ) = _addresses[0].call{value: _value}(_data); } else { success = false; } uint tokensLeft = _amount; uint tokensReturned = 0; if (success){ // check how many tokens left from _src if (_addresses[1] == KYBER_ETH_ADDRESS) { tokensLeft = address(this).balance; } else { tokensLeft = ERC20(_addresses[1]).balanceOf(address(this)); } // check how many tokens are returned if (_addresses[2] == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); tokensReturned = address(this).balance; } else { tokensReturned = ERC20(_addresses[2]).balanceOf(address(this)); } } return (success, tokensReturned, tokensLeft); } /// @notice Converts WETH -> Kybers Eth address /// @param _src Input address function wethToKyberEth(address _src) internal pure returns (address) { return _src == WETH_ADDRESS ? KYBER_ETH_ADDRESS : _src; } }
contract ExchangeHelper is ConstantAddressesExchange { using SafeERC20 for ERC20; address public constant ZRX_ALLOWLIST_ADDR = 0x019739e288973F92bDD3c1d87178E206E51fd911; /// @notice Swaps 2 tokens on the Saver Exchange /// @dev ETH is sent with Weth address /// @param _data [amount, minPrice, exchangeType, 0xPrice] /// @param _src Token address of the source token /// @param _dest Token address of the destination token /// @param _exchangeAddress Address of 0x exchange that should be called /// @param _callData data to call 0x exchange with function swap(uint[4] memory _data, address _src, address _dest, address _exchangeAddress, bytes memory _callData) internal returns (uint) { address wrapper; uint price; // [tokensReturned, tokensLeft] uint[2] memory tokens; bool success; // tokensLeft is equal to amount at the beginning tokens[1] = _data[0]; _src = wethToKyberEth(_src); _dest = wethToKyberEth(_dest); // use this to avoid stack too deep error address[3] memory orderAddresses = [_exchangeAddress, _src, _dest]; // if _data[2] == 4 use 0x if possible if (_data[2] == 4) { if (orderAddresses[1] != KYBER_ETH_ADDRESS) { ERC20(orderAddresses[1]).approve(address(ERC20_PROXY_0X), _data[0]); } (success, tokens[0], ) = takeOrder(orderAddresses, _callData, address(this).balance, _data[0]); // if specifically 4, then require it to be successfull require(success && tokens[0] > 0, "0x transaction failed"); } if (tokens[0] == 0) { (wrapper, price) = SaverExchangeInterface(SAVER_EXCHANGE_ADDRESS).getBestPrice(_data[0], orderAddresses[1], orderAddresses[2], _data[2]); require(price > _data[1] || _data[3] > _data[1], "Slippage hit"); // handle 0x exchange, if equal price, try 0x to use less gas if (_data[3] >= price) { if (orderAddresses[1] != KYBER_ETH_ADDRESS) { ERC20(orderAddresses[1]).approve(address(ERC20_PROXY_0X), _data[0]); } // when selling eth its possible that some eth isn't sold and it is returned back (success, tokens[0], tokens[1]) = takeOrder(orderAddresses, _callData, address(this).balance, _data[0]); } // if there are more tokens left, try to sell them on other exchanges if (tokens[1] > 0) { // as it stands today, this can happend only when selling ETH if (tokens[1] != _data[0]) { (wrapper, price) = SaverExchangeInterface(SAVER_EXCHANGE_ADDRESS).getBestPrice(tokens[1], orderAddresses[1], orderAddresses[2], _data[2]); } require(price > _data[1], "Slippage hit onchain price"); if (orderAddresses[1] == KYBER_ETH_ADDRESS) { uint tRet; (tRet,) = ExchangeInterface(wrapper).swapEtherToToken{value: tokens[1]}(tokens[1], orderAddresses[2], uint(-1)); tokens[0] += tRet; } else { ERC20(orderAddresses[1]).safeTransfer(wrapper, tokens[1]); if (orderAddresses[2] == KYBER_ETH_ADDRESS) { tokens[0] += ExchangeInterface(wrapper).swapTokenToEther(orderAddresses[1], tokens[1], uint(-1)); } else { tokens[0] += ExchangeInterface(wrapper).swapTokenToToken(orderAddresses[1], orderAddresses[2], tokens[1]); } } } } return tokens[0]; } // @notice Takes order from 0x and returns bool indicating if it is successful // @param _addresses [exchange, src, dst] // @param _data Data to send with call // @param _value Value to send with call // @param _amount Amount to sell function takeOrder(address[3] memory _addresses, bytes memory _data, uint _value, uint _amount) private returns(bool, uint, uint) { bool success; if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_addresses[0])) { (success, ) = _addresses[0].call{value: _value}(_data); } else { success = false; } uint tokensLeft = _amount; uint tokensReturned = 0; if (success){ // check how many tokens left from _src if (_addresses[1] == KYBER_ETH_ADDRESS) { tokensLeft = address(this).balance; } else { tokensLeft = ERC20(_addresses[1]).balanceOf(address(this)); } // check how many tokens are returned if (_addresses[2] == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); tokensReturned = address(this).balance; } else { tokensReturned = ERC20(_addresses[2]).balanceOf(address(this)); } } return (success, tokensReturned, tokensLeft); } /// @notice Converts WETH -> Kybers Eth address /// @param _src Input address function wethToKyberEth(address _src) internal pure returns (address) { return _src == WETH_ADDRESS ? KYBER_ETH_ADDRESS : _src; } }
14,055
6
// An array of list addresses.
address[] public lists;
address[] public lists;
35,134
0
// ========== STATE VARIABLES ========== // ========== Event ========== // ========== MODIFIERS ========== /
modifier onlyKeeper() { require(msg.sender == keeper || msg.sender == owner(), "Qore: caller is not the owner or keeper"); _; }
modifier onlyKeeper() { require(msg.sender == keeper || msg.sender == owner(), "Qore: caller is not the owner or keeper"); _; }
12,226
23
// slither-disable-next-line unused-return
Address.functionCallWithValue(deployedAddress, _initializeData, _value);
Address.functionCallWithValue(deployedAddress, _initializeData, _value);
19,390
62
// See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}; Requirements:- `sender` and `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`.- the caller must have allowance for ``sender``'s tokens of at least`amount`. /
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
21,488
84
// if value of B is lower, users are incentivized to trade in B for A to make pool evenly balanced
_weightInOut[0] = currentWeightB(); _weightInOut[1] = currentWeightA(); _balanceInOut[0] = pooledBalanceB(); _balanceInOut[1] = pooledBalanceA(); _amountIn = _idealBUsd.sub(_debtBUsd).mul(10 ** providerB.getPriceFeedDecimals()).div(providerB.getPriceFeed()); _amountOutIfNoSlippage = _debtAUsd.sub(_idealAUsd).mul(10 ** providerA.getPriceFeedDecimals()).div(providerA.getPriceFeed()); _outDecimals = decimals(tokenA);
_weightInOut[0] = currentWeightB(); _weightInOut[1] = currentWeightA(); _balanceInOut[0] = pooledBalanceB(); _balanceInOut[1] = pooledBalanceA(); _amountIn = _idealBUsd.sub(_debtBUsd).mul(10 ** providerB.getPriceFeedDecimals()).div(providerB.getPriceFeed()); _amountOutIfNoSlippage = _debtAUsd.sub(_idealAUsd).mul(10 ** providerA.getPriceFeedDecimals()).div(providerA.getPriceFeed()); _outDecimals = decimals(tokenA);
41,230
20
// Conforms to ERC-1155 Standard /
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal override
function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal override
26,692
35
// SmtPriceFeed Protofire Contract module to retrieve SMT price per asset. /
contract SmtPriceFeed is Ownable { using SafeMath for uint256; uint256 public constant decimals = 18; uint256 public constant ONE = 10**18; address public immutable WETH_ADDRESS; /// @dev Address smt address public smt; /// @dev Address of BRegistry IBRegistry public registry; /// @dev Address of EurPriceFeed module IEurPriceFeed public eurPriceFeed; /// @dev Address of XTokenWrapper module IXTokenWrapper public xTokenWrapper; /// @dev price of SMT measured in ETH stored, used to decouple price querying and calculating uint256 public currentPrice; /** * @dev Emitted when `registry` address is set. */ event RegistrySet(address registry); /** * @dev Emitted when `eurPriceFeed` address is set. */ event EurPriceFeedSet(address eurPriceFeed); /** * @dev Emitted when `smt` address is set. */ event SmtSet(address smt); /** * @dev Emitted when `xTokenWrapper` address is set. */ event XTokenWrapperSet(address xTokenWrapper); /** * @dev Emitted when someone executes computePrice. */ event PriceComputed(address caller, uint256 price); /** * @dev Sets the values for {registry}, {eurPriceFeed} {smt} and {xTokenWrapper}. * * Sets ownership to the account that deploys the contract. * */ constructor( address _registry, address _eurPriceFeed, address _smt, address _xTokenWrapper, address _wethAddress ) { _setRegistry(_registry); _setEurPriceFeed(_eurPriceFeed); _setSmt(_smt); _setXTokenWrapper(_xTokenWrapper); WETH_ADDRESS = _wethAddress; } /** * @dev Sets `_registry` as the new registry. * * Requirements: * * - the caller must be the owner. * - `_registry` should not be the zero address. * * @param _registry The address of the registry. */ function setRegistry(address _registry) external onlyOwner { _setRegistry(_registry); } /** * @dev Sets `_eurPriceFeed` as the new EurPriceFeed. * * Requirements: * * - the caller must be the owner. * - `_eurPriceFeed` should not be the zero address. * * @param _eurPriceFeed The address of the EurPriceFeed. */ function setEurPriceFeed(address _eurPriceFeed) external onlyOwner { _setEurPriceFeed(_eurPriceFeed); } /** * @dev Sets `_smt` as the new Smt. * * Requirements: * * - the caller must be the owner. * - `_smt` should not be the zero address. * * @param _smt The address of the Smt. */ function setSmt(address _smt) external onlyOwner { _setSmt(_smt); } /** * @dev Sets `_xTokenWrapper` as the new xTokenWrapper. * * Requirements: * * - the caller must be the owner. * - `_xTokenWrapper` should not be the zero address. * * @param _xTokenWrapper The address of the xTokenWrapper. */ function setXTokenWrapper(address _xTokenWrapper) external onlyOwner { _setXTokenWrapper(_xTokenWrapper); } /** * @dev Sets `_registry` as the new registry. * * Requirements: * * - `_registry` should not be the zero address. * * @param _registry The address of the registry. */ function _setRegistry(address _registry) internal { require(_registry != address(0), "registry is the zero address"); emit RegistrySet(_registry); registry = IBRegistry(_registry); } /** * @dev Sets `_eurPriceFeed` as the new EurPriceFeed. * * Requirements: * * - `_eurPriceFeed` should not be the zero address. * * @param _eurPriceFeed The address of the EurPriceFeed. */ function _setEurPriceFeed(address _eurPriceFeed) internal { require(_eurPriceFeed != address(0), "eurPriceFeed is the zero address"); emit EurPriceFeedSet(_eurPriceFeed); eurPriceFeed = IEurPriceFeed(_eurPriceFeed); } /** * @dev Sets `_smt` as the new Smt. * * Requirements: * * - `_smt` should not be the zero address. * * @param _smt The address of the Smt. */ function _setSmt(address _smt) internal { require(_smt != address(0), "smt is the zero address"); emit SmtSet(_smt); smt = _smt; } /** * @dev Sets `_xTokenWrapper` as the new xTokenWrapper. * * Requirements: * * - `_xTokenWrapper` should not be the zero address. * * @param _xTokenWrapper The address of the xTokenWrapper. */ function _setXTokenWrapper(address _xTokenWrapper) internal { require(_xTokenWrapper != address(0), "xTokenWrapper is the zero address"); emit XTokenWrapperSet(_xTokenWrapper); xTokenWrapper = IXTokenWrapper(_xTokenWrapper); } /** * @dev Gets the price of `_asset` in SMT. * * @param _asset address of asset to get the price. */ function getPrice(address _asset) external view returns (uint256) { uint8 assetDecimals = IDecimals(_asset).decimals(); return calculateAmount(_asset, 10**assetDecimals); } /** * @dev Gets how many SMT represents the `_amount` of `_asset`. * * @param _asset address of asset to get the amount. * @param _assetAmountIn amount of `_asset`. */ function calculateAmount(address _asset, uint256 _assetAmountIn) public view returns (uint256) { // pools will include the wrapepd SMT address xSMT = xTokenWrapper.tokenToXToken(smt); address xETH = xTokenWrapper.tokenToXToken(WETH_ADDRESS); //if same token, didn't modify the token amount if (_asset == xSMT) { return _assetAmountIn; } // get amount from some of the pools uint256 amount = getAvgAmountFromPools(_asset, xSMT, _assetAmountIn); // not pool with SMT/asset pair -> calculate base on SMT/ETH pool and Asset/ETH external price feed if (amount == 0) { // pools will include the wrapepd ETH uint256 ethSmtAmount = getAvgAmountFromPools(xETH, xSMT, ONE); address assetEthFeed = eurPriceFeed.assetEthFeed(_asset); if (assetEthFeed != address(0)) { // always 18 decimals int256 assetEthPrice = AggregatorV2V3Interface(assetEthFeed).latestAnswer(); if (assetEthPrice > 0) { uint8 assetDecimals = IDecimals(_asset).decimals(); uint256 assetToEthAmount = _assetAmountIn.mul(uint256(assetEthPrice)).div(10**assetDecimals); amount = assetToEthAmount.mul(ethSmtAmount).div(ONE); } } } return amount; } /** * @dev Gets SMT/ETH based on the last executiong of computePrice. * * To be consume by EurPriceFeed module as the `assetEthFeed` from xSMT. */ function latestAnswer() external view returns (int256) { return int256(currentPrice); } /** * @dev Computes SMT/ETH based on the avg price from pools containig the pair. * * To be consume by EurPriceFeed module as the `assetEthFeed` from xSMT. */ function computePrice() public { // pools will include the wrapepd SMT and wrapped ETH currentPrice = getAvgAmountFromPools( xTokenWrapper.tokenToXToken(smt), xTokenWrapper.tokenToXToken(WETH_ADDRESS), ONE ); emit PriceComputed(msg.sender, currentPrice); } function getAvgAmountFromPools( address _assetIn, address _assetOut, uint256 _assetAmountIn ) internal view returns (uint256) { address[] memory poolAddresses = registry.getBestPoolsWithLimit(_assetIn, _assetOut, 10); uint256 totalAmount; for (uint256 i = 0; i < poolAddresses.length; i++) { totalAmount += calcOutGivenIn(poolAddresses[i], _assetIn, _assetOut, _assetAmountIn); } return totalAmount > 0 ? totalAmount.div(poolAddresses.length) : 0; } function calcOutGivenIn( address poolAddress, address _assetIn, address _assetOut, uint256 _assetAmountIn ) internal view returns (uint256) { IBPool pool = IBPool(poolAddress); uint256 tokenBalanceIn = pool.getBalance(_assetIn); uint256 tokenBalanceOut = pool.getBalance(_assetOut); uint256 tokenWeightIn = pool.getDenormalizedWeight(_assetIn); uint256 tokenWeightOut = pool.getDenormalizedWeight(_assetOut); return pool.calcOutGivenIn(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, _assetAmountIn, 0); } }
contract SmtPriceFeed is Ownable { using SafeMath for uint256; uint256 public constant decimals = 18; uint256 public constant ONE = 10**18; address public immutable WETH_ADDRESS; /// @dev Address smt address public smt; /// @dev Address of BRegistry IBRegistry public registry; /// @dev Address of EurPriceFeed module IEurPriceFeed public eurPriceFeed; /// @dev Address of XTokenWrapper module IXTokenWrapper public xTokenWrapper; /// @dev price of SMT measured in ETH stored, used to decouple price querying and calculating uint256 public currentPrice; /** * @dev Emitted when `registry` address is set. */ event RegistrySet(address registry); /** * @dev Emitted when `eurPriceFeed` address is set. */ event EurPriceFeedSet(address eurPriceFeed); /** * @dev Emitted when `smt` address is set. */ event SmtSet(address smt); /** * @dev Emitted when `xTokenWrapper` address is set. */ event XTokenWrapperSet(address xTokenWrapper); /** * @dev Emitted when someone executes computePrice. */ event PriceComputed(address caller, uint256 price); /** * @dev Sets the values for {registry}, {eurPriceFeed} {smt} and {xTokenWrapper}. * * Sets ownership to the account that deploys the contract. * */ constructor( address _registry, address _eurPriceFeed, address _smt, address _xTokenWrapper, address _wethAddress ) { _setRegistry(_registry); _setEurPriceFeed(_eurPriceFeed); _setSmt(_smt); _setXTokenWrapper(_xTokenWrapper); WETH_ADDRESS = _wethAddress; } /** * @dev Sets `_registry` as the new registry. * * Requirements: * * - the caller must be the owner. * - `_registry` should not be the zero address. * * @param _registry The address of the registry. */ function setRegistry(address _registry) external onlyOwner { _setRegistry(_registry); } /** * @dev Sets `_eurPriceFeed` as the new EurPriceFeed. * * Requirements: * * - the caller must be the owner. * - `_eurPriceFeed` should not be the zero address. * * @param _eurPriceFeed The address of the EurPriceFeed. */ function setEurPriceFeed(address _eurPriceFeed) external onlyOwner { _setEurPriceFeed(_eurPriceFeed); } /** * @dev Sets `_smt` as the new Smt. * * Requirements: * * - the caller must be the owner. * - `_smt` should not be the zero address. * * @param _smt The address of the Smt. */ function setSmt(address _smt) external onlyOwner { _setSmt(_smt); } /** * @dev Sets `_xTokenWrapper` as the new xTokenWrapper. * * Requirements: * * - the caller must be the owner. * - `_xTokenWrapper` should not be the zero address. * * @param _xTokenWrapper The address of the xTokenWrapper. */ function setXTokenWrapper(address _xTokenWrapper) external onlyOwner { _setXTokenWrapper(_xTokenWrapper); } /** * @dev Sets `_registry` as the new registry. * * Requirements: * * - `_registry` should not be the zero address. * * @param _registry The address of the registry. */ function _setRegistry(address _registry) internal { require(_registry != address(0), "registry is the zero address"); emit RegistrySet(_registry); registry = IBRegistry(_registry); } /** * @dev Sets `_eurPriceFeed` as the new EurPriceFeed. * * Requirements: * * - `_eurPriceFeed` should not be the zero address. * * @param _eurPriceFeed The address of the EurPriceFeed. */ function _setEurPriceFeed(address _eurPriceFeed) internal { require(_eurPriceFeed != address(0), "eurPriceFeed is the zero address"); emit EurPriceFeedSet(_eurPriceFeed); eurPriceFeed = IEurPriceFeed(_eurPriceFeed); } /** * @dev Sets `_smt` as the new Smt. * * Requirements: * * - `_smt` should not be the zero address. * * @param _smt The address of the Smt. */ function _setSmt(address _smt) internal { require(_smt != address(0), "smt is the zero address"); emit SmtSet(_smt); smt = _smt; } /** * @dev Sets `_xTokenWrapper` as the new xTokenWrapper. * * Requirements: * * - `_xTokenWrapper` should not be the zero address. * * @param _xTokenWrapper The address of the xTokenWrapper. */ function _setXTokenWrapper(address _xTokenWrapper) internal { require(_xTokenWrapper != address(0), "xTokenWrapper is the zero address"); emit XTokenWrapperSet(_xTokenWrapper); xTokenWrapper = IXTokenWrapper(_xTokenWrapper); } /** * @dev Gets the price of `_asset` in SMT. * * @param _asset address of asset to get the price. */ function getPrice(address _asset) external view returns (uint256) { uint8 assetDecimals = IDecimals(_asset).decimals(); return calculateAmount(_asset, 10**assetDecimals); } /** * @dev Gets how many SMT represents the `_amount` of `_asset`. * * @param _asset address of asset to get the amount. * @param _assetAmountIn amount of `_asset`. */ function calculateAmount(address _asset, uint256 _assetAmountIn) public view returns (uint256) { // pools will include the wrapepd SMT address xSMT = xTokenWrapper.tokenToXToken(smt); address xETH = xTokenWrapper.tokenToXToken(WETH_ADDRESS); //if same token, didn't modify the token amount if (_asset == xSMT) { return _assetAmountIn; } // get amount from some of the pools uint256 amount = getAvgAmountFromPools(_asset, xSMT, _assetAmountIn); // not pool with SMT/asset pair -> calculate base on SMT/ETH pool and Asset/ETH external price feed if (amount == 0) { // pools will include the wrapepd ETH uint256 ethSmtAmount = getAvgAmountFromPools(xETH, xSMT, ONE); address assetEthFeed = eurPriceFeed.assetEthFeed(_asset); if (assetEthFeed != address(0)) { // always 18 decimals int256 assetEthPrice = AggregatorV2V3Interface(assetEthFeed).latestAnswer(); if (assetEthPrice > 0) { uint8 assetDecimals = IDecimals(_asset).decimals(); uint256 assetToEthAmount = _assetAmountIn.mul(uint256(assetEthPrice)).div(10**assetDecimals); amount = assetToEthAmount.mul(ethSmtAmount).div(ONE); } } } return amount; } /** * @dev Gets SMT/ETH based on the last executiong of computePrice. * * To be consume by EurPriceFeed module as the `assetEthFeed` from xSMT. */ function latestAnswer() external view returns (int256) { return int256(currentPrice); } /** * @dev Computes SMT/ETH based on the avg price from pools containig the pair. * * To be consume by EurPriceFeed module as the `assetEthFeed` from xSMT. */ function computePrice() public { // pools will include the wrapepd SMT and wrapped ETH currentPrice = getAvgAmountFromPools( xTokenWrapper.tokenToXToken(smt), xTokenWrapper.tokenToXToken(WETH_ADDRESS), ONE ); emit PriceComputed(msg.sender, currentPrice); } function getAvgAmountFromPools( address _assetIn, address _assetOut, uint256 _assetAmountIn ) internal view returns (uint256) { address[] memory poolAddresses = registry.getBestPoolsWithLimit(_assetIn, _assetOut, 10); uint256 totalAmount; for (uint256 i = 0; i < poolAddresses.length; i++) { totalAmount += calcOutGivenIn(poolAddresses[i], _assetIn, _assetOut, _assetAmountIn); } return totalAmount > 0 ? totalAmount.div(poolAddresses.length) : 0; } function calcOutGivenIn( address poolAddress, address _assetIn, address _assetOut, uint256 _assetAmountIn ) internal view returns (uint256) { IBPool pool = IBPool(poolAddress); uint256 tokenBalanceIn = pool.getBalance(_assetIn); uint256 tokenBalanceOut = pool.getBalance(_assetOut); uint256 tokenWeightIn = pool.getDenormalizedWeight(_assetIn); uint256 tokenWeightOut = pool.getDenormalizedWeight(_assetOut); return pool.calcOutGivenIn(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, _assetAmountIn, 0); } }
13,039
174
// Helper to decode the encoded call arguments for claiming rewards and swapping
function __decodeClaimRewardsAndSwapCallArgs(bytes memory _encodedCallArgs) private pure returns ( bool useFullBalances_, address incomingAsset_, uint256 minIncomingAssetAmount_ )
function __decodeClaimRewardsAndSwapCallArgs(bytes memory _encodedCallArgs) private pure returns ( bool useFullBalances_, address incomingAsset_, uint256 minIncomingAssetAmount_ )
83,837
24
// Script format errors/ 0x01: At least one of the source scripts is not a valid CBOR-encoded value.
SourceScriptNotCBOR,
SourceScriptNotCBOR,
36,530
386
// txAwareHashNotAllowed()
returns (address _wallet)
returns (address _wallet)
42,742
5
// set new message
message = _message; return message;
message = _message; return message;
1,410
149
// scope to remove the error Stack too deep
(uint _nthday,uint _daystoclose,uint _totalBonusToReceive,uint _dailyEarnings,uint _principalPmtDaily) = _deposits(_month,_amount,_interest); uint _localid = allDeposits.length++;
(uint _nthday,uint _daystoclose,uint _totalBonusToReceive,uint _dailyEarnings,uint _principalPmtDaily) = _deposits(_month,_amount,_interest); uint _localid = allDeposits.length++;
63,295
27
// i = 2h
mstore(i, mulmod(mload(h), 2, MODULUS)) mstore(add(i, 0x20), mulmod(mload(add(h, 0x20)), 2, MODULUS))
mstore(i, mulmod(mload(h), 2, MODULUS)) mstore(add(i, 0x20), mulmod(mload(add(h, 0x20)), 2, MODULUS))
1,986
5
// Returns the amount of tokens owned by `account`. /
function balanceOf(address account) external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
316
59
// Returns the address that signed on the given block hash./blockHash The block hash that the validator signed data on.
function recoverSigner(Data memory self, bytes32 blockHash) internal pure returns (address)
function recoverSigner(Data memory self, bytes32 blockHash) internal pure returns (address)
7,363
308
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
emit Approval(_from, msg.sender, _allowance);
49,886
6
// Utility function that converts the msg.sender viewed in the L2 to the/ address in the L1 that submitted a tx to the inbox/l1Address L2 address as viewed in msg.sender/ return The address in the L1 that triggered the tx to L2
function applyL1ToL2Alias(address l1Address) internal pure returns (address) { return address(uint160(l1Address) + offset); }
function applyL1ToL2Alias(address l1Address) internal pure returns (address) { return address(uint160(l1Address) + offset); }
6,363
41
// Adding the created proposal to the proposal queue
proposalQueue.push(proposal);
proposalQueue.push(proposal);
52,650
144
// removes a collateral from minting. Still allows withdrawals however
function removeCollateral(address collateral_) external oneLPGov
function removeCollateral(address collateral_) external oneLPGov
60,943
3
// Indicate that a `_party` won full custody._party The party that won full custody. /
event PartyWonCustody(address _party);
event PartyWonCustody(address _party);
39,155
7
// Subtract 256 bit number from 512 bit number
assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) }
assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) }
17,476
81
// event for token purchases loggingpurchaser who paid for the tokensvalue weis paid for purchasepurchaseDate time of log/
event TokenPurchased(address indexed purchaser, uint256 value, uint256 purchaseDate);
event TokenPurchased(address indexed purchaser, uint256 value, uint256 purchaseDate);
59,463
13
// Scopes calls to an address, limited to specific function signatures, and per function scoping rules./Only callable by owner./role Role to set for./targetAddress Address to be scoped.
function scopeTarget(uint16 role, address targetAddress) external onlyOwner
function scopeTarget(uint16 role, address targetAddress) external onlyOwner
28,210
124
// generate the uniSwap pair path of token -> weth
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniSwapRouter.WETH(); _approve(address(this), address(uniSwapRouter), tokenAmount);
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniSwapRouter.WETH(); _approve(address(this), address(uniSwapRouter), tokenAmount);
6,668
33
// This is used to send tokens and execute code on other smart contract, this method is disabled if emergencyLock is activated_spender Contract that is receiving tokens_value The amount that msg.sender is sending_extraData Additional params that can be used on reciving smart contract return if successful returns true/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) lockAffected public returns (bool success) { tokenRecipientInterface spender = tokenRecipientInterface(_spender); approve(_spender, _value); spender.receiveApproval(msg.sender, _value, this, _extraData); return true; }
function approveAndCall(address _spender, uint256 _value, bytes _extraData) lockAffected public returns (bool success) { tokenRecipientInterface spender = tokenRecipientInterface(_spender); approve(_spender, _value); spender.receiveApproval(msg.sender, _value, this, _extraData); return true; }
8,331
12
// only if maturity has not arrived yet
IEURxb(_eurxb).removeMaturity(value, maturity);
IEURxb(_eurxb).removeMaturity(value, maturity);
76,447
17
// require(proposed_purchase.set,"There is no proposition !!!");We can check there is a proposition or not.
require(!proposed_purchase.approvedAccounts[msg.sender],"You've approved once."); proposed_purchase.approval_state += 1; proposed_purchase.approvedAccounts[msg.sender] = true; // Preventing more than once voting situation
require(!proposed_purchase.approvedAccounts[msg.sender],"You've approved once."); proposed_purchase.approval_state += 1; proposed_purchase.approvedAccounts[msg.sender] = true; // Preventing more than once voting situation
34,789
31
// require(_timeOfAuction[_saleId] >= block.timestamp,"Auction Over");
if (_tokenMeta[_saleId].currency != address(0)) { IERC20(_tokenMeta[_saleId].currency).transferFrom( msg.sender, address(this), _bidPrice ); }
if (_tokenMeta[_saleId].currency != address(0)) { IERC20(_tokenMeta[_saleId].currency).transferFrom( msg.sender, address(this), _bidPrice ); }
23,773
41
// ensure that destination chain has enrolled router
bytes32 _router = _mustHaveRouter(_destination);
bytes32 _router = _mustHaveRouter(_destination);
21,438
36
// WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible Requirements: - `tokenId` must not exist.- `to` cannot be the zero address. Emits a {Transfer} event. /
function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), 'A: you are stupid'); require(_rednecks[tokenId] == address(0), 'A: you are slowpoke'); _rednecks[tokenId] = to; emit Transfer(address(0), to, tokenId); }
function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), 'A: you are stupid'); require(_rednecks[tokenId] == address(0), 'A: you are slowpoke'); _rednecks[tokenId] = to; emit Transfer(address(0), to, tokenId); }
6,805
27
// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { if (isFunding) throw; if (_fundingStartBlock >= _fundingStopBlock) throw; if (block.number >= _fundingStartBlock) throw; fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true; }
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { if (isFunding) throw; if (_fundingStartBlock >= _fundingStopBlock) throw; if (block.number >= _fundingStartBlock) throw; fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true; }
39,658
3
// operation -> ValidatorIndex
mapping(bytes32 => uint8) internal operationsByValidatorIndex; mapping(uint8 => uint8) internal operationsCountByValidatorIndex;
mapping(bytes32 => uint8) internal operationsByValidatorIndex; mapping(uint8 => uint8) internal operationsCountByValidatorIndex;
4,289
231
// oracle token price update term
uint256 public updateTokenPriceTerm = 120;
uint256 public updateTokenPriceTerm = 120;
6,467
71
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; }
if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; }
5,159
11
// Find the length of the conversion path
uint256 len = 0; for(; len < orderAddresses.length; len++) { if(orderAddresses[len] == 0) { break; }
uint256 len = 0; for(; len < orderAddresses.length; len++) { if(orderAddresses[len] == 0) { break; }
39,883
32
// Constructors
constructor () public{ totalSupply = initialSupply; balances[msg.sender] = initialSupply; // Send all tokens to owner //allowedAddresses[owner] = true; }
constructor () public{ totalSupply = initialSupply; balances[msg.sender] = initialSupply; // Send all tokens to owner //allowedAddresses[owner] = true; }
9,818
28
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such that denominatorinv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for four bits. That is, denominatorinv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
uint256 inverse = (3 * denominator) ^ 2;
53,714
176
// log contribution event
LogContribution( userAddress, msg.sender, msg.value, totalRaised, userAssignedTokens, userId );
LogContribution( userAddress, msg.sender, msg.value, totalRaised, userAssignedTokens, userId );
22,791
89
// Next, work backwards and fill in the remaining gaps (proofPtr + 0x260) = proofOutputs[1].outputNotes[0].length (0xc0 + metadataLength)
mstore(add(proofPtr, 0x260), add(0xc0, metadataLength))
mstore(add(proofPtr, 0x260), add(0xc0, metadataLength))
19,269
3
// Tells the address of the COMP token in the Ethereum Mainnet. /
function compToken() public pure returns (ERC20) { return ERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); }
function compToken() public pure returns (ERC20) { return ERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); }
2,562
29
// _fromsource address_totarget address_value transfer amountreturn true if the transfer was successful, false if it wasn't/
function _transfer(address _from, address _to, uint256 _value) internal returns (bool success)
function _transfer(address _from, address _to, uint256 _value) internal returns (bool success)
22,886
23
// Get the migration request.
function getMigrationRequest(uint256 _requestId) external view onlyOwner returns (RequestStateChange memory) { return _requestMigrateToPublicStorage[_requestId]; }
function getMigrationRequest(uint256 _requestId) external view onlyOwner returns (RequestStateChange memory) { return _requestMigrateToPublicStorage[_requestId]; }
185
14
// An array containing what is actively being voted on.
address[] activeVotes;
address[] activeVotes;
51,197
0
// An entry relating (tld, address) => {add, release, transfer} may modify thepermissions the address has inside this tld. By default, a user in this rolewill have no permissions over a given TLD unless the TLD has an entry for it,being the entry the one which enables the action by setting it to true. However, if the address also is enabled into the defaultDomainRegistrants setthen the default permissions when lacking an entry for a given TLD, is to havepermissions to do any of the 3 actions in the TLD. The TLD configuration, for the involved domain, may however have their ownflags
bytes32 public domainRegistrantRole;
bytes32 public domainRegistrantRole;
6,118