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
104
// Return the current collateral ratio (ICR) of a given Trove. Takes a trove's pending coll and debt rewards from redistributions into account.
function getCurrentICR(address _borrower, uint _price) public view override returns (uint) { (uint currentETH, uint currentLUSDDebt) = _getCurrentTroveAmounts(_borrower); uint ICR = LiquityMath._computeCR(currentETH, currentLUSDDebt, _price); return ICR; }
function getCurrentICR(address _borrower, uint _price) public view override returns (uint) { (uint currentETH, uint currentLUSDDebt) = _getCurrentTroveAmounts(_borrower); uint ICR = LiquityMath._computeCR(currentETH, currentLUSDDebt, _price); return ICR; }
62,631
3
// Raised when attempting to amend the provenance hash.
error ProvenanceAlreadySet();
error ProvenanceAlreadySet();
6,003
3
// The implementation version new collections will use. This is auto-incremented each time the implementation is changed. /
uint256 public version; event RolesContractUpdated(address indexed rolesContract); event CollectionCreated(
uint256 public version; event RolesContractUpdated(address indexed rolesContract); event CollectionCreated(
4,007
20
// give to _formint will call _updateReward
_mint(_for, _amount);
_mint(_for, _amount);
9,480
3
// send `value` token to `to` from `from` on the condition it is approved by `from`/_from The address of the sender/_to The address of the recipient/_value The amount of token to be transferred/ return True if transfer was successful
function transferFrom( address _from, address _to, uint256 _value ) external returns (bool);
function transferFrom( address _from, address _to, uint256 _value ) external returns (bool);
23,353
11
// when applied to a function, ensures that the function is only callable by the `registry`.
modifier onlyRegistry() { require(msg.sender == address(registry), "onlyRegistry"); _; }
modifier onlyRegistry() { require(msg.sender == address(registry), "onlyRegistry"); _; }
38,758
1,932
// 967
entry "male-assigned" : ENG_ADJECTIVE
entry "male-assigned" : ENG_ADJECTIVE
17,579
26
// Calls winningProposal() function to get the index of the winner contained in the proposals array and thenreturn winnerName_ the name of the winner /
function mqj34m2ss() public view returns (bytes32 winnerName_)
function mqj34m2ss() public view returns (bytes32 winnerName_)
22,777
89
// wad in DAI
address urn = ManagerLike(cdp_manager).urns(cdpId); DaiJoinLike(mcd_join_dai).join(urn, wad); ManagerLike(cdp_manager).frob(cdpId, 0, _getWipeDart(VatLike(vat).dai(urn), urn));
address urn = ManagerLike(cdp_manager).urns(cdpId); DaiJoinLike(mcd_join_dai).join(urn, wad); ManagerLike(cdp_manager).frob(cdpId, 0, _getWipeDart(VatLike(vat).dai(urn), urn));
43,880
18
// Extracts the first rune in the slice into `rune`, advancing the slice to point to the next rune and returning `self`. self The slice to operate on. rune The slice that will contain the first rune.return `rune`. /
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory)
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory)
21,535
150
// This implements an optional extension of {ERC721} defined in the EIP that adds Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
10,133
6
// We don't disallow joining several accounts together to consolidate salaries for different projects. require(originalAddresses[_newAccount] == 0, "Account is taken.")
newToOldAccount[_newAccount] = _oldAccount; originalAddresses[_newAccount] = _orig; originalToCurrentAddresses[_orig] = _newAccount;
newToOldAccount[_newAccount] = _oldAccount; originalAddresses[_newAccount] = _orig; originalToCurrentAddresses[_orig] = _newAccount;
31,132
95
// approve token transfer to cover all possible scenarios
_approve(address(this), address(pancakeswapRouter), tokenAmount); IERC20(USDTAddress).approve(address(pancakeswapRouter),usdtAmount);
_approve(address(this), address(pancakeswapRouter), tokenAmount); IERC20(USDTAddress).approve(address(pancakeswapRouter),usdtAmount);
15,879
36
// return the amount of tokens the user would get by doing a swap _param contain all params required from struct GetAmountParametersreturn amountOut_ The amount of token the user would receivereturn newReserveIn_ reserves of the selling token after the swapreturn newReserveOut_ reserves of the buying token after the swapreturn newFictiveReserveIn_ fictive reserve of the selling token after the swapreturn newFictiveReserveOut_ fictive reserve of the buying token after the swap /
function getAmountOut( GetAmountParameters memory _param ) internal pure returns ( uint256 amountOut_, uint256 newReserveIn_, uint256 newReserveOut_, uint256 newFictiveReserveIn_,
function getAmountOut( GetAmountParameters memory _param ) internal pure returns ( uint256 amountOut_, uint256 newReserveIn_, uint256 newReserveOut_, uint256 newFictiveReserveIn_,
45,318
10
// GEB_AUTO_SURPLUS_BUFFER, INCREASING_TREASURY_REIMBURSEMENT_OVERLAY
AuthLike(0x1450f40E741F2450A95F9579Be93DD63b8407a25).addAuthorization(0x1dCeE093a7C952260f591D9B8401318f2d2d72Ac);
AuthLike(0x1450f40E741F2450A95F9579Be93DD63b8407a25).addAuthorization(0x1dCeE093a7C952260f591D9B8401318f2d2d72Ac);
26,695
10
// Sets the Linear Weights used to Calculate the reputation_weights uint256[]/
function setReputationLinWeights(uint256[] _weights) public returns (uint256[]) { require(msg.sender == owner); require(_weights.length == reputationWindowSize); for(uint128 i = 0; i < reputationWindowSize; i++){ repWeights.push(_weights[i]); } reputationWeightsSet = true; return repWeights; }
function setReputationLinWeights(uint256[] _weights) public returns (uint256[]) { require(msg.sender == owner); require(_weights.length == reputationWindowSize); for(uint128 i = 0; i < reputationWindowSize; i++){ repWeights.push(_weights[i]); } reputationWeightsSet = true; return repWeights; }
35,455
52
// The allowance has overflowed.
error AllowanceOverflow();
error AllowanceOverflow();
17,291
110
// Returns if the address is whitelisted or not. /
function whitelisted(address addr) public view returns ( bool, bool, bool, bool )
function whitelisted(address addr) public view returns ( bool, bool, bool, bool )
16,445
1
// Returns bit.ly URL to swarm file bzz:/0191e5bf83b4b172ac36921a4ba1ceab49ba6178fcc35404047c04e6e5e95771
string memory genomeURL = "URL: http://bit.ly/0x4554482b45626f6c61"; return (genomeURL);
string memory genomeURL = "URL: http://bit.ly/0x4554482b45626f6c61"; return (genomeURL);
9,264
42
// add liquidity
swapAndLiquify(contractTokenBalance);
swapAndLiquify(contractTokenBalance);
26,330
52
// Supported non-payable function: ERC_ER_SHI.decreaseSupplyOnly can be called by this contract itself to resolve calldata /
function decreaseSupply(uint256 _value, address /* _from */) external onlyMe onlySealed
function decreaseSupply(uint256 _value, address /* _from */) external onlyMe onlySealed
18,755
5
// Termination.WithdrawalByPolicyHolder_NonRenewed
else if (termination == 5) { policy.operationEffectiveDate = policy.expirationDate.setDateAt23h59m59s(TIME_ZONE_OFFSET); }
else if (termination == 5) { policy.operationEffectiveDate = policy.expirationDate.setDateAt23h59m59s(TIME_ZONE_OFFSET); }
3,443
48
// emitted on successful device activation/_sender manufacturer or device owner paying for activation/_fee registration fee paid by manufacturer/_deviceId the real device id (only revealed after activation)/_manufacturerId of the manufacturer the device belongs to/_deviceType is the type of device categorized by the manufacturer
event DeviceActivated( address indexed _sender, uint256 _fee, bytes32 indexed _deviceId, bytes32 indexed _manufacturerId, bytes32 _deviceType );
event DeviceActivated( address indexed _sender, uint256 _fee, bytes32 indexed _deviceId, bytes32 indexed _manufacturerId, bytes32 _deviceType );
22,711
106
// Send the earned tokens to the resolver
if (tokensEarned >= 1e14) { controller.gamePayoutResolver(msg.sender, tokensEarned); }
if (tokensEarned >= 1e14) { controller.gamePayoutResolver(msg.sender, tokensEarned); }
50,636
104
// range must be sane
require(_endTimestamp > _startTimestamp); duration = _endTimestamp - _startTimestamp;
require(_endTimestamp > _startTimestamp); duration = _endTimestamp - _startTimestamp;
32,006
7
// Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws./orderHash Hash of the order associated with this transfer./assetData Byte array encoded for the asset./from Address to transfer token from./to Address to transfer token to./amount Amount of token to transfer.
function _dispatchTransferFrom( bytes32 orderHash, bytes memory assetData, address from, address to, uint256 amount ) internal
function _dispatchTransferFrom( bytes32 orderHash, bytes memory assetData, address from, address to, uint256 amount ) internal
8,190
84
// return The total supply of the token /
function totalSupply() public view virtual override returns (uint256) { return _totalSupply; }
function totalSupply() public view virtual override returns (uint256) { return _totalSupply; }
16,074
68
// Remove from set of existing challengers
if (isChallenger) challengers.remove(msg.sender);
if (isChallenger) challengers.remove(msg.sender);
73,598
91
// mints new tokens and assigns them to the target _investor. Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet)/
function mint(address _investor, uint256 _amount) public onlyModule(STO_KEY, true) returns (bool success) { require(verifyTransfer(address(0), _investor, _amount)); totalSupply_ = totalSupply_.add(_amount); balances[_investor] = balances[_investor].add(_amount); emit Mint(_investor, _amount); emit Transfer(address(0), _investor, _amount); return true; }
function mint(address _investor, uint256 _amount) public onlyModule(STO_KEY, true) returns (bool success) { require(verifyTransfer(address(0), _investor, _amount)); totalSupply_ = totalSupply_.add(_amount); balances[_investor] = balances[_investor].add(_amount); emit Mint(_investor, _amount); emit Transfer(address(0), _investor, _amount); return true; }
25,629
34
// Settle request is at the very least initialized
require( curSettleRequest.status != Status.Uninitialized, "Settle request has not been initialized!" );
require( curSettleRequest.status != Status.Uninitialized, "Settle request has not been initialized!" );
5,240
152
// Checks if the given tranche is a valid child of the given parent bond./ return True if the bond is the tranche's parent.
function _isBondTranche(ITranche tranche, IBondController bond) private view returns (bool) { return (bond.trancheTokenAddresses(tranche) && address(bond) == tranche.bond()); }
function _isBondTranche(ITranche tranche, IBondController bond) private view returns (bool) { return (bond.trancheTokenAddresses(tranche) && address(bond) == tranche.bond()); }
13,748
20
// Returns `x | y`.
function or(bool x, bool y) internal pure returns (bool z) { /// @solidity memory-safe-assembly assembly { z := or(x, y) } }
function or(bool x, bool y) internal pure returns (bool z) { /// @solidity memory-safe-assembly assembly { z := or(x, y) } }
39,166
47
// There are 103725856 tokens in stage 2 1 ETH = 3549 IML
uint tokenPrice2 = 3549; uint tokenSupply2 = 103725856 * BASE;
uint tokenPrice2 = 3549; uint tokenSupply2 = 103725856 * BASE;
14,340
70
// Disallow transfers to irretrievable-addresses. / Insufficient balance will be handled by the safe subtraction.
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
18,095
1
// Token addresses
address public wanna_near_dai_lp = 0xE6c47B036f6Fd0684B109B484aC46094e633aF2e; address public dai = 0xe3520349F477A5F6EB06107066048508498A291b; constructor( address _governance, address _strategist, address _controller, address _timelock )
address public wanna_near_dai_lp = 0xE6c47B036f6Fd0684B109B484aC46094e633aF2e; address public dai = 0xe3520349F477A5F6EB06107066048508498A291b; constructor( address _governance, address _strategist, address _controller, address _timelock )
6,749
33
// Writes an integer to the buffer. Resizes if doing so would exceedthe capacity of the buffer.buf The buffer to append to.off The offset to write at.data The data to append.len The number of bytes to write (right-aligned). return The original buffer, for chaining./
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; }
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; }
64,401
32
// - Context Library
abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } }
abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } }
8,053
21
// mint new tokens and transfer to wallet
token.mint(msg.sender, ehterToBin(amountTobuy, price)); emit Bought(msg.sender);
token.mint(msg.sender, ehterToBin(amountTobuy, price)); emit Bought(msg.sender);
20,853
16
// Enable Transfer of ERC20 gardenTokens Only members can transfer tokens until the protocol is fully decentralized
bool public override gardenTokensTransfersEnabled;
bool public override gardenTokensTransfersEnabled;
23,545
261
// List of aggregator keys for convenient iteration
bytes32[] public aggregatorKeys;
bytes32[] public aggregatorKeys;
48,695
4
// Returns the state of an authorization Nonces are randomly generated 32-byte data unique to theauthorizer's address authorizerAuthorizer's address nonce Nonce of the authorizationreturn True if the nonce is used /
function authorizationState(address authorizer, bytes32 nonce)
function authorizationState(address authorizer, bytes32 nonce)
6,726
10
// verifies that the receipt is included in the receipts trie usingthe provided proof. Accepts both existence and nonexistenceproofs. Reverts if the proof is invalid. Assumes the receiptsRootcomes from a valid Ethereum block header.idx the receipt index in the block proof the MPT proof for the storage trie receiptsRoot the MPT root hash for the storage triereturn exists whether the receipt index existsreturn value the value in the storage slot, as bytes, with leading 0 bytes removed /
function verifyReceipt( uint256 idx, bytes calldata proof, bytes32 receiptsRoot
function verifyReceipt( uint256 idx, bytes calldata proof, bytes32 receiptsRoot
39,271
152
// ERC165 interface.Returns true for ERC721, false otherwise /
function supportsInterface(bytes4 interfaceID) external view returns (bool _isSupported)
function supportsInterface(bytes4 interfaceID) external view returns (bool _isSupported)
8,876
3
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); }
function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); }
8,928
173
// Allows the operator to set the address of the game operator, which should be the pre-sale contract or the game contract./_gameOperator the address of the game operator
function setGameOperator(address _gameOperator) public onlyOperator { require(_gameOperator != address(0)); emit LogGameOperatorChanged(gameOperator, _gameOperator); gameOperator = _gameOperator; }
function setGameOperator(address _gameOperator) public onlyOperator { require(_gameOperator != address(0)); emit LogGameOperatorChanged(gameOperator, _gameOperator); gameOperator = _gameOperator; }
21,762
0
// ========== ENUMS ========== /
enum LockTypes { USDV, VADER }
enum LockTypes { USDV, VADER }
17,880
8
// Set new oracle
function setOracle(address oracle) external onlyOwner { _ORACLE_ = oracle; }
function setOracle(address oracle) external onlyOwner { _ORACLE_ = oracle; }
17,059
287
// PRICELESS POSITION DATA STRUCTURES / Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; }
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; }
7,822
25
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned for accounts without code, i.e. `keccak256('')`
bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
2,052
17
// destroy token when the user claims their tokens
function burn(uint256 _amount) public { require (msg.sender == owner, "only contract owner can burn."); require (balances[owner] >= _amount && _totalSupply >= _amount, "the consumer must have at least the amount of tokens to be burned, and there must be at least that much in the total supply"); _totalSupply = safeSub(_totalSupply, _amount); balances[owner] = safeSub(balances[owner], _amount); }
function burn(uint256 _amount) public { require (msg.sender == owner, "only contract owner can burn."); require (balances[owner] >= _amount && _totalSupply >= _amount, "the consumer must have at least the amount of tokens to be burned, and there must be at least that much in the total supply"); _totalSupply = safeSub(_totalSupply, _amount); balances[owner] = safeSub(balances[owner], _amount); }
19,832
92
// This loop checks that all condition sets are disjoint (the same outcome is not part of more than 1 set)
uint[] memory positionIds = new uint[](partition.length); uint[] memory amounts = new uint[](partition.length); for (uint i = 0; i < partition.length; i++) { uint indexSet = partition[i]; require(indexSet > 0 && indexSet < fullIndexSet, "got invalid index set"); require((indexSet & freeIndexSet) == indexSet, "partition not disjoint"); freeIndexSet ^= indexSet; positionIds[i] = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet)); amounts[i] = amount; }
uint[] memory positionIds = new uint[](partition.length); uint[] memory amounts = new uint[](partition.length); for (uint i = 0; i < partition.length; i++) { uint indexSet = partition[i]; require(indexSet > 0 && indexSet < fullIndexSet, "got invalid index set"); require((indexSet & freeIndexSet) == indexSet, "partition not disjoint"); freeIndexSet ^= indexSet; positionIds[i] = CTHelpers.getPositionId(collateralToken, CTHelpers.getCollectionId(parentCollectionId, conditionId, indexSet)); amounts[i] = amount; }
24,239
5
// Information for liquidity providing, stored inside contract
struct LPProvidingInfo { address walletOwner; // address of token wallet owner uint256 walletPubkey; // pubkey of token wallet owner address w1; // address of first token wallet uint128 a1; // amount of tokens provided address w2; // address of second token wallet uint128 a2; // amount of tokens provided }
struct LPProvidingInfo { address walletOwner; // address of token wallet owner uint256 walletPubkey; // pubkey of token wallet owner address w1; // address of first token wallet uint128 a1; // amount of tokens provided address w2; // address of second token wallet uint128 a2; // amount of tokens provided }
3,316
13
// Declared constants below to be used in tandem with/ getDecimalsConstant(), for gas optimization purposes/ which return decimals from a constant list of popular/ tokens.
IERC20Ext internal constant ETH_TOKEN_ADDRESS = IERC20Ext( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); IERC20Ext internal constant USDT_TOKEN_ADDRESS = IERC20Ext( 0xdAC17F958D2ee523a2206206994597C13D831ec7 ); IERC20Ext internal constant DAI_TOKEN_ADDRESS = IERC20Ext( 0x6B175474E89094C44Da98b954EedeAC495271d0F ); IERC20Ext internal constant USDC_TOKEN_ADDRESS = IERC20Ext(
IERC20Ext internal constant ETH_TOKEN_ADDRESS = IERC20Ext( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); IERC20Ext internal constant USDT_TOKEN_ADDRESS = IERC20Ext( 0xdAC17F958D2ee523a2206206994597C13D831ec7 ); IERC20Ext internal constant DAI_TOKEN_ADDRESS = IERC20Ext( 0x6B175474E89094C44Da98b954EedeAC495271d0F ); IERC20Ext internal constant USDC_TOKEN_ADDRESS = IERC20Ext(
16,560
247
// Tokens can be moved only after if transfer enabled or if you are an approved operator. /
modifier canTransfer(address from) { require( _transferEnabled || hasRole(OPERATOR_ROLE, from), "ERC20Base: transfer is not enabled or from does not have the OPERATOR role" ); _; }
modifier canTransfer(address from) { require( _transferEnabled || hasRole(OPERATOR_ROLE, from), "ERC20Base: transfer is not enabled or from does not have the OPERATOR role" ); _; }
12,034
0
// basis points (percent100) of EL rewards that should go to the recipient/
uint96 basisPoints;
uint96 basisPoints;
39,852
307
// set auth signer
function setAuthSigner(address _authSigner) external onlyOwner { authSigner = _authSigner; emit AuthSignerSet(_authSigner); }
function setAuthSigner(address _authSigner) external onlyOwner { authSigner = _authSigner; emit AuthSignerSet(_authSigner); }
24,988
370
// CHECK BALANCE
uint balance = IERC20Mikaboshi(IERC20ContractAddress).balanceOf(address(this));
uint balance = IERC20Mikaboshi(IERC20ContractAddress).balanceOf(address(this));
24,929
41
// pragma solidity >=0.4.23; // import "ds-math/math.sol"; // import "ds-auth/auth.sol"; /
contract LizardToken is DSMath, DSAuth { bool public stopped; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; bytes32 public symbol = "LZRD"; uint256 public decimals = 18; // standard token precision. override to customize bytes32 public name = "Lizard"; mapping (address => bool) public claimed; uint256 public claimAmt = 69420000000000000000; constructor() public {} event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); event Stop(); event Start(); modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function approve(address guy) external returns (bool) { return approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad, "ds-token-insufficient-approval"); allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); } require(balanceOf[src] >= wad, "ds-token-insufficient-balance"); balanceOf[src] = sub(balanceOf[src], wad); balanceOf[dst] = add(balanceOf[dst], wad); emit Transfer(src, dst, wad); return true; } function push(address dst, uint wad) external { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) external { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) external { transferFrom(src, dst, wad); } function claim() external { uint256 _claimAmt = claimAmt; require(!claimed[msg.sender], "No double claiming"); claimed[msg.sender] = true; allowance[address(this)][msg.sender] = _claimAmt; transferFrom(address(this), msg.sender, _claimAmt); } function mint(uint wad) external { mint(msg.sender, wad); } function burn(uint wad) external { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { balanceOf[guy] = add(balanceOf[guy], wad); totalSupply = add(totalSupply, wad); emit Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && allowance[guy][msg.sender] != uint(-1)) { require(allowance[guy][msg.sender] >= wad, "ds-token-insufficient-approval"); allowance[guy][msg.sender] = sub(allowance[guy][msg.sender], wad); } require(balanceOf[guy] >= wad, "ds-token-insufficient-balance"); balanceOf[guy] = sub(balanceOf[guy], wad); totalSupply = sub(totalSupply, wad); emit Burn(guy, wad); } function stop() public auth { stopped = true; emit Stop(); } function start() public auth { stopped = false; emit Start(); } function setName(bytes32 name_) external auth { name = name_; } }
contract LizardToken is DSMath, DSAuth { bool public stopped; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; bytes32 public symbol = "LZRD"; uint256 public decimals = 18; // standard token precision. override to customize bytes32 public name = "Lizard"; mapping (address => bool) public claimed; uint256 public claimAmt = 69420000000000000000; constructor() public {} event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); event Stop(); event Start(); modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function approve(address guy) external returns (bool) { return approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad, "ds-token-insufficient-approval"); allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); } require(balanceOf[src] >= wad, "ds-token-insufficient-balance"); balanceOf[src] = sub(balanceOf[src], wad); balanceOf[dst] = add(balanceOf[dst], wad); emit Transfer(src, dst, wad); return true; } function push(address dst, uint wad) external { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) external { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) external { transferFrom(src, dst, wad); } function claim() external { uint256 _claimAmt = claimAmt; require(!claimed[msg.sender], "No double claiming"); claimed[msg.sender] = true; allowance[address(this)][msg.sender] = _claimAmt; transferFrom(address(this), msg.sender, _claimAmt); } function mint(uint wad) external { mint(msg.sender, wad); } function burn(uint wad) external { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { balanceOf[guy] = add(balanceOf[guy], wad); totalSupply = add(totalSupply, wad); emit Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && allowance[guy][msg.sender] != uint(-1)) { require(allowance[guy][msg.sender] >= wad, "ds-token-insufficient-approval"); allowance[guy][msg.sender] = sub(allowance[guy][msg.sender], wad); } require(balanceOf[guy] >= wad, "ds-token-insufficient-balance"); balanceOf[guy] = sub(balanceOf[guy], wad); totalSupply = sub(totalSupply, wad); emit Burn(guy, wad); } function stop() public auth { stopped = true; emit Stop(); } function start() public auth { stopped = false; emit Start(); } function setName(bytes32 name_) external auth { name = name_; } }
13,366
129
// list edition with "buy now" price and start date
function listForBuyNow(address _seller, uint256 _id, uint128 _listingPrice, uint128 _startDate) public override
function listForBuyNow(address _seller, uint256 _id, uint128 _listingPrice, uint128 _startDate) public override
44,537
259
// Execute a withdrawal with a signed authorization. This is used totransfer tokens back to the root chain. owner Token owner's address (Authorizer) value Amount to be withdrawn validAfterThe time after which this is valid (unix time) validBefore The time before which this is valid (unix time) nonce Unique nonce v v of the signature r r of the signature s s of the signature /
function withdrawWithAuthorization( address owner, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s
function withdrawWithAuthorization( address owner, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s
22,780
30
// compute community tokens without bonus
communityTokenAmount = communityEthAmount.mul(ethToTokenConversion); uint256 availableTokenAmount = maxCommunityWithoutBonusCap.sub(communityTokenWithoutBonusSold);
communityTokenAmount = communityEthAmount.mul(ethToTokenConversion); uint256 availableTokenAmount = maxCommunityWithoutBonusCap.sub(communityTokenWithoutBonusSold);
4,362
118
// get the number of token from this sender
uint256 tokenBalance = token.balanceOf(msg.sender);
uint256 tokenBalance = token.balanceOf(msg.sender);
4,821
16
// 构造函数
constructor ( GDXToken _gdx, address _gamma, Refer _refer
constructor ( GDXToken _gdx, address _gamma, Refer _refer
23,608
45
// The event emitted when the stored price is updated
event PriceUpdated(string symbol, uint price);
event PriceUpdated(string symbol, uint price);
36,005
17
// There must be a name.
require((bytes(_name).length > 0), "TicketBooth::issue: EMPTY_NAME");
require((bytes(_name).length > 0), "TicketBooth::issue: EMPTY_NAME");
29,452
87
// Withdraw the shares from the system.
uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient);
uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient);
68,949
186
// Basic Configs
uint256 public maxSupply = 7777; uint256 public _price = 0.005 ether; uint256 public regularMintMax = 20;
uint256 public maxSupply = 7777; uint256 public _price = 0.005 ether; uint256 public regularMintMax = 20;
44,385
36
// Returns vested amount for a user for a given duration user address of the user duration the durationreturn Vested amount for the given duration /
function getVestedAmount(address user, Duration duration) public view returns (uint256) { uint256 timestamp = userstakedAmounts[user][duration].timestamp; // short circuit if no vesting for this duration if (timestamp == 0) { return 0; } uint256 durationInSeconds = _getDurationInSeconds(duration); uint256 secondsSinceStake = block.timestamp - timestamp; uint256 amount = userstakedAmounts[user][duration].amount; return secondsSinceStake >= durationInSeconds ? amount : 0; }
function getVestedAmount(address user, Duration duration) public view returns (uint256) { uint256 timestamp = userstakedAmounts[user][duration].timestamp; // short circuit if no vesting for this duration if (timestamp == 0) { return 0; } uint256 durationInSeconds = _getDurationInSeconds(duration); uint256 secondsSinceStake = block.timestamp - timestamp; uint256 amount = userstakedAmounts[user][duration].amount; return secondsSinceStake >= durationInSeconds ? amount : 0; }
30,969
112
// - mint sSYNR
mintSSyn(_staker, pendingYield);
mintSSyn(_staker, pendingYield);
50,738
7
// ONLY OPERATOR: Updates issue fee on IssuanceModule_setToken Address of SetToken _newFee New issue fee percentage in precise units (1% = 1e16, 100% = 1e18) /
function updateIssueFee(ISetToken _setToken, uint256 _newFee) external onlyOperator
function updateIssueFee(ISetToken _setToken, uint256 _newFee) external onlyOperator
51,074
270
// Emitted when a deToken(DeBridgeTokenProxy) is deployed using this contract
event DeBridgeTokenDeployed( address asset, string name, string symbol, uint8 decimals );
event DeBridgeTokenDeployed( address asset, string name, string symbol, uint8 decimals );
71,880
6
// 승인된 지갑만
modifier onlyApprovedOf(uint256 partId) { require( msg.sender == ownerOf(partId) || msg.sender == getApproved(partId) || isApprovedForAll(ownerOf(partId), msg.sender) == true || msg.sender == address(this) ); _; }
modifier onlyApprovedOf(uint256 partId) { require( msg.sender == ownerOf(partId) || msg.sender == getApproved(partId) || isApprovedForAll(ownerOf(partId), msg.sender) == true || msg.sender == address(this) ); _; }
17,876
14
// The block number when rewardToken mining starts.
uint256 public startBlock;
uint256 public startBlock;
27,127
5
// Get the address of the owner/ return owner_ The address of the owner.
function owner() external view returns (address owner_);
function owner() external view returns (address owner_);
40,069
180
// Mint silver token function for contract owner./
function mintSilverToken(address to) external onlyMinter() { if (to == address(0)) revert CantMintToZeroAddress(); if (nextSilverTokenId > MAX_SILVER_TOKEN_ID) revert TokenOutOfSupply(); _safeMint(to, nextSilverTokenId); unchecked{ nextSilverTokenId += 1; } }
function mintSilverToken(address to) external onlyMinter() { if (to == address(0)) revert CantMintToZeroAddress(); if (nextSilverTokenId > MAX_SILVER_TOKEN_ID) revert TokenOutOfSupply(); _safeMint(to, nextSilverTokenId); unchecked{ nextSilverTokenId += 1; } }
13,295
5
// 投資時會被呼叫的函數
function fund() public payable { //若是活動已結束的話就中斷處理 require(!ended); Investor storage inv = investors[numInvestors++]; inv.addr = msg.sender; inv.amount = msg.value; totalAmount += msg.value; }
function fund() public payable { //若是活動已結束的話就中斷處理 require(!ended); Investor storage inv = investors[numInvestors++]; inv.addr = msg.sender; inv.amount = msg.value; totalAmount += msg.value; }
54,153
18
// initialzie Emergency calls
emergencyCalls.push( EmergencyCall({ selector: keccak256(abi.encodePacked("setMarketBorrowUsability(uint16,bool)")), paramsBytesCount: 64 })
emergencyCalls.push( EmergencyCall({ selector: keccak256(abi.encodePacked("setMarketBorrowUsability(uint16,bool)")), paramsBytesCount: 64 })
20,302
31
// A method for a stakeholder to create a stake. This when an investor will invest in the debt offeringepoch The timestamp/
function createStake(uint256 epoch) public payable isMinimumInvestment isExceededMaximumOffering isValidStakeholder noStakes
function createStake(uint256 epoch) public payable isMinimumInvestment isExceededMaximumOffering isValidStakeholder noStakes
5,251
93
// Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS; assembly {
uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS; assembly {
7,797
16
// Get the flash loan fees amount amount of token to borrow /
function flashFee(uint256 amount) external view returns (uint256) { require( ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed(address(this), address(0), amount, ""), "flashloan is paused" ); return div_(mul_(amount, flashFeeBips), 10000); }
function flashFee(uint256 amount) external view returns (uint256) { require( ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed(address(this), address(0), amount, ""), "flashloan is paused" ); return div_(mul_(amount, flashFeeBips), 10000); }
56,548
35
// calculates the expected return of converting a given amount on a given path note that there is no support for circular paths _pathconversion path (see conversion path format above)_amountamount of _path[0] tokens received from the userreturn amount of _path[_path.length - 1] tokens that the user will receive return amount of _path[_path.length - 1] tokens that the user will pay as fee/
function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 ratio; IBancorConverter converter; IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token fromToken = _path[i - 2]; IERC20Token smartToken = _path[i - 1]; IERC20Token toToken = _path[i]; if (toToken == smartToken) { // buy the smart token // check if the current smart token has changed if (i < 3 || smartToken != _path[i - 3]) { supply = smartToken.totalSupply(); converter = IBancorConverter(ISmartToken(smartToken).owner()); } // calculate the amount & the conversion fee balance = converter.getConnectorBalance(fromToken); (, ratio, , , ) = converter.connectors(fromToken); amount = formula.calculatePurchaseReturn(supply, balance, ratio, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply += amount; } else if (fromToken == smartToken) { // sell the smart token // check if the current smart token has changed if (i < 3 || smartToken != _path[i - 3]) { supply = smartToken.totalSupply(); converter = IBancorConverter(ISmartToken(smartToken).owner()); } // calculate the amount & the conversion fee balance = converter.getConnectorBalance(toToken); (, ratio, , , ) = converter.connectors(toToken); amount = formula.calculateSaleReturn(supply, balance, ratio, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply -= amount; } else { // cross reserve conversion // check if the current smart token has changed if (i < 3 || smartToken != _path[i - 3]) { converter = IBancorConverter(ISmartToken(smartToken).owner()); } (amount, fee) = getReturn(converter, fromToken, toToken, amount); } } return (amount, fee); }
function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 ratio; IBancorConverter converter; IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token fromToken = _path[i - 2]; IERC20Token smartToken = _path[i - 1]; IERC20Token toToken = _path[i]; if (toToken == smartToken) { // buy the smart token // check if the current smart token has changed if (i < 3 || smartToken != _path[i - 3]) { supply = smartToken.totalSupply(); converter = IBancorConverter(ISmartToken(smartToken).owner()); } // calculate the amount & the conversion fee balance = converter.getConnectorBalance(fromToken); (, ratio, , , ) = converter.connectors(fromToken); amount = formula.calculatePurchaseReturn(supply, balance, ratio, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply += amount; } else if (fromToken == smartToken) { // sell the smart token // check if the current smart token has changed if (i < 3 || smartToken != _path[i - 3]) { supply = smartToken.totalSupply(); converter = IBancorConverter(ISmartToken(smartToken).owner()); } // calculate the amount & the conversion fee balance = converter.getConnectorBalance(toToken); (, ratio, , , ) = converter.connectors(toToken); amount = formula.calculateSaleReturn(supply, balance, ratio, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply -= amount; } else { // cross reserve conversion // check if the current smart token has changed if (i < 3 || smartToken != _path[i - 3]) { converter = IBancorConverter(ISmartToken(smartToken).owner()); } (amount, fee) = getReturn(converter, fromToken, toToken, amount); } } return (amount, fee); }
27,363
96
// ProtocolFeeTracker Contract/Enzyme Council <[email protected]>/The contract responsible for tracking owed protocol fees
contract ProtocolFeeTracker is IProtocolFeeTracker, FundDeployerOwnerMixin { using SafeMath for uint256; event InitializedForVault(address vaultProxy); event FeeBpsDefaultSet(uint256 nextFeeBpsDefault); event FeeBpsOverrideSetForVault(address indexed vaultProxy, uint256 nextFeeBpsOverride); event FeePaidForVault(address indexed vaultProxy, uint256 sharesAmount, uint256 secondsPaid); event LastPaidSetForVault( address indexed vaultProxy, uint256 prevTimestamp, uint256 nextTimestamp ); uint256 private constant MAX_BPS = 10000; uint256 private constant SECONDS_IN_YEAR = 31557600; // 60*60*24*365.25 uint256 private feeBpsDefault; mapping(address => uint256) private vaultProxyToFeeBpsOverride; mapping(address => uint256) private vaultProxyToLastPaid; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) { // Validate constants require( SECONDS_IN_YEAR == (60 * 60 * 24 * 36525) / 100, "constructor: Incorrect SECONDS_IN_YEAR" ); } // EXTERNAL FUNCTIONS /// @notice Initializes protocol fee tracking for a given VaultProxy /// @param _vaultProxy The VaultProxy /// @dev Does not validate whether _vaultProxy is already initialized, /// as FundDeployer will only do this once function initializeForVault(address _vaultProxy) external override { require(msg.sender == getFundDeployer(), "Only the FundDeployer can call this function"); __setLastPaidForVault(_vaultProxy, block.timestamp); emit InitializedForVault(_vaultProxy); } /// @notice Marks the protocol fee as paid for the sender, and gets the amount of shares that /// should be minted for payment /// @return sharesDue_ The amount of shares to be minted for payment /// @dev This trusts the VaultProxy to mint the correct sharesDue_. /// There is no need to validate that the VaultProxy is still on this release. function payFee() external override returns (uint256 sharesDue_) { address vaultProxy = msg.sender; // VaultProxy is validated during initialization uint256 lastPaid = getLastPaidForVault(vaultProxy); if (lastPaid >= block.timestamp) { return 0; } // Not strictly necessary as we trust the FundDeployer to have already initialized the // VaultProxy, but inexpensive require(lastPaid > 0, "payFee: VaultProxy not initialized"); uint256 secondsDue = block.timestamp.sub(lastPaid); sharesDue_ = __calcSharesDueForVault(vaultProxy, secondsDue); // Even if sharesDue_ is 0, we update the lastPaid timestamp and emit the event __setLastPaidForVault(vaultProxy, block.timestamp); emit FeePaidForVault(vaultProxy, sharesDue_, secondsDue); return sharesDue_; } // PUBLIC FUNCTIONS /// @notice Gets the protocol fee rate (in bps) for a given VaultProxy /// @param _vaultProxy The VaultProxy /// @return feeBps_ The protocol fee (in bps) function getFeeBpsForVault(address _vaultProxy) public view returns (uint256 feeBps_) { feeBps_ = getFeeBpsOverrideForVault(_vaultProxy); if (feeBps_ == 0) { feeBps_ = getFeeBpsDefault(); } return feeBps_; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the protocol fee shares due for a given VaultProxy function __calcSharesDueForVault(address _vaultProxy, uint256 _secondsDue) private view returns (uint256 sharesDue_) { uint256 sharesSupply = ERC20(_vaultProxy).totalSupply(); uint256 rawSharesDue = sharesSupply .mul(getFeeBpsForVault(_vaultProxy)) .mul(_secondsDue) .div(SECONDS_IN_YEAR) .div(MAX_BPS); uint256 supplyNetRawSharesDue = sharesSupply.sub(rawSharesDue); if (supplyNetRawSharesDue == 0) { return 0; } return rawSharesDue.mul(sharesSupply).div(supplyNetRawSharesDue); } /// @dev Helper to set the lastPaid timestamp for a given VaultProxy function __setLastPaidForVault(address _vaultProxy, uint256 _nextTimestamp) private { vaultProxyToLastPaid[_vaultProxy] = _nextTimestamp; } //////////////// // ADMIN ONLY // //////////////// /// @notice Sets the default protocol fee rate (in bps) /// @param _nextFeeBpsDefault The default protocol fee rate (in bps) to set function setFeeBpsDefault(uint256 _nextFeeBpsDefault) external onlyFundDeployerOwner { require(_nextFeeBpsDefault < MAX_BPS, "setDefaultFeeBps: Exceeds max"); feeBpsDefault = _nextFeeBpsDefault; emit FeeBpsDefaultSet(_nextFeeBpsDefault); } /// @notice Sets a specified protocol fee rate (in bps) for a particular VaultProxy /// @param _vaultProxy The VaultProxy /// @param _nextFeeBpsOverride The protocol fee rate (in bps) to set function setFeeBpsOverrideForVault(address _vaultProxy, uint256 _nextFeeBpsOverride) external onlyFundDeployerOwner { require(_nextFeeBpsOverride < MAX_BPS, "setFeeBpsOverrideForVault: Exceeds max"); vaultProxyToFeeBpsOverride[_vaultProxy] = _nextFeeBpsOverride; emit FeeBpsOverrideSetForVault(_vaultProxy, _nextFeeBpsOverride); } /// @notice Sets the lastPaid timestamp for a specified VaultProxy /// @param _vaultProxy The VaultProxy /// @param _nextTimestamp The lastPaid timestamp to set function setLastPaidForVault(address _vaultProxy, uint256 _nextTimestamp) external onlyFundDeployerOwner { uint256 prevTimestamp = getLastPaidForVault(_vaultProxy); require(prevTimestamp > 0, "setLastPaidForVault: _vaultProxy not initialized"); require( _nextTimestamp > prevTimestamp || _nextTimestamp > block.timestamp, "setLastPaidForVault: Can only increase or set a future timestamp" ); __setLastPaidForVault(_vaultProxy, _nextTimestamp); emit LastPaidSetForVault(_vaultProxy, prevTimestamp, _nextTimestamp); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `feeBpsDefault` variable value /// @return feeBpsDefault_ The `feeBpsDefault` variable value function getFeeBpsDefault() public view returns (uint256 feeBpsDefault_) { return feeBpsDefault; } /// @notice Gets the feeBpsOverride value for the given VaultProxy /// @param _vaultProxy The VaultProxy /// @return feeBpsOverride_ The feeBpsOverride value function getFeeBpsOverrideForVault(address _vaultProxy) public view returns (uint256 feeBpsOverride_) { return vaultProxyToFeeBpsOverride[_vaultProxy]; } /// @notice Gets the lastPaid value for the given VaultProxy /// @param _vaultProxy The VaultProxy /// @return lastPaid_ The lastPaid value function getLastPaidForVault(address _vaultProxy) public view returns (uint256 lastPaid_) { return vaultProxyToLastPaid[_vaultProxy]; } }
contract ProtocolFeeTracker is IProtocolFeeTracker, FundDeployerOwnerMixin { using SafeMath for uint256; event InitializedForVault(address vaultProxy); event FeeBpsDefaultSet(uint256 nextFeeBpsDefault); event FeeBpsOverrideSetForVault(address indexed vaultProxy, uint256 nextFeeBpsOverride); event FeePaidForVault(address indexed vaultProxy, uint256 sharesAmount, uint256 secondsPaid); event LastPaidSetForVault( address indexed vaultProxy, uint256 prevTimestamp, uint256 nextTimestamp ); uint256 private constant MAX_BPS = 10000; uint256 private constant SECONDS_IN_YEAR = 31557600; // 60*60*24*365.25 uint256 private feeBpsDefault; mapping(address => uint256) private vaultProxyToFeeBpsOverride; mapping(address => uint256) private vaultProxyToLastPaid; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) { // Validate constants require( SECONDS_IN_YEAR == (60 * 60 * 24 * 36525) / 100, "constructor: Incorrect SECONDS_IN_YEAR" ); } // EXTERNAL FUNCTIONS /// @notice Initializes protocol fee tracking for a given VaultProxy /// @param _vaultProxy The VaultProxy /// @dev Does not validate whether _vaultProxy is already initialized, /// as FundDeployer will only do this once function initializeForVault(address _vaultProxy) external override { require(msg.sender == getFundDeployer(), "Only the FundDeployer can call this function"); __setLastPaidForVault(_vaultProxy, block.timestamp); emit InitializedForVault(_vaultProxy); } /// @notice Marks the protocol fee as paid for the sender, and gets the amount of shares that /// should be minted for payment /// @return sharesDue_ The amount of shares to be minted for payment /// @dev This trusts the VaultProxy to mint the correct sharesDue_. /// There is no need to validate that the VaultProxy is still on this release. function payFee() external override returns (uint256 sharesDue_) { address vaultProxy = msg.sender; // VaultProxy is validated during initialization uint256 lastPaid = getLastPaidForVault(vaultProxy); if (lastPaid >= block.timestamp) { return 0; } // Not strictly necessary as we trust the FundDeployer to have already initialized the // VaultProxy, but inexpensive require(lastPaid > 0, "payFee: VaultProxy not initialized"); uint256 secondsDue = block.timestamp.sub(lastPaid); sharesDue_ = __calcSharesDueForVault(vaultProxy, secondsDue); // Even if sharesDue_ is 0, we update the lastPaid timestamp and emit the event __setLastPaidForVault(vaultProxy, block.timestamp); emit FeePaidForVault(vaultProxy, sharesDue_, secondsDue); return sharesDue_; } // PUBLIC FUNCTIONS /// @notice Gets the protocol fee rate (in bps) for a given VaultProxy /// @param _vaultProxy The VaultProxy /// @return feeBps_ The protocol fee (in bps) function getFeeBpsForVault(address _vaultProxy) public view returns (uint256 feeBps_) { feeBps_ = getFeeBpsOverrideForVault(_vaultProxy); if (feeBps_ == 0) { feeBps_ = getFeeBpsDefault(); } return feeBps_; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the protocol fee shares due for a given VaultProxy function __calcSharesDueForVault(address _vaultProxy, uint256 _secondsDue) private view returns (uint256 sharesDue_) { uint256 sharesSupply = ERC20(_vaultProxy).totalSupply(); uint256 rawSharesDue = sharesSupply .mul(getFeeBpsForVault(_vaultProxy)) .mul(_secondsDue) .div(SECONDS_IN_YEAR) .div(MAX_BPS); uint256 supplyNetRawSharesDue = sharesSupply.sub(rawSharesDue); if (supplyNetRawSharesDue == 0) { return 0; } return rawSharesDue.mul(sharesSupply).div(supplyNetRawSharesDue); } /// @dev Helper to set the lastPaid timestamp for a given VaultProxy function __setLastPaidForVault(address _vaultProxy, uint256 _nextTimestamp) private { vaultProxyToLastPaid[_vaultProxy] = _nextTimestamp; } //////////////// // ADMIN ONLY // //////////////// /// @notice Sets the default protocol fee rate (in bps) /// @param _nextFeeBpsDefault The default protocol fee rate (in bps) to set function setFeeBpsDefault(uint256 _nextFeeBpsDefault) external onlyFundDeployerOwner { require(_nextFeeBpsDefault < MAX_BPS, "setDefaultFeeBps: Exceeds max"); feeBpsDefault = _nextFeeBpsDefault; emit FeeBpsDefaultSet(_nextFeeBpsDefault); } /// @notice Sets a specified protocol fee rate (in bps) for a particular VaultProxy /// @param _vaultProxy The VaultProxy /// @param _nextFeeBpsOverride The protocol fee rate (in bps) to set function setFeeBpsOverrideForVault(address _vaultProxy, uint256 _nextFeeBpsOverride) external onlyFundDeployerOwner { require(_nextFeeBpsOverride < MAX_BPS, "setFeeBpsOverrideForVault: Exceeds max"); vaultProxyToFeeBpsOverride[_vaultProxy] = _nextFeeBpsOverride; emit FeeBpsOverrideSetForVault(_vaultProxy, _nextFeeBpsOverride); } /// @notice Sets the lastPaid timestamp for a specified VaultProxy /// @param _vaultProxy The VaultProxy /// @param _nextTimestamp The lastPaid timestamp to set function setLastPaidForVault(address _vaultProxy, uint256 _nextTimestamp) external onlyFundDeployerOwner { uint256 prevTimestamp = getLastPaidForVault(_vaultProxy); require(prevTimestamp > 0, "setLastPaidForVault: _vaultProxy not initialized"); require( _nextTimestamp > prevTimestamp || _nextTimestamp > block.timestamp, "setLastPaidForVault: Can only increase or set a future timestamp" ); __setLastPaidForVault(_vaultProxy, _nextTimestamp); emit LastPaidSetForVault(_vaultProxy, prevTimestamp, _nextTimestamp); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `feeBpsDefault` variable value /// @return feeBpsDefault_ The `feeBpsDefault` variable value function getFeeBpsDefault() public view returns (uint256 feeBpsDefault_) { return feeBpsDefault; } /// @notice Gets the feeBpsOverride value for the given VaultProxy /// @param _vaultProxy The VaultProxy /// @return feeBpsOverride_ The feeBpsOverride value function getFeeBpsOverrideForVault(address _vaultProxy) public view returns (uint256 feeBpsOverride_) { return vaultProxyToFeeBpsOverride[_vaultProxy]; } /// @notice Gets the lastPaid value for the given VaultProxy /// @param _vaultProxy The VaultProxy /// @return lastPaid_ The lastPaid value function getLastPaidForVault(address _vaultProxy) public view returns (uint256 lastPaid_) { return vaultProxyToLastPaid[_vaultProxy]; } }
63,691
601
// Check if there is excess eth
uint256 excessETH = msg.value.sub(amountETH);
uint256 excessETH = msg.value.sub(amountETH);
74,146
48
// Notifies the controller about an approval allowing the controller to react if desiredInitialization check is implicitly provided by `onlyToken()`. return False if the controller does not authorize the approval/
function onApprove(address, address, uint) external onlyToken returns (bool) { return true; }
function onApprove(address, address, uint) external onlyToken returns (bool) { return true; }
11,614
2
// set LFG token address for contract
* @param {_token} address of IERC20 instance * @return {bool} return status of token address * */ function setLFGToken(IERC20 _token) external onlyOwner returns (bool) { lfgToken = _token; return true; }
* @param {_token} address of IERC20 instance * @return {bool} return status of token address * */ function setLFGToken(IERC20 _token) external onlyOwner returns (bool) { lfgToken = _token; return true; }
8,103
49
// Get stats about a particular UniV3 NFT
function getUniV3NFTValueInfo(uint256 token_id) public view returns (UniV3NFTValueInfo memory) { UniV3NFTBasicInfo memory lp_basic_info = getUniV3NFTBasicInfo(token_id); // Get pool price info uint160 sqrtPriceX96; { address pool_address = univ3_factory.getPool(lp_basic_info.token0, lp_basic_info.token1, lp_basic_info.fee); IUniswapV3Pool the_pool = IUniswapV3Pool(pool_address); (sqrtPriceX96, , , , , , ) = the_pool.slot0(); } // Tick math uint256 token0_val_usd = 0; uint256 token1_val_usd = 0; { // Get the amount of each underlying token in each NFT uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper); // Get amount of each token for 0.1% liquidity movement in each direction (1 per mille) uint256 liq_pricing_divisor = (10 ** lp_basic_info.lowest_decimals); (uint256 token0_1pm_amt, uint256 token1_1pm_amt) = LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, uint128(lp_basic_info.liquidity / liq_pricing_divisor)); // Get missing decimals uint256 token0_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token0_decimals); uint256 token1_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token1_decimals); // Get token prices // Will revert if ComboOracle doesn't have a price for both token0 and token1 (uint256 token0_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token0); (uint256 token1_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token1); // Get the value of each portion // Multiply by liq_pricing_divisor as well token0_val_usd = (token0_1pm_amt * liq_pricing_divisor * token0_precise_price * token0_miss_dec_mult) / PRECISE_PRICE_PRECISION; token1_val_usd = (token1_1pm_amt * liq_pricing_divisor * token1_precise_price * token1_miss_dec_mult) / PRECISE_PRICE_PRECISION; } // Return the total value of the UniV3 NFT uint256 nft_ttl_val = (token0_val_usd + token1_val_usd); // Return return UniV3NFTValueInfo( token0_val_usd, token1_val_usd, nft_ttl_val, ERC20(lp_basic_info.token0).symbol(), ERC20(lp_basic_info.token1).symbol(), (uint256(lp_basic_info.liquidity) * PRECISE_PRICE_PRECISION) / nft_ttl_val ); }
function getUniV3NFTValueInfo(uint256 token_id) public view returns (UniV3NFTValueInfo memory) { UniV3NFTBasicInfo memory lp_basic_info = getUniV3NFTBasicInfo(token_id); // Get pool price info uint160 sqrtPriceX96; { address pool_address = univ3_factory.getPool(lp_basic_info.token0, lp_basic_info.token1, lp_basic_info.fee); IUniswapV3Pool the_pool = IUniswapV3Pool(pool_address); (sqrtPriceX96, , , , , , ) = the_pool.slot0(); } // Tick math uint256 token0_val_usd = 0; uint256 token1_val_usd = 0; { // Get the amount of each underlying token in each NFT uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper); // Get amount of each token for 0.1% liquidity movement in each direction (1 per mille) uint256 liq_pricing_divisor = (10 ** lp_basic_info.lowest_decimals); (uint256 token0_1pm_amt, uint256 token1_1pm_amt) = LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, uint128(lp_basic_info.liquidity / liq_pricing_divisor)); // Get missing decimals uint256 token0_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token0_decimals); uint256 token1_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token1_decimals); // Get token prices // Will revert if ComboOracle doesn't have a price for both token0 and token1 (uint256 token0_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token0); (uint256 token1_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token1); // Get the value of each portion // Multiply by liq_pricing_divisor as well token0_val_usd = (token0_1pm_amt * liq_pricing_divisor * token0_precise_price * token0_miss_dec_mult) / PRECISE_PRICE_PRECISION; token1_val_usd = (token1_1pm_amt * liq_pricing_divisor * token1_precise_price * token1_miss_dec_mult) / PRECISE_PRICE_PRECISION; } // Return the total value of the UniV3 NFT uint256 nft_ttl_val = (token0_val_usd + token1_val_usd); // Return return UniV3NFTValueInfo( token0_val_usd, token1_val_usd, nft_ttl_val, ERC20(lp_basic_info.token0).symbol(), ERC20(lp_basic_info.token1).symbol(), (uint256(lp_basic_info.liquidity) * PRECISE_PRICE_PRECISION) / nft_ttl_val ); }
11,567
193
// revert if we can't withdraw full balance /
function prepareMigration(address _newStrategy) internal override { uint256 outstanding = vault.strategies(address(this)).totalDebt; (,uint loss, uint wantBalance) = prepareReturn(outstanding); require(wantBalance.add(loss) >= outstanding, "LIQUIDITY LOCKED"); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); }
function prepareMigration(address _newStrategy) internal override { uint256 outstanding = vault.strategies(address(this)).totalDebt; (,uint loss, uint wantBalance) = prepareReturn(outstanding); require(wantBalance.add(loss) >= outstanding, "LIQUIDITY LOCKED"); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); }
40,097
11
// Perform actual minting of the tokens
function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } }
function _mintTokens(address to, uint count) internal { for(uint index = 0; index < count; index++) { _tokenIds.increment(); uint newItemId = _tokenIds.current(); _safeMint(to, newItemId); } }
13,674
6
// left a->f
if (uint8(bytes(_hexStr)[i]) >= 97 && uint8(bytes(_hexStr)[i]) <= 102) tetrad1 = uint8(bytes(_hexStr)[i]) - 97 + 10;
if (uint8(bytes(_hexStr)[i]) >= 97 && uint8(bytes(_hexStr)[i]) <= 102) tetrad1 = uint8(bytes(_hexStr)[i]) - 97 + 10;
21,519
55
// Sets an configuration value Changes the value of a key in the configuration mapping key The configuration key for which the value will be set value The value to set the key /
function setAddressConfiguration(bytes32 key, address value) external hasAccess(this, AclFlag.SET_CONFIGURATION)
function setAddressConfiguration(bytes32 key, address value) external hasAccess(this, AclFlag.SET_CONFIGURATION)
62,467
10
// This is to protect players preventing the owner from running away with the contract balance when players are still playing the game. This function can only be operated after specified minutes has passed since gate guard is up.
require(shouldGateGuard == true && (sinceGateGuarded - now) > 10 minutes); _;
require(shouldGateGuard == true && (sinceGateGuarded - now) > 10 minutes); _;
44,977
202
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
return string(abi.encodePacked(_baseURI, tokenId.toString()));
205
17
// investor uses this function to claim share token
function cST() public virtual returns (bool) { address caller = msg.sender; require( _wlMember[caller] == true, "only white-listed members can claim share tokens" ); require(_claimST[caller] > 0, "you have 0 share token to claim"); require( _st.balanceOf(address(this)) >= _claimST[caller], "cST: this should never happen => insufficient balance of share tokens in contract" ); _st.transfer(caller, _claimST[caller]); _claimST[caller] = 0; return true; }
function cST() public virtual returns (bool) { address caller = msg.sender; require( _wlMember[caller] == true, "only white-listed members can claim share tokens" ); require(_claimST[caller] > 0, "you have 0 share token to claim"); require( _st.balanceOf(address(this)) >= _claimST[caller], "cST: this should never happen => insufficient balance of share tokens in contract" ); _st.transfer(caller, _claimST[caller]); _claimST[caller] = 0; return true; }
12,954
81
// Creates clone, more info here: https:blog.openzeppelin.com/deep-dive-into-the-minimal-proxy-contract/
assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) cloneAddress := create2(0, clone, 0x37, salt) }
assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) cloneAddress := create2(0, clone, 0x37, salt) }
72,910
558
// BASE 64 - Written by Brech Devos /
function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; }
function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; }
12,827
41
// Get the reward, sell it in exchange for underlying, invest what you got. It's not much, but it's honest work. Note that although `onlyNotPausedInvesting` is not added here, calling `investAllUnderlying()` affectively blocks the usage of `doHardWork` when the investing is being paused by governance./
function doHardWork() external override onlyNotPausedInvesting restricted { uint256 bal = rewardPoolBalance(); if (bal != 0) { _claimReward(); _liquidateReward(); } investAllUnderlying(); }
function doHardWork() external override onlyNotPausedInvesting restricted { uint256 bal = rewardPoolBalance(); if (bal != 0) { _claimReward(); _liquidateReward(); } investAllUnderlying(); }
39,202
1,213
// Returns the secondary rewarder if it is set
function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; if (context.hasSecondaryRewarder) { return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress]; } else { return IRewarder(address(0)); } }
function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; if (context.hasSecondaryRewarder) { return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress]; } else { return IRewarder(address(0)); } }
4,184
3
// Create new investment pool.token The address token contract for investment pool.locked The blocking period of assets.rate The address to query the wager of.interestFee The asset withdrawal commission.anualPrecent The annual percentage of tokens.superAdmin The An address that has privileges SUPER_ADMIN_ROLE.gPartner The An address that has privileges GENERAL_PARTNER_ROLE.lPartner The An address that has privileges LIMITED_PARTNER_ROLE.team The An address that has privileges TEAM_ROLE.sturtapTeam The An address that has privileges STURTAP_TEAM_ROLE.referer The An address that has privileges REFERER_ROLE. return A boolean that indicates if the operation was successful./
function createPool( address token, uint256 locked, uint256 rate, uint256 interestFee,
function createPool( address token, uint256 locked, uint256 rate, uint256 interestFee,
4,333
29
// existing unstaking period will be adjusted
_adjustOrCreateUnstakingPeriod( staker, totalStakedPerCurrentUnstakingPeriod, _increasedUnstakingPeriod, false ); staker.unstakingPeriods[currentUnstakingPeriodPos] = staker .unstakingPeriods[staker.unstakingPeriods.length - 1]; staker.unstakingPeriods.pop();
_adjustOrCreateUnstakingPeriod( staker, totalStakedPerCurrentUnstakingPeriod, _increasedUnstakingPeriod, false ); staker.unstakingPeriods[currentUnstakingPeriodPos] = staker .unstakingPeriods[staker.unstakingPeriods.length - 1]; staker.unstakingPeriods.pop();
10,032
11
// Vested wallet address
address public vestedAddress;
address public vestedAddress;
41,299