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
0
// ====================== 🇽 VARIABLES 🇾 =======================
uint256 public maxSupply = 5555; uint256 public mintPrice = 0.004 ether; uint256 public maxPerTxn = 10; uint256 public maxFree = 1; string public baseExtension = ".json"; string public baseURI; bool public mintEnabled = false; bool public revealed = false; constructor (
uint256 public maxSupply = 5555; uint256 public mintPrice = 0.004 ether; uint256 public maxPerTxn = 10; uint256 public maxFree = 1; string public baseExtension = ".json"; string public baseURI; bool public mintEnabled = false; bool public revealed = false; constructor (
34,630
164
// create a collection minted using erc20 tokens. Requirements: senders need to sets `_castingValue` amount as the allowance of this contract in ERC20 token in advance./
function mintByERC20(address _addr, uint256 _value, string memory _uri,uint256 _burnTime) external returns (uint256) { require(_value > 0, "Value must be greater than 0"); IERC20 erc20Token = IERC20(_addr); require(erc20Token.allowance(msg.sender, address(this)) >= _value, "Insufficient allowance!"); require(erc20Token.transferFrom(msg.sender, address(this), _value), "Transfer failed!"); return _create(2,_uri,_value,_addr, _burnTime); }
function mintByERC20(address _addr, uint256 _value, string memory _uri,uint256 _burnTime) external returns (uint256) { require(_value > 0, "Value must be greater than 0"); IERC20 erc20Token = IERC20(_addr); require(erc20Token.allowance(msg.sender, address(this)) >= _value, "Insufficient allowance!"); require(erc20Token.transferFrom(msg.sender, address(this), _value), "Transfer failed!"); return _create(2,_uri,_value,_addr, _burnTime); }
56,341
61
// Returns the address of the owner of the NFT. NFTs assigned to zero address are consideredinvalid, and queries about them do throw. _tokenId The identifier for an NFT. /
function ownerOf( uint256 _tokenId ) external view returns (address _owner)
function ownerOf( uint256 _tokenId ) external view returns (address _owner)
38,734
12
// 1. TODO define a contract call to the zokrates generated solidity contract <Verifier> or <renamedVerifier>
contract Verifier { function verifyTx( uint[2] memory A, uint[2] memory A_p, uint[2][2] memory B, uint[2] memory B_p, uint[2] memory C, uint[2] memory C_p, uint[2] memory H, uint[2] memory K, uint[2] memory input ) public returns (bool r); }
contract Verifier { function verifyTx( uint[2] memory A, uint[2] memory A_p, uint[2][2] memory B, uint[2] memory B_p, uint[2] memory C, uint[2] memory C_p, uint[2] memory H, uint[2] memory K, uint[2] memory input ) public returns (bool r); }
40,189
68
// payOracle pays out _transmitter's balance to the corresponding payee, and zeros it out
function payOracle(address _transmitter) internal
function payOracle(address _transmitter) internal
35,914
154
// our simple algo get the lowest apr strat cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1); _lowest = 0; uint256 lowestNav = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < _lowestApr) { _lowestApr = apr; _lowest = i; lowestNav = lenders[i].nav();
_lowestApr = uint256(-1); _lowest = 0; uint256 lowestNav = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < _lowestApr) { _lowestApr = apr; _lowest = i; lowestNav = lenders[i].nav();
11,515
114
// Compound
address private constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address private constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address private immutable cToken;
address private constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address private constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address private immutable cToken;
6,693
279
// Remove an `IZap` from the registry name The name of the `IZap` (see `INameIdentifier`) /
function removeZap(string calldata name) external;
function removeZap(string calldata name) external;
27,373
37
// new owner only activity. (Voting to be implemented for owner replacement)
function removeController(address controllerToRemove) public justOwner { require(contracts[controllerToRemove]); contracts[controllerToRemove] = false; }
function removeController(address controllerToRemove) public justOwner { require(contracts[controllerToRemove]); contracts[controllerToRemove] = false; }
37,429
1
// Modifiers // /
modifier whenNotPaused() { require( !_getSettings().atmSettings().isATMPaused(atmAddress), "ATM_IS_PAUSED" ); _; }
modifier whenNotPaused() { require( !_getSettings().atmSettings().isATMPaused(atmAddress), "ATM_IS_PAUSED" ); _; }
4,457
162
// Stakers set which migrator(s) they want to use
mapping(address => mapping(address => bool)) internal staker_allowed_migrators; mapping(address => address) public staker_designated_proxies; // Keep public so users can see on the frontend if they have a proxy
mapping(address => mapping(address => bool)) internal staker_allowed_migrators; mapping(address => address) public staker_designated_proxies; // Keep public so users can see on the frontend if they have a proxy
50,381
9
// Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
82,031
49
// Splitbid/Overbid
if (ethCost > _platValue) { cards.setCoinBalance(_player,SafeMath.sub(ethCost,_platValue),1,false); } else if (_platValue > ethCost) {
if (ethCost > _platValue) { cards.setCoinBalance(_player,SafeMath.sub(ethCost,_platValue),1,false); } else if (_platValue > ethCost) {
45,014
792
// We've found a branch node, but it doesn't contain our key. Reinsert the old branch for now.
newNodes[totalNewNodes] = lastNode; totalNewNodes += 1;
newNodes[totalNewNodes] = lastNode; totalNewNodes += 1;
56,994
78
// User Interface // Sender supplies assets into the market and receives kTokens in exchange Reverts upon any failurereturn the actual mint amount. /
function mint() external payable returns (uint) { return mintInternal(msg.value); }
function mint() external payable returns (uint) { return mintInternal(msg.value); }
70,432
181
// Check that the calling account has the minter role the midex contract will be the minter
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter"); _mint(to, amount);
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter"); _mint(to, amount);
9,474
66
// Sub `base` from `total` and update `total.elastic`./ return (Rebase) The new total./ return elastic in relationship to `base`.
function sub( Rebase memory total, uint256 base, bool roundUp
function sub( Rebase memory total, uint256 base, bool roundUp
22,512
214
// TODO: static_assert + no error code?
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
33,133
88
// Approve `operator` to operate on all of `owner` tokens
* Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner_, address operator, bool approved ) internal virtual { require(owner_ != operator, "ERC721: approve to caller"); _operatorApprovals[owner_][operator] = approved; emit ApprovalForAll(owner_, operator, approved); }
* Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner_, address operator, bool approved ) internal virtual { require(owner_ != operator, "ERC721: approve to caller"); _operatorApprovals[owner_][operator] = approved; emit ApprovalForAll(owner_, operator, approved); }
33,899
42
// Returns true if the given address is a permissioned offRamp/ and sourceChainSelector if so.
function isOffRamp(address offRamp) external view returns (bool, uint64) { (bool exists, uint256 sourceChainSelector) = s_offRamps.tryGet(offRamp); return (exists, uint64(sourceChainSelector)); }
function isOffRamp(address offRamp) external view returns (bool, uint64) { (bool exists, uint256 sourceChainSelector) = s_offRamps.tryGet(offRamp); return (exists, uint64(sourceChainSelector)); }
37,399
2
// Agreement vars
IERC20 public token; address payable public brand; address payable public influencer; uint256 public endDate; uint256 public payPerView; uint256 public budget; bool public usingEth; string public mediaLink; Status public agreementStatus; //= Status.PROPOSED; string public API_KEY ;//= "&key=AIzaSyB8UEknqf0DmdJW5Ow6rGP8co7I_dZEhwo";
IERC20 public token; address payable public brand; address payable public influencer; uint256 public endDate; uint256 public payPerView; uint256 public budget; bool public usingEth; string public mediaLink; Status public agreementStatus; //= Status.PROPOSED; string public API_KEY ;//= "&key=AIzaSyB8UEknqf0DmdJW5Ow6rGP8co7I_dZEhwo";
50,181
169
// Updated retrieval to handle future planned upgrades if needed
uint temp = wrapperdb(dbcontract).getArtStatus(tokenId);
uint temp = wrapperdb(dbcontract).getArtStatus(tokenId);
38,365
0
// prettier-ignore
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 private constant TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); uint256 private constant SLIPPAGE_BASE_UNIT = 10**18; IERC20 public pbtc; IERC20 public metaToken; IERC20 public crv; ICurveDepositPBTC public depositPbtc; ICurveGaugeV2 public gauge; ModifiedUnipool public modifiedUnipool;
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 private constant TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); uint256 private constant SLIPPAGE_BASE_UNIT = 10**18; IERC20 public pbtc; IERC20 public metaToken; IERC20 public crv; ICurveDepositPBTC public depositPbtc; ICurveGaugeV2 public gauge; ModifiedUnipool public modifiedUnipool;
36,020
123
// Add reserves by transferring from caller Requires fresh interest accrual addAmount Amount of addition to reservesreturn (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees /
function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); }
function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); }
7,415
18
// Harvests earnings (compounds rewards) and charges performance fee
function harvest() external { _harvest(true); }
function harvest() external { _harvest(true); }
9,409
0
// <yes> <report> UNCHECKED_LL_CALLS
msg.sender.send(amountToWithdraw);
msg.sender.send(amountToWithdraw);
24,232
140
// also get rewards from linked rewards
if(_claimExtras){ uint256 length = extraRewards.length; for(uint i=0; i < length; i++){ IRewards(extraRewards[i]).getReward(_account); }
if(_claimExtras){ uint256 length = extraRewards.length; for(uint i=0; i < length; i++){ IRewards(extraRewards[i]).getReward(_account); }
29,972
101
// calculate user's interest due for new bond, accounting for Olympus Fee_value uint return uint /
function payoutFor( uint _value ) external view returns ( uint ) { uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 ); return total.sub(total.mul( currentOlympusFee() ).div( 1e6 )); }
function payoutFor( uint _value ) external view returns ( uint ) { uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 ); return total.sub(total.mul( currentOlympusFee() ).div( 1e6 )); }
23,890
206
// The block number when CNT mining starts.
uint256 public startBlock; uint256 public constant EVENT_INDEX_IN_RECEIPT = 3; uint256 public TRANSFER_EVENT_INDEX_IN_RECEIPT = 2; // TODO: Make it changeable by owner uint256 public TRANSFER_EVENT_PARAMS_INDEX_IN_RECEIPT = 1; // TODO: Make it changeable by owner bytes32 public constant TRANSFER_EVENT_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; event PoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken);
uint256 public startBlock; uint256 public constant EVENT_INDEX_IN_RECEIPT = 3; uint256 public TRANSFER_EVENT_INDEX_IN_RECEIPT = 2; // TODO: Make it changeable by owner uint256 public TRANSFER_EVENT_PARAMS_INDEX_IN_RECEIPT = 1; // TODO: Make it changeable by owner bytes32 public constant TRANSFER_EVENT_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; event PoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken);
10,742
38
// return the list of valid signatories registered in the contract
function getValidSignatoryList() public constant returns (address[] memory) { return validSignatories; }
function getValidSignatoryList() public constant returns (address[] memory) { return validSignatories; }
44,347
138
// Whitelist Clipper on pip
addReaderToOSMWhitelist(co.pip, co.clip);
addReaderToOSMWhitelist(co.pip, co.clip);
48,704
34
// calculate the cost of the lock by its size and skin/_size The lock size/_skin The lock skin
function calculateCost(uint _size, uint _skin) public view returns (uint cost) { // Calculate cost by size if(_size == 2) cost = mediumPrice; else if(_size == 3) cost = bigPrice; else cost = smallPrice; // Apply price modifiers if(_skin >= PREMIUM_TYPE) cost = cost * premiumMod; else if(_skin >= MEDIUM_TYPE) cost = cost * mediumMod; return cost; }
function calculateCost(uint _size, uint _skin) public view returns (uint cost) { // Calculate cost by size if(_size == 2) cost = mediumPrice; else if(_size == 3) cost = bigPrice; else cost = smallPrice; // Apply price modifiers if(_skin >= PREMIUM_TYPE) cost = cost * premiumMod; else if(_skin >= MEDIUM_TYPE) cost = cost * mediumMod; return cost; }
37,702
0
// WORLD WAR GOO (BETA LAUNCHING SOONISH)PRELAUNCH EVENT CONTRACT FOR LIMITED CLANS & PREMIUM FACTORIES! FOR MORE DETAILS VISIT:/
uint256 constant SUPPORTER_PACK_PRICE = 0.1 ether; uint256 constant CRYPTO_CLAN_PRICE = 1 ether; uint256 constant PREMIUM_FACTORY_PRICE = 0.5 ether; uint256 constant GAS_LIMIT = 0.05 szabo; // 50 gwei uint256 public startTime = 1544832000; // Friday evening (00:00 UTC) uint256 clanIdStart; // Can release in waves uint256 clanIdEnd;
uint256 constant SUPPORTER_PACK_PRICE = 0.1 ether; uint256 constant CRYPTO_CLAN_PRICE = 1 ether; uint256 constant PREMIUM_FACTORY_PRICE = 0.5 ether; uint256 constant GAS_LIMIT = 0.05 szabo; // 50 gwei uint256 public startTime = 1544832000; // Friday evening (00:00 UTC) uint256 clanIdStart; // Can release in waves uint256 clanIdEnd;
10,278
70
// Burn tokens._value number of tokens to burn /
function burnTokens (uint256 _value)
function burnTokens (uint256 _value)
75,680
26
// ```
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
112
17
// This function should allow governance to set a new protocol fee for relayers instance the to update newFee the new fee to use/
function setProtocolFee(ITornadoInstance instance, uint32 newFee) external onlyGovernance { instances[instance].protocolFeePercentage = newFee; }
function setProtocolFee(ITornadoInstance instance, uint32 newFee) external onlyGovernance { instances[instance].protocolFeePercentage = newFee; }
5,722
30
// SUPPLY CONTROL EVENTS
event SupplyIncreased(address indexed to, uint256 value); event SupplyDecreased(address indexed from, uint256 value); event SupplyControllerSet( address indexed oldSupplyController, address indexed newSupplyController );
event SupplyIncreased(address indexed to, uint256 value); event SupplyDecreased(address indexed from, uint256 value); event SupplyControllerSet( address indexed oldSupplyController, address indexed newSupplyController );
14,971
11
// File @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol@v4.1.0
interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
29,838
27
// Checks if address is the token owner addr addressreturn bool. True if address is token owner, false otherwise. /
function _isTokenOwner(address addr) internal view returns (bool) { return addr == _tokenOwner(); }
function _isTokenOwner(address addr) internal view returns (bool) { return addr == _tokenOwner(); }
29,340
9
// 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 Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
64,581
11
// Its important to change the state first because otherwise, the contracts called using 'send' below can call in again here.
state = State.Inactive;
state = State.Inactive;
45,044
0
// ADMIN full administrative privileges can manage all rolesAPI can sign data published in dataURIBIDDER can sign bids sent to consumers over the messaging systemMANAGER can add staff and perform non-critical tasks (no finance access)FINANCE can retrieve funds owned by the service providerSTAFF non-critical tasksWRITE = (ADMIN || API || MANAGER || WRITE)
enum Role { ADMIN, API, BIDDER, MANAGER, STAFF, WRITE }
enum Role { ADMIN, API, BIDDER, MANAGER, STAFF, WRITE }
8,114
23
// ======================================/ ============= Claim logic ============/ ======================================/Lets an account claim NFTs.
function claim( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, bytes32[] calldata _proofs, uint256 _proofMaxQuantityPerTransaction
function claim( address _receiver, uint256 _quantity, address _currency, uint256 _pricePerToken, bytes32[] calldata _proofs, uint256 _proofMaxQuantityPerTransaction
14,250
242
// Current state. See RaiseState enum for details
RaiseState public raiseState = RaiseState.Open;
RaiseState public raiseState = RaiseState.Open;
73,331
98
// Precisely divides two units, by first scaling the left hand operand. Useful for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) x Left hand input to division y Right hand input to divisionreturn Result after multiplying the left operand by the scale, andexecuting the division on the right hand input. /
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256)
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256)
4,319
46
// Allows the DAO to change the amount of time insurance remains valid after liquidation/_newLimit New time limit
function setInsuranceRepurchaseTimeLimit(uint256 _newLimit) external onlyRole(DAO_ROLE) { require(_newLimit != 0, "invalid_limit"); settings.insuranceRepurchaseTimeLimit = _newLimit; }
function setInsuranceRepurchaseTimeLimit(uint256 _newLimit) external onlyRole(DAO_ROLE) { require(_newLimit != 0, "invalid_limit"); settings.insuranceRepurchaseTimeLimit = _newLimit; }
54,092
46
// No limit on Dev wallet and UniSwap Contract so liquidity can be added
if(Buylimitactive && msg.sender != owner() && msg.sender != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D){ require(amount <= BuyLimit); // Buylimit not allowed to be over actualBuylimit }
if(Buylimitactive && msg.sender != owner() && msg.sender != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D){ require(amount <= BuyLimit); // Buylimit not allowed to be over actualBuylimit }
85,491
4
// Mapping from owner to list of owned NFT IDs. /
mapping(address => uint256[]) internal ownerToIds;
mapping(address => uint256[]) internal ownerToIds;
8,307
75
// We have only one snapshot, so let's use the dummy snapshot
subtractSnapshot = lastSnapshot;
subtractSnapshot = lastSnapshot;
27,584
3
// Developer events
event AddDevEvent(uint32 indexed store, address indexed dev, bytes32 name, bytes32 desc); event ChangeNameDevEvent(uint32 indexed store, address indexed dev, bytes32 name, bytes32 desc); event SetStoreBlockedDevEvent(uint32 indexed store, address indexed dev, bool state); event SetRatingDevEvent(uint32 indexed store, address indexed dev, int rating);
event AddDevEvent(uint32 indexed store, address indexed dev, bytes32 name, bytes32 desc); event ChangeNameDevEvent(uint32 indexed store, address indexed dev, bytes32 name, bytes32 desc); event SetStoreBlockedDevEvent(uint32 indexed store, address indexed dev, bool state); event SetRatingDevEvent(uint32 indexed store, address indexed dev, int rating);
16,086
30
// TokenFactoryCyril Lapinte - <cyril.lapinte@openfiz.com>SPDX-License-Identifier: MIT Error messagesTF01: required privileges must be granted from the core to the factoryTF02: There must be the same number of vault and suppliesTF03: Token proxy contract must be deployedTF04: Token must be defined in the coreTF05: Issuer role must be granted on the proxyTF06: The rule must be setTF07: The token must have its locksTF08: The token must be lockedTF09: Token must be mintedTF10: Token minting must be finishedTF11: Incorrect core providedTF12: The rule must be removedTF13: DefineAuditTriggers privileges is required for setting complianceTF14: Wrapped token contract must be deployedTF15: Wrapped token contract should be
contract TokenFactory is ITokenFactory, Factory, OperableAsCore, YesNoRule, Operable { /* * @dev constructor */ constructor() public YesNoRule(false) {} /* * @dev has core access */ function hasCoreAccess(ITokenCore _core) override public view returns (bool access) { access = true; for (uint256 i=0; i<requiredCorePrivileges.length; i++) { access = access && _core.hasCorePrivilege( address(this), requiredCorePrivileges[i]); } for (uint256 i=0; i<requiredProxyPrivileges.length; i++) { access = access && _core.hasProxyPrivilege( address(this), ALL_PROXIES, requiredProxyPrivileges[i]); } } /** * @dev defineBlueprint */ function defineBlueprint( uint256 _id, address _template, bytes memory _bytecode, bytes memory _defaultParameters) override public onlyOperator returns (bool) { return defineBlueprintInternal(_id, _template, _bytecode, _defaultParameters); } /** * @dev deployContract */ function deployContract(uint256 _id, bytes memory _parameters) public override returns (address) { return deployContractInternal(_id, _parameters); } /** * @dev deploy token */ function deployToken( ITokenCore _core, uint256 _delegateId, string memory _name, string memory _symbol, uint256 _decimals, uint64 _lockEnd, bool _finishMinting, address[] memory _vaults, uint256[] memory _supplies, address[] memory _proxyOperators ) override public returns (IERC20) { require(hasCoreAccess(_core), "TF01"); require(_vaults.length == _supplies.length, "TF02"); // 1- Creating a proxy IERC20 token = IERC20(deployContractInternal( uint256(ProxyCode.TOKEN), abi.encode(address(_core)))); require(address(token) != address(0), "TF03"); // 2- Defining the token in the core require(_core.defineToken( address(token), _delegateId, _name, _symbol, _decimals), "TF04"); // 3- Assign roles require(_core.assignProxyOperators(address(token), ISSUER_PROXY_ROLE, _proxyOperators), "TF05"); // 4- Define rules // Token is blocked for review and approval by core operators // This contract is used as a YesNo rule configured as No to prevent transfers // Removing this contract from the rules will unlock the token if (!_core.hasCorePrivilege(msg.sender, APPROVE_TOKEN_PRIV)) { IRule[] memory factoryRules = new IRule[](1); factoryRules[0] = IRule(address(this)); require(_core.defineRules(address(token), factoryRules), "TF06"); } // 5- Locking the token address[] memory locks = new address[](1); locks[0] = address(token); require(_core.defineTokenLocks(address(token), locks), "TF07"); // solhint-disable-next-line not-rely-on-time if (_lockEnd > now) { require(_core.defineLock( address(token), ANY_ADDRESSES, ANY_ADDRESSES, 0, _lockEnd), "TF08"); } // 6- Minting the token require(_core.mint(address(token), _vaults, _supplies), "TF09"); // 7 - Finish the minting if(_finishMinting) { require(_core.finishMinting(address(token)), "TF10"); } emit TokenDeployed(token); return token; } /** * @dev approveToken */ function approveToken(ITokenCore _core, ITokenProxy _token) override public onlyCoreOperator(_core) returns (bool) { require(hasCoreAccess(_core), "TF01"); require(_token.core() == address(_core), "TF11"); // This ensure that the call does not change a custom made rules configuration (,,,,,,IRule[] memory rules) = _core.token(address(_token)); if (rules.length == 1 && rules[0] == IRule(this)) { require(_core.defineRules(address(_token), new IRule[](0)), "TF12"); } emit TokenApproved(_token); return true; } /** * @dev deploy wrapped token */ function deployWrappedToken( ITokenProxy _token, string memory _name, string memory _symbol, uint256 _decimals, address[] memory _vaults, uint256[] memory _supplies, bool _compliance ) override public onlyProxyOperator(Proxy(address(_token))) returns (IERC20) { require(_vaults.length == _supplies.length, "TF02"); ITokenCore core; if (_compliance) { core = ITokenCore(_token.core()); require(hasCoreAccess(core), "TF01"); require(core.hasCorePrivilege(msg.sender, DEFINE_AUDIT_TRIGGERS_PRIV), "TF13"); } // 1- Creating a wrapped token IWrappedERC20 wToken = IWrappedERC20(deployContractInternal( uint256(ProxyCode.WRAPPED_TOKEN), abi.encode(_name, _symbol, _decimals, address(_token)))); require(address(wToken) != address(0), "TF14"); emit WrappedTokenDeployed(_token, wToken); // 2- Compliance Configuration if (_compliance) { // Avoid the approval step for non self managed users address[] memory operators = new address[](1); operators[0] = address(wToken); require(core.assignProxyOperators(address(_token), OPERATOR_PROXY_ROLE, operators), "TF15"); // Avoid KYC restrictions for the wrapped tokens (AuditConfigurationId == 0) { uint256 delegateId = core.proxyDelegateId(address(_token)); uint256 auditConfigurationId = core.delegatesConfigurations(delegateId)[0]; address[] memory senders = new address[](2); senders[0] = ANY_ADDRESSES; senders[1] = address(wToken); address[] memory receivers = new address[](2); receivers[0] = address(wToken); receivers[1] = ANY_ADDRESSES; ITokenStorage.AuditTriggerMode[] memory modes = new ITokenStorage.AuditTriggerMode[](2); modes[0] = ITokenStorage.AuditTriggerMode.NONE; modes[1] = ITokenStorage.AuditTriggerMode.RECEIVER_ONLY; require(core.defineAuditTriggers(auditConfigurationId, senders, receivers, modes), "TF16"); } require(core.defineLock(address(_token), address(this), ANY_ADDRESSES, ~uint64(0), ~uint64(0)), "TF17"); } else { require(_token.approve(address(wToken), ~uint256(0)), "TF18"); } // 3- Wrap tokens for(uint256 i=0; i < _vaults.length; i++) { require(wToken.depositTo(_vaults[i], _supplies[i]), "TF19"); } return wToken; } /** * @dev configureTokensales */ function configureTokensales( ITokenProxy _token, address[] memory _tokensales, uint256[] memory _allowances) override public onlyProxyOperator(Proxy(address(_token))) returns (bool) { ITokenCore core = ITokenCore(_token.core()); require(hasCoreAccess(core), "TF01"); require(_tokensales.length == _allowances.length, "TF20"); for(uint256 i=0; i < _tokensales.length; i++) { require(core.defineLock(address(_token), _tokensales[i], ANY_ADDRESSES, ~uint64(0), ~uint64(0)), "TF21"); } updateAllowances(_token, _tokensales, _allowances); emit TokensalesConfigured(_token, _tokensales); } /** * @dev updateAllowance */ function updateAllowances( ITokenProxy _token, address[] memory _spenders, uint256[] memory _allowances) override public onlyProxyOperator(_token) returns (bool) { uint256 balance = _token.balanceOf(address(this)); for(uint256 i=0; i < _spenders.length; i++) { require(_allowances[i] <= balance, "TF22"); require(_token.approve(_spenders[i], _allowances[i]), "TF23"); emit AllowanceUpdated(_token, _spenders[i], _allowances[i]); } } }
contract TokenFactory is ITokenFactory, Factory, OperableAsCore, YesNoRule, Operable { /* * @dev constructor */ constructor() public YesNoRule(false) {} /* * @dev has core access */ function hasCoreAccess(ITokenCore _core) override public view returns (bool access) { access = true; for (uint256 i=0; i<requiredCorePrivileges.length; i++) { access = access && _core.hasCorePrivilege( address(this), requiredCorePrivileges[i]); } for (uint256 i=0; i<requiredProxyPrivileges.length; i++) { access = access && _core.hasProxyPrivilege( address(this), ALL_PROXIES, requiredProxyPrivileges[i]); } } /** * @dev defineBlueprint */ function defineBlueprint( uint256 _id, address _template, bytes memory _bytecode, bytes memory _defaultParameters) override public onlyOperator returns (bool) { return defineBlueprintInternal(_id, _template, _bytecode, _defaultParameters); } /** * @dev deployContract */ function deployContract(uint256 _id, bytes memory _parameters) public override returns (address) { return deployContractInternal(_id, _parameters); } /** * @dev deploy token */ function deployToken( ITokenCore _core, uint256 _delegateId, string memory _name, string memory _symbol, uint256 _decimals, uint64 _lockEnd, bool _finishMinting, address[] memory _vaults, uint256[] memory _supplies, address[] memory _proxyOperators ) override public returns (IERC20) { require(hasCoreAccess(_core), "TF01"); require(_vaults.length == _supplies.length, "TF02"); // 1- Creating a proxy IERC20 token = IERC20(deployContractInternal( uint256(ProxyCode.TOKEN), abi.encode(address(_core)))); require(address(token) != address(0), "TF03"); // 2- Defining the token in the core require(_core.defineToken( address(token), _delegateId, _name, _symbol, _decimals), "TF04"); // 3- Assign roles require(_core.assignProxyOperators(address(token), ISSUER_PROXY_ROLE, _proxyOperators), "TF05"); // 4- Define rules // Token is blocked for review and approval by core operators // This contract is used as a YesNo rule configured as No to prevent transfers // Removing this contract from the rules will unlock the token if (!_core.hasCorePrivilege(msg.sender, APPROVE_TOKEN_PRIV)) { IRule[] memory factoryRules = new IRule[](1); factoryRules[0] = IRule(address(this)); require(_core.defineRules(address(token), factoryRules), "TF06"); } // 5- Locking the token address[] memory locks = new address[](1); locks[0] = address(token); require(_core.defineTokenLocks(address(token), locks), "TF07"); // solhint-disable-next-line not-rely-on-time if (_lockEnd > now) { require(_core.defineLock( address(token), ANY_ADDRESSES, ANY_ADDRESSES, 0, _lockEnd), "TF08"); } // 6- Minting the token require(_core.mint(address(token), _vaults, _supplies), "TF09"); // 7 - Finish the minting if(_finishMinting) { require(_core.finishMinting(address(token)), "TF10"); } emit TokenDeployed(token); return token; } /** * @dev approveToken */ function approveToken(ITokenCore _core, ITokenProxy _token) override public onlyCoreOperator(_core) returns (bool) { require(hasCoreAccess(_core), "TF01"); require(_token.core() == address(_core), "TF11"); // This ensure that the call does not change a custom made rules configuration (,,,,,,IRule[] memory rules) = _core.token(address(_token)); if (rules.length == 1 && rules[0] == IRule(this)) { require(_core.defineRules(address(_token), new IRule[](0)), "TF12"); } emit TokenApproved(_token); return true; } /** * @dev deploy wrapped token */ function deployWrappedToken( ITokenProxy _token, string memory _name, string memory _symbol, uint256 _decimals, address[] memory _vaults, uint256[] memory _supplies, bool _compliance ) override public onlyProxyOperator(Proxy(address(_token))) returns (IERC20) { require(_vaults.length == _supplies.length, "TF02"); ITokenCore core; if (_compliance) { core = ITokenCore(_token.core()); require(hasCoreAccess(core), "TF01"); require(core.hasCorePrivilege(msg.sender, DEFINE_AUDIT_TRIGGERS_PRIV), "TF13"); } // 1- Creating a wrapped token IWrappedERC20 wToken = IWrappedERC20(deployContractInternal( uint256(ProxyCode.WRAPPED_TOKEN), abi.encode(_name, _symbol, _decimals, address(_token)))); require(address(wToken) != address(0), "TF14"); emit WrappedTokenDeployed(_token, wToken); // 2- Compliance Configuration if (_compliance) { // Avoid the approval step for non self managed users address[] memory operators = new address[](1); operators[0] = address(wToken); require(core.assignProxyOperators(address(_token), OPERATOR_PROXY_ROLE, operators), "TF15"); // Avoid KYC restrictions for the wrapped tokens (AuditConfigurationId == 0) { uint256 delegateId = core.proxyDelegateId(address(_token)); uint256 auditConfigurationId = core.delegatesConfigurations(delegateId)[0]; address[] memory senders = new address[](2); senders[0] = ANY_ADDRESSES; senders[1] = address(wToken); address[] memory receivers = new address[](2); receivers[0] = address(wToken); receivers[1] = ANY_ADDRESSES; ITokenStorage.AuditTriggerMode[] memory modes = new ITokenStorage.AuditTriggerMode[](2); modes[0] = ITokenStorage.AuditTriggerMode.NONE; modes[1] = ITokenStorage.AuditTriggerMode.RECEIVER_ONLY; require(core.defineAuditTriggers(auditConfigurationId, senders, receivers, modes), "TF16"); } require(core.defineLock(address(_token), address(this), ANY_ADDRESSES, ~uint64(0), ~uint64(0)), "TF17"); } else { require(_token.approve(address(wToken), ~uint256(0)), "TF18"); } // 3- Wrap tokens for(uint256 i=0; i < _vaults.length; i++) { require(wToken.depositTo(_vaults[i], _supplies[i]), "TF19"); } return wToken; } /** * @dev configureTokensales */ function configureTokensales( ITokenProxy _token, address[] memory _tokensales, uint256[] memory _allowances) override public onlyProxyOperator(Proxy(address(_token))) returns (bool) { ITokenCore core = ITokenCore(_token.core()); require(hasCoreAccess(core), "TF01"); require(_tokensales.length == _allowances.length, "TF20"); for(uint256 i=0; i < _tokensales.length; i++) { require(core.defineLock(address(_token), _tokensales[i], ANY_ADDRESSES, ~uint64(0), ~uint64(0)), "TF21"); } updateAllowances(_token, _tokensales, _allowances); emit TokensalesConfigured(_token, _tokensales); } /** * @dev updateAllowance */ function updateAllowances( ITokenProxy _token, address[] memory _spenders, uint256[] memory _allowances) override public onlyProxyOperator(_token) returns (bool) { uint256 balance = _token.balanceOf(address(this)); for(uint256 i=0; i < _spenders.length; i++) { require(_allowances[i] <= balance, "TF22"); require(_token.approve(_spenders[i], _allowances[i]), "TF23"); emit AllowanceUpdated(_token, _spenders[i], _allowances[i]); } } }
2,964
161
// We define offsets and size for the deserialization of ordered tuples in raw arrays
uint private constant amount_offset = 0; uint private constant start_offset = 1; uint private constant end_offset = 2; uint private constant price_offset = 3; uint private constant tranche_size = 4; Tranche[] public tranches;
uint private constant amount_offset = 0; uint private constant start_offset = 1; uint private constant end_offset = 2; uint private constant price_offset = 3; uint private constant tranche_size = 4; Tranche[] public tranches;
44,365
80
// GETTERS
function getClaimTopics() external view returns (uint256[] memory);
function getClaimTopics() external view returns (uint256[] memory);
33,650
20
// Emitted when protocol state is changed by admin
event ActionProtocolPaused(bool state);
event ActionProtocolPaused(bool state);
43,556
157
// Returns the claim price /
function getTokenPrice() external view returns (uint256) { return tokenPrice; }
function getTokenPrice() external view returns (uint256) { return tokenPrice; }
39,799
167
// SUBZERO tokens created per second.
uint256 public SUBZEROPerSec;
uint256 public SUBZEROPerSec;
6,215
1
// Mapping from id of a batch of tokens => to base URI for the respective batch of tokens.
mapping(uint256 => string) private baseURI;
mapping(uint256 => string) private baseURI;
31,009
33
// can check status before returning so thatresults are readable only after isActive is falseassert(!isActive);
bytes32 opt =getOptionById(optId); return ( opt, options[optId].score);
bytes32 opt =getOptionById(optId); return ( opt, options[optId].score);
8,468
95
// Modifiers /
modifier singletonLockCall() { require(!singletonLock, "Only can call once"); _; singletonLock = true; }
modifier singletonLockCall() { require(!singletonLock, "Only can call once"); _; singletonLock = true; }
13,562
6
// Set a new arbitrators list with (N-of-M multisig) descArbitrators list of all arbitrators from voting /
function setArbitrators( address[] calldata descArbitrators ) external onlyInternalRole(ROLE_ARBITRATOR_MANAGER)
function setArbitrators( address[] calldata descArbitrators ) external onlyInternalRole(ROLE_ARBITRATOR_MANAGER)
44,670
90
// revert if x is > MAX_POWER, where MAX_POWER = int(mp.floor(mp.log(mpf(2256 - 1) / ONE)ONE))
require(x <= 2454971259878909886679);
require(x <= 2454971259878909886679);
55,135
118
// Get current owner of the token. It is technically possible that the owner is the same address as the address to which the token is to be sent to. In this case the token will be moved to the end of the list of tokens owned by this address.
address _from = ownerByTokenId[_tokenId];
address _from = ownerByTokenId[_tokenId];
6,415
215
// Gets the virtual active balance of `yieldToken`.//The virtual active balance is the active balance minus any harvestable tokens which have yet to be realized.//yieldToken The address of the yield token to get the virtual active balance of.// return The virtual active balance.
function _calculateUnrealizedActiveBalance(address yieldToken) internal view returns (uint256) { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; uint256 activeBalance = yieldTokenParams.activeBalance; if (activeBalance == 0) { return activeBalance; } uint256 currentValue = _convertYieldTokensToUnderlying(yieldToken, activeBalance); uint256 expectedValue = yieldTokenParams.expectedValue; if (currentValue <= expectedValue) { return activeBalance; } uint256 harvestable = _convertUnderlyingTokensToYield(yieldToken, currentValue - expectedValue); if (harvestable == 0) { return activeBalance; } return activeBalance - harvestable; }
function _calculateUnrealizedActiveBalance(address yieldToken) internal view returns (uint256) { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; uint256 activeBalance = yieldTokenParams.activeBalance; if (activeBalance == 0) { return activeBalance; } uint256 currentValue = _convertYieldTokensToUnderlying(yieldToken, activeBalance); uint256 expectedValue = yieldTokenParams.expectedValue; if (currentValue <= expectedValue) { return activeBalance; } uint256 harvestable = _convertUnderlyingTokensToYield(yieldToken, currentValue - expectedValue); if (harvestable == 0) { return activeBalance; } return activeBalance - harvestable; }
69,044
22
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 internal constant ERC1271_VALIDSIGNATURE = 0x1626ba7e;
bytes4 internal constant ERC1271_VALIDSIGNATURE = 0x1626ba7e;
7,265
230
// Minimum Amount of destination synthetic tokens that user wants to receive (anti-slippage)
uint256 minDestNumTokens;
uint256 minDestNumTokens;
51,951
6
// bonus
if(bonusStatus){ if(user.deposits.length >= 2 && user.deposits.length <=5){ uint256 firstAmount = user.deposits[0].amount; if(firstAmount >= BONUS_MIN_AMOUNT && firstAmount <= BONUS_MAX_AMOUNT){ uint256 preAmount = user.deposits[user.deposits.length -2].amount; if(user.deposits.length == 2){ if(preAmount == msg.value){ userDepositBonus[msg.sender][user.deposits.length-1] = BONUS_PERCENTS[0]; }
if(bonusStatus){ if(user.deposits.length >= 2 && user.deposits.length <=5){ uint256 firstAmount = user.deposits[0].amount; if(firstAmount >= BONUS_MIN_AMOUNT && firstAmount <= BONUS_MAX_AMOUNT){ uint256 preAmount = user.deposits[user.deposits.length -2].amount; if(user.deposits.length == 2){ if(preAmount == msg.value){ userDepositBonus[msg.sender][user.deposits.length-1] = BONUS_PERCENTS[0]; }
8,317
80
// BaseStrategy The BaseStrategy is an abstract contract which allyAxis strategies should inherit functionality from. It givesspecific security properties which make it hard to write aninsecure strategy. All state-changing functions implemented in the strategyshould be internal, since any public or externally-facing functionsare already handled in the BaseStrategy. The following functions must be implemented by a strategy:- function _deposit() internal virtual;- function _harvest() internal virtual;- function _withdraw(uint256 _amount) internal virtual;- function _withdrawAll() internal virtual;- function balanceOfPool() public view override virtual returns (uint256); /
abstract contract BaseStrategy is IStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 public constant ONE_HUNDRED_PERCENT = 10000; address public immutable override want; address public immutable override weth; address public immutable controller; IManager public immutable override manager; string public override name; address[] public routerArray; ISwap public override router; /** * @param _controller The address of the controller * @param _manager The address of the manager * @param _want The desired token of the strategy * @param _weth The address of WETH * @param _routerArray The addresses of routers for swapping tokens */ constructor( string memory _name, address _controller, address _manager, address _want, address _weth, address[] memory _routerArray ) public { name = _name; want = _want; controller = _controller; manager = IManager(_manager); weth = _weth; require(_routerArray.length > 0, "Must input at least one router"); routerArray = _routerArray; router = ISwap(_routerArray[0]); for(uint i = 0; i < _routerArray.length; i++) { IERC20(_weth).safeApprove(address(_routerArray[i]), 0); IERC20(_weth).safeApprove(address(_routerArray[i]), type(uint256).max); } } /** * GOVERNANCE-ONLY FUNCTIONS */ /** * @notice Approves a token address to be spent by an address * @param _token The address of the token * @param _spender The address of the spender * @param _amount The amount to spend */ function approveForSpender( IERC20 _token, address _spender, uint256 _amount ) external { require(msg.sender == manager.governance(), "!governance"); _token.safeApprove(_spender, 0); _token.safeApprove(_spender, _amount); } /** * @notice Sets the address of the ISwap-compatible router * @param _routerArray The addresses of routers * @param _tokenArray The addresses of tokens that need to be approved by the strategy */ function setRouter( address[] calldata _routerArray, address[] calldata _tokenArray ) external { require(msg.sender == manager.governance(), "!governance"); routerArray = _routerArray; router = ISwap(_routerArray[0]); address _router; uint256 _routerLength = _routerArray.length; uint256 _tokenArrayLength = _tokenArray.length; for(uint i = 0; i < _routerLength; i++) { _router = _routerArray[i]; IERC20(weth).safeApprove(_router, 0); IERC20(weth).safeApprove(_router, type(uint256).max); for(uint j = 0; j < _tokenArrayLength; j++) { IERC20(_tokenArray[j]).safeApprove(_router, 0); IERC20(_tokenArray[j]).safeApprove(_router, type(uint256).max); } } } /** * @notice Sets the default ISwap-compatible router * @param _routerIndex Gets the address of the router from routerArray */ function setDefaultRouter( uint256 _routerIndex ) external { require(msg.sender == manager.governance(), "!governance"); router = ISwap(routerArray[_routerIndex]); } /** * CONTROLLER-ONLY FUNCTIONS */ /** * @notice Deposits funds to the strategy's pool */ function deposit() external override onlyController { _deposit(); } /** * @notice Harvest funds in the strategy's pool */ function harvest( uint256[] calldata _estimates ) external override onlyController { _harvest(_estimates); } /** * @notice Sends stuck want tokens in the strategy to the controller */ function skim() external override onlyController { IERC20(want).safeTransfer(controller, balanceOfWant()); } /** * @notice Sends stuck tokens in the strategy to the controller * @param _asset The address of the token to withdraw */ function withdraw( address _asset ) external override onlyController { require(want != _asset, "want"); IERC20 _assetToken = IERC20(_asset); uint256 _balance = _assetToken.balanceOf(address(this)); _assetToken.safeTransfer(controller, _balance); } /** * @notice Initiated from a vault, withdraws funds from the pool * @param _amount The amount of the want token to withdraw */ function withdraw( uint256 _amount ) external override onlyController { uint256 _balance = balanceOfWant(); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } IERC20(want).safeTransfer(controller, _amount); } /** * @notice Withdraws all funds from the strategy */ function withdrawAll() external override onlyController { _withdrawAll(); uint256 _balance = IERC20(want).balanceOf(address(this)); IERC20(want).safeTransfer(controller, _balance); } /** * EXTERNAL VIEW FUNCTIONS */ /** * @notice Returns the strategy's balance of the want token plus the balance of pool */ function balanceOf() external view override returns (uint256) { return balanceOfWant().add(balanceOfPool()); } /** * PUBLIC VIEW FUNCTIONS */ /** * @notice Returns the balance of the pool * @dev Must be implemented by the strategy */ function balanceOfPool() public view virtual override returns (uint256); /** * @notice Returns the balance of the want token on the strategy */ function balanceOfWant() public view override returns (uint256) { return IERC20(want).balanceOf(address(this)); } /** * INTERNAL FUNCTIONS */ function _deposit() internal virtual; function _harvest( uint256[] calldata _estimates ) internal virtual; function _payHarvestFees( address _poolToken, uint256 _estimatedWETH, uint256 _estimatedYAXIS, uint256 _routerIndex ) internal returns (uint256 _wethBal) { uint256 _amount = IERC20(_poolToken).balanceOf(address(this)); _swapTokens(_poolToken, weth, _amount, _estimatedWETH); _wethBal = IERC20(weth).balanceOf(address(this)); if (_wethBal > 0) { // get all the necessary variables in a single call ( address yaxis, address treasury, uint256 treasuryFee ) = manager.getHarvestFeeInfo(); uint256 _fee; // pay the treasury with YAX if (treasuryFee > 0 && treasury != address(0)) { _fee = _wethBal.mul(treasuryFee).div(ONE_HUNDRED_PERCENT); _swapTokensWithRouterIndex(weth, yaxis, _fee, _estimatedYAXIS, _routerIndex); IERC20(yaxis).safeTransfer(treasury, IERC20(yaxis).balanceOf(address(this))); } // return the remaining WETH balance _wethBal = IERC20(weth).balanceOf(address(this)); } } function _swapTokensWithRouterIndex( address _input, address _output, uint256 _amount, uint256 _expected, uint256 _routerIndex ) internal { address[] memory path = new address[](2); path[0] = _input; path[1] = _output; ISwap(routerArray[_routerIndex]).swapExactTokensForTokens( _amount, _expected, path, address(this), // The deadline is a hardcoded value that is far in the future. 1e10 ); } function _swapTokens( address _input, address _output, uint256 _amount, uint256 _expected ) internal { address[] memory path = new address[](2); path[0] = _input; path[1] = _output; router.swapExactTokensForTokens( _amount, _expected, path, address(this), // The deadline is a hardcoded value that is far in the future. 1e10 ); } function _withdraw( uint256 _amount ) internal virtual; function _withdrawAll() internal virtual; function _withdrawSome( uint256 _amount ) internal returns (uint256) { uint256 _before = IERC20(want).balanceOf(address(this)); _withdraw(_amount); uint256 _after = IERC20(want).balanceOf(address(this)); _amount = _after.sub(_before); return _amount; } /** * MODIFIERS */ modifier onlyStrategist() { require(msg.sender == manager.strategist(), "!strategist"); _; } modifier onlyController() { require(msg.sender == controller, "!controller"); _; } }
abstract contract BaseStrategy is IStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 public constant ONE_HUNDRED_PERCENT = 10000; address public immutable override want; address public immutable override weth; address public immutable controller; IManager public immutable override manager; string public override name; address[] public routerArray; ISwap public override router; /** * @param _controller The address of the controller * @param _manager The address of the manager * @param _want The desired token of the strategy * @param _weth The address of WETH * @param _routerArray The addresses of routers for swapping tokens */ constructor( string memory _name, address _controller, address _manager, address _want, address _weth, address[] memory _routerArray ) public { name = _name; want = _want; controller = _controller; manager = IManager(_manager); weth = _weth; require(_routerArray.length > 0, "Must input at least one router"); routerArray = _routerArray; router = ISwap(_routerArray[0]); for(uint i = 0; i < _routerArray.length; i++) { IERC20(_weth).safeApprove(address(_routerArray[i]), 0); IERC20(_weth).safeApprove(address(_routerArray[i]), type(uint256).max); } } /** * GOVERNANCE-ONLY FUNCTIONS */ /** * @notice Approves a token address to be spent by an address * @param _token The address of the token * @param _spender The address of the spender * @param _amount The amount to spend */ function approveForSpender( IERC20 _token, address _spender, uint256 _amount ) external { require(msg.sender == manager.governance(), "!governance"); _token.safeApprove(_spender, 0); _token.safeApprove(_spender, _amount); } /** * @notice Sets the address of the ISwap-compatible router * @param _routerArray The addresses of routers * @param _tokenArray The addresses of tokens that need to be approved by the strategy */ function setRouter( address[] calldata _routerArray, address[] calldata _tokenArray ) external { require(msg.sender == manager.governance(), "!governance"); routerArray = _routerArray; router = ISwap(_routerArray[0]); address _router; uint256 _routerLength = _routerArray.length; uint256 _tokenArrayLength = _tokenArray.length; for(uint i = 0; i < _routerLength; i++) { _router = _routerArray[i]; IERC20(weth).safeApprove(_router, 0); IERC20(weth).safeApprove(_router, type(uint256).max); for(uint j = 0; j < _tokenArrayLength; j++) { IERC20(_tokenArray[j]).safeApprove(_router, 0); IERC20(_tokenArray[j]).safeApprove(_router, type(uint256).max); } } } /** * @notice Sets the default ISwap-compatible router * @param _routerIndex Gets the address of the router from routerArray */ function setDefaultRouter( uint256 _routerIndex ) external { require(msg.sender == manager.governance(), "!governance"); router = ISwap(routerArray[_routerIndex]); } /** * CONTROLLER-ONLY FUNCTIONS */ /** * @notice Deposits funds to the strategy's pool */ function deposit() external override onlyController { _deposit(); } /** * @notice Harvest funds in the strategy's pool */ function harvest( uint256[] calldata _estimates ) external override onlyController { _harvest(_estimates); } /** * @notice Sends stuck want tokens in the strategy to the controller */ function skim() external override onlyController { IERC20(want).safeTransfer(controller, balanceOfWant()); } /** * @notice Sends stuck tokens in the strategy to the controller * @param _asset The address of the token to withdraw */ function withdraw( address _asset ) external override onlyController { require(want != _asset, "want"); IERC20 _assetToken = IERC20(_asset); uint256 _balance = _assetToken.balanceOf(address(this)); _assetToken.safeTransfer(controller, _balance); } /** * @notice Initiated from a vault, withdraws funds from the pool * @param _amount The amount of the want token to withdraw */ function withdraw( uint256 _amount ) external override onlyController { uint256 _balance = balanceOfWant(); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } IERC20(want).safeTransfer(controller, _amount); } /** * @notice Withdraws all funds from the strategy */ function withdrawAll() external override onlyController { _withdrawAll(); uint256 _balance = IERC20(want).balanceOf(address(this)); IERC20(want).safeTransfer(controller, _balance); } /** * EXTERNAL VIEW FUNCTIONS */ /** * @notice Returns the strategy's balance of the want token plus the balance of pool */ function balanceOf() external view override returns (uint256) { return balanceOfWant().add(balanceOfPool()); } /** * PUBLIC VIEW FUNCTIONS */ /** * @notice Returns the balance of the pool * @dev Must be implemented by the strategy */ function balanceOfPool() public view virtual override returns (uint256); /** * @notice Returns the balance of the want token on the strategy */ function balanceOfWant() public view override returns (uint256) { return IERC20(want).balanceOf(address(this)); } /** * INTERNAL FUNCTIONS */ function _deposit() internal virtual; function _harvest( uint256[] calldata _estimates ) internal virtual; function _payHarvestFees( address _poolToken, uint256 _estimatedWETH, uint256 _estimatedYAXIS, uint256 _routerIndex ) internal returns (uint256 _wethBal) { uint256 _amount = IERC20(_poolToken).balanceOf(address(this)); _swapTokens(_poolToken, weth, _amount, _estimatedWETH); _wethBal = IERC20(weth).balanceOf(address(this)); if (_wethBal > 0) { // get all the necessary variables in a single call ( address yaxis, address treasury, uint256 treasuryFee ) = manager.getHarvestFeeInfo(); uint256 _fee; // pay the treasury with YAX if (treasuryFee > 0 && treasury != address(0)) { _fee = _wethBal.mul(treasuryFee).div(ONE_HUNDRED_PERCENT); _swapTokensWithRouterIndex(weth, yaxis, _fee, _estimatedYAXIS, _routerIndex); IERC20(yaxis).safeTransfer(treasury, IERC20(yaxis).balanceOf(address(this))); } // return the remaining WETH balance _wethBal = IERC20(weth).balanceOf(address(this)); } } function _swapTokensWithRouterIndex( address _input, address _output, uint256 _amount, uint256 _expected, uint256 _routerIndex ) internal { address[] memory path = new address[](2); path[0] = _input; path[1] = _output; ISwap(routerArray[_routerIndex]).swapExactTokensForTokens( _amount, _expected, path, address(this), // The deadline is a hardcoded value that is far in the future. 1e10 ); } function _swapTokens( address _input, address _output, uint256 _amount, uint256 _expected ) internal { address[] memory path = new address[](2); path[0] = _input; path[1] = _output; router.swapExactTokensForTokens( _amount, _expected, path, address(this), // The deadline is a hardcoded value that is far in the future. 1e10 ); } function _withdraw( uint256 _amount ) internal virtual; function _withdrawAll() internal virtual; function _withdrawSome( uint256 _amount ) internal returns (uint256) { uint256 _before = IERC20(want).balanceOf(address(this)); _withdraw(_amount); uint256 _after = IERC20(want).balanceOf(address(this)); _amount = _after.sub(_before); return _amount; } /** * MODIFIERS */ modifier onlyStrategist() { require(msg.sender == manager.strategist(), "!strategist"); _; } modifier onlyController() { require(msg.sender == controller, "!controller"); _; } }
15,740
90
// view function / return rewardId => rewardEarned result[rewardId-1] represent `rewardId` reward
function claimable(address user) public view returns (uint[] memory){ uint[]memory result = new uint[](rewardsId); if (totalStaked == 0) { // if there are no staked token, the reward accrued at contract return result; } for (uint i = 1; i <= rewardsId; i++) { Reward memory reward = rewards[i]; if (reward.startBlock >= block.number) { // reward not start continue; } uint latestBlock = block.number < reward.endBlock ? block.number : reward.endBlock; uint blockDelta = latestBlock - reward.updateBlock; if (blockDelta == 0) { // reward ended continue; } uint rewardAccrued = blockDelta * reward.speed; UserState memory state = userStates[user][i]; if (state.index == 0 && reward.index >= MULTIPLIER) { state.index = MULTIPLIER; } uint indexDelta = reward.index - state.index + rewardAccrued * MULTIPLIER / totalStaked; uint earned = indexDelta * userStaked[user] / MULTIPLIER; result[i - 1] = state.accrued + earned; } return result; }
function claimable(address user) public view returns (uint[] memory){ uint[]memory result = new uint[](rewardsId); if (totalStaked == 0) { // if there are no staked token, the reward accrued at contract return result; } for (uint i = 1; i <= rewardsId; i++) { Reward memory reward = rewards[i]; if (reward.startBlock >= block.number) { // reward not start continue; } uint latestBlock = block.number < reward.endBlock ? block.number : reward.endBlock; uint blockDelta = latestBlock - reward.updateBlock; if (blockDelta == 0) { // reward ended continue; } uint rewardAccrued = blockDelta * reward.speed; UserState memory state = userStates[user][i]; if (state.index == 0 && reward.index >= MULTIPLIER) { state.index = MULTIPLIER; } uint indexDelta = reward.index - state.index + rewardAccrued * MULTIPLIER / totalStaked; uint earned = indexDelta * userStaked[user] / MULTIPLIER; result[i - 1] = state.accrued + earned; } return result; }
5,607
204
// burn an NFT._id the NFT id to burn. /
function burn(uint256 _id) public { _burn(_id); }
function burn(uint256 _id) public { _burn(_id); }
1,038
10
// for BNB-Chain x tern.crypto contest
contract rpsv1 is ReentrancyGuard{ mapping (address => uint) public playerBalances; event Received(address, uint); //give the contract something to bet with function fundContract() external payable { emit Received(msg.sender, msg.value); } //deposit a player's funds function deposit() external payable { playerBalances[msg.sender] += msg.value; } //withdraw a player's funds function withdraw() external nonReentrant { uint playerBalance = playerBalances[msg.sender]; require(playerBalance > 0); playerBalances[msg.sender] = 0; (bool success, ) = address(msg.sender).call{ value: playerBalance }(""); require(success, "withdraw failed to send"); } function getContractBalance() external view returns(uint contractBalance) { return address(this).balance; } function random() public view returns(uint){ return uint(keccak256(abi.encodePacked(block.timestamp,block.difficulty, msg.sender))) % 3; } function playGame(uint _playerOneChoice, uint _gameStake) external returns(uint gameOutcome) { require(playerBalances[msg.sender] >= _gameStake * (1 ether), "Not enough funds to place bet - please deposit more Ether."); uint _playerTwoChoice = random(); bytes memory b = bytes.concat(bytes(Strings.toString(_playerOneChoice)), bytes(Strings.toString(_playerTwoChoice))); uint rslt; if(keccak256(b) == keccak256(bytes("11")) || keccak256(b) == keccak256(bytes("22")) || keccak256(b) == keccak256(bytes("33"))) { //this is a draw rslt = 0; } else if(keccak256(b) == keccak256(bytes("32")) || keccak256(b) == keccak256(bytes("13")) || keccak256(b) == keccak256(bytes("21"))) { //player 1 wins playerBalances[msg.sender] += _gameStake * 2 * (1 ether); rslt = 1; } else if(keccak256(b) == keccak256(bytes("23")) || keccak256(b) == keccak256(bytes("31")) || keccak256(b) == keccak256(bytes("12"))) { //player 2 wins (the contract wins) playerBalances[msg.sender] -= _gameStake * (1 ether); rslt = 2; } else { //there was a problem with this game... rslt = 3; } return rslt; } }
contract rpsv1 is ReentrancyGuard{ mapping (address => uint) public playerBalances; event Received(address, uint); //give the contract something to bet with function fundContract() external payable { emit Received(msg.sender, msg.value); } //deposit a player's funds function deposit() external payable { playerBalances[msg.sender] += msg.value; } //withdraw a player's funds function withdraw() external nonReentrant { uint playerBalance = playerBalances[msg.sender]; require(playerBalance > 0); playerBalances[msg.sender] = 0; (bool success, ) = address(msg.sender).call{ value: playerBalance }(""); require(success, "withdraw failed to send"); } function getContractBalance() external view returns(uint contractBalance) { return address(this).balance; } function random() public view returns(uint){ return uint(keccak256(abi.encodePacked(block.timestamp,block.difficulty, msg.sender))) % 3; } function playGame(uint _playerOneChoice, uint _gameStake) external returns(uint gameOutcome) { require(playerBalances[msg.sender] >= _gameStake * (1 ether), "Not enough funds to place bet - please deposit more Ether."); uint _playerTwoChoice = random(); bytes memory b = bytes.concat(bytes(Strings.toString(_playerOneChoice)), bytes(Strings.toString(_playerTwoChoice))); uint rslt; if(keccak256(b) == keccak256(bytes("11")) || keccak256(b) == keccak256(bytes("22")) || keccak256(b) == keccak256(bytes("33"))) { //this is a draw rslt = 0; } else if(keccak256(b) == keccak256(bytes("32")) || keccak256(b) == keccak256(bytes("13")) || keccak256(b) == keccak256(bytes("21"))) { //player 1 wins playerBalances[msg.sender] += _gameStake * 2 * (1 ether); rslt = 1; } else if(keccak256(b) == keccak256(bytes("23")) || keccak256(b) == keccak256(bytes("31")) || keccak256(b) == keccak256(bytes("12"))) { //player 2 wins (the contract wins) playerBalances[msg.sender] -= _gameStake * (1 ether); rslt = 2; } else { //there was a problem with this game... rslt = 3; } return rslt; } }
7,301
147
// updates the interest rate model (requires fresh interest accrual) Admin function to update the interest rate model newInterestRateModel the new interest rate model to usereturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); }
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); }
7,432
12
// Transfers tokens from the sender's address to another address. _to The address to receive the tokens. _value The amount of tokens to transfer.return success True if the transfer is successful. /
function transfer(address _to, uint256 _value) external override returns (bool success) { _transfer(msg.sender, _to, _value); return true; }
function transfer(address _to, uint256 _value) external override returns (bool success) { _transfer(msg.sender, _to, _value); return true; }
7,758
21
// Elliptic Curve Digital Signature Algorithm (ECDSA) operations. These functions can be used to verify that a message was signed by the holderof the private keys of a given address. /
library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS } /** * @dev The signature derives the `address(0)`. */ error ECDSAInvalidSignature(); /** * @dev The signature has an invalid length. */ error ECDSAInvalidSignatureLength(uint256 length); /** * @dev The signature has an S value that is in the upper half order. */ error ECDSAInvalidSignatureS(bytes32 s); /** * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not * return address(0) without also returning an error description. Errors are documented using an enum (error type) * and a bytes32 providing additional information about the error. * * If no error is returned, then the address can be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length)); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) { unchecked { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); // We do not check for an overflow here since the shift operation results in 0 or 1. uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError, bytes32) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS, s); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature, bytes32(0)); } return (signer, RecoverError.NoError, bytes32(0)); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s); _throwError(error, errorArg); return recovered; } /** * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided. */ function _throwError(RecoverError error, bytes32 errorArg) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert ECDSAInvalidSignature(); } else if (error == RecoverError.InvalidSignatureLength) { revert ECDSAInvalidSignatureLength(uint256(errorArg)); } else if (error == RecoverError.InvalidSignatureS) { revert ECDSAInvalidSignatureS(errorArg); } } }
library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS } /** * @dev The signature derives the `address(0)`. */ error ECDSAInvalidSignature(); /** * @dev The signature has an invalid length. */ error ECDSAInvalidSignatureLength(uint256 length); /** * @dev The signature has an S value that is in the upper half order. */ error ECDSAInvalidSignatureS(bytes32 s); /** * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not * return address(0) without also returning an error description. Errors are documented using an enum (error type) * and a bytes32 providing additional information about the error. * * If no error is returned, then the address can be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length)); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) { unchecked { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); // We do not check for an overflow here since the shift operation results in 0 or 1. uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError, bytes32) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS, s); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature, bytes32(0)); } return (signer, RecoverError.NoError, bytes32(0)); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s); _throwError(error, errorArg); return recovered; } /** * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided. */ function _throwError(RecoverError error, bytes32 errorArg) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert ECDSAInvalidSignature(); } else if (error == RecoverError.InvalidSignatureLength) { revert ECDSAInvalidSignatureLength(uint256(errorArg)); } else if (error == RecoverError.InvalidSignatureS) { revert ECDSAInvalidSignatureS(errorArg); } } }
1,430
0
// Number of seconds for which time-weighted average should be calculated, ie. 1800 means 30 min
uint32 periodForAvgPrice;
uint32 periodForAvgPrice;
19,655
120
// Send Neuro Credits to the owner of the token ID
_mint(tokenOwner, NeuroCreditPerTokenId);
_mint(tokenOwner, NeuroCreditPerTokenId);
54,669
242
// Switch Flower images
function flowerSwitch(uint256 _from, uint256 _to) external { address switcher = ownerOf(_from); address switchee = ownerOf(_to); require(msg.sender == switcher); require(address(0) != switchee); require(LoveTokenAddress.balanceOf(switcher) > 0); require(LoveTokenAddress.balanceOf(switchee) > 0); uint256 tokento = flowerId[_to]; uint256 tokenfrom = flowerId[_from]; flowerId[_to] = tokenfrom; flowerId[_from] = tokento; expireCheck(); }
function flowerSwitch(uint256 _from, uint256 _to) external { address switcher = ownerOf(_from); address switchee = ownerOf(_to); require(msg.sender == switcher); require(address(0) != switchee); require(LoveTokenAddress.balanceOf(switcher) > 0); require(LoveTokenAddress.balanceOf(switchee) > 0); uint256 tokento = flowerId[_to]; uint256 tokenfrom = flowerId[_from]; flowerId[_to] = tokenfrom; flowerId[_from] = tokento; expireCheck(); }
23,759
35
// Updates price feed /
function updatePriceFeed(address priceFeed) external onlyOwner
function updatePriceFeed(address priceFeed) external onlyOwner
39,239
24
// Last block number when cumulative funding rate was recorded
uint256 private _cumuFundingRateBlock;
uint256 private _cumuFundingRateBlock;
76,141
62
// 4. Mint more LP tokens and return all LP tokens to the sender.
(,, uint256 moreLPAmount) = router.addLiquidityETH.value(address(this).balance)( fToken, fToken.myBalance(), 0, 0, address(this), now ); require(moreLPAmount >= minLPAmount, "insufficient LP tokens received"); lpToken.transfer(msg.sender, lpToken.balanceOf(address(this)));
(,, uint256 moreLPAmount) = router.addLiquidityETH.value(address(this).balance)( fToken, fToken.myBalance(), 0, 0, address(this), now ); require(moreLPAmount >= minLPAmount, "insufficient LP tokens received"); lpToken.transfer(msg.sender, lpToken.balanceOf(address(this)));
25,664
384
// The total funds that have been allocated to the reserve
uint256 public reserveTotalSupply;
uint256 public reserveTotalSupply;
36,099
8
// 4. add liquidity
uint[2] memory suppliedAmts; for (uint i = 0; i < 2; i++) { suppliedAmts[i] = IERC20(tokens[i]).balanceOf(address(this)); }
uint[2] memory suppliedAmts; for (uint i = 0; i < 2; i++) { suppliedAmts[i] = IERC20(tokens[i]).balanceOf(address(this)); }
25,799
5
// Calculates _valuepow(10, _shift)._value amount of tokens._shift decimal shift to apply. return shifted value./
function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) { if (_shift == 0) { return _value; } if (_shift > 0) { return _value.mul(10**uint256(_shift)); } return _value.div(10**uint256(-_shift)); }
function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) { if (_shift == 0) { return _value; } if (_shift > 0) { return _value.mul(10**uint256(_shift)); } return _value.div(10**uint256(-_shift)); }
10,432
85
// Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`./pid The index of the pool. See `poolInfo`./amount LP token amount to withdraw./to Receiver of the LP tokens and tokens rewards.
function withdrawAndHarvest( uint256 pid, uint256 amount, address to
function withdrawAndHarvest( uint256 pid, uint256 amount, address to
11,957
394
// Emitted when an account enters a market
event MarketEntered(PToken pToken, address account);
event MarketEntered(PToken pToken, address account);
47,963
44
// staking fee 2 %
uint public constant stakingFeeRate = 200;
uint public constant stakingFeeRate = 200;
16,069
0
// Eternal interface Nobody (me) Methods are used for all gage-related functioning /
interface IEternal { // Initiates a standard gage function initiateStandardGage(uint32 users) external returns(uint256); // Deposit an asset to the platform function deposit(address asset, address user, uint256 amount, uint256 id) external; // Withdraw an asset from the platform function withdraw(address user, uint256 id) external; // Set the fee rate of the platform function setFeeRate(uint16 newRate) external; event NewGage(uint256 id, address indexed gageAddress); event FeeRateChanged(uint16 oldRate, uint16 newRate); }
interface IEternal { // Initiates a standard gage function initiateStandardGage(uint32 users) external returns(uint256); // Deposit an asset to the platform function deposit(address asset, address user, uint256 amount, uint256 id) external; // Withdraw an asset from the platform function withdraw(address user, uint256 id) external; // Set the fee rate of the platform function setFeeRate(uint16 newRate) external; event NewGage(uint256 id, address indexed gageAddress); event FeeRateChanged(uint16 oldRate, uint16 newRate); }
14,978
87
// The initialization method that creates a new mintable token._name Token name _symbol Token symbol _decimals Token decimals /
function initializeMintableTokenFundraiser(string _name, string _symbol, uint8 _decimals) internal { token = new StandardMintableToken( address(this), // The fundraiser is the token minter _name, _symbol, _decimals ); }
function initializeMintableTokenFundraiser(string _name, string _symbol, uint8 _decimals) internal { token = new StandardMintableToken( address(this), // The fundraiser is the token minter _name, _symbol, _decimals ); }
48,188
125
// add liquidity
require(address(this).balance > 0, "Must have ETH on contract to launch"); liquidityAddress = payable(msg.sender); // send initial liquidity to owner to ensure project is functioning before burning / locking LP. addLiquidity(balanceOf(address(this)), address(this).balance);
require(address(this).balance > 0, "Must have ETH on contract to launch"); liquidityAddress = payable(msg.sender); // send initial liquidity to owner to ensure project is functioning before burning / locking LP. addLiquidity(balanceOf(address(this)), address(this).balance);
20,031
2
// abi decode may revert, but the encoding is done by L1 gateway, so we trust it
(gatewayData, callHookData) = abi.decode(_data, (bytes, bytes));
(gatewayData, callHookData) = abi.decode(_data, (bytes, bytes));
35,891
969
// no other changes to this contract
continue;
continue;
28,979
44
// ================================================================================== Data Model
function _incrementPoolBalances(uint _baseAmt, uint _tokenAmt) external onlyRouter { baseAmt += _baseAmt; tokenAmt += _tokenAmt; baseAmtStaked += _baseAmt; tokenAmtStaked += _tokenAmt; }
function _incrementPoolBalances(uint _baseAmt, uint _tokenAmt) external onlyRouter { baseAmt += _baseAmt; tokenAmt += _tokenAmt; baseAmtStaked += _baseAmt; tokenAmtStaked += _tokenAmt; }
24,140
150
// Function body
_;
_;
3,541
9
// Sender enters mToken market and borrows NFT assets from the protocol to their own address.borrowUnderlyingID The ID of the underlying NFT asset to borrow return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
function borrow(uint256 borrowUnderlyingID) external returns (uint) { borrowUnderlyingID; /* No NFT borrowing for now */ return fail(Error.MTROLLER_REJECTION, FailureInfo.BORROW_MTROLLER_REJECTION); }
function borrow(uint256 borrowUnderlyingID) external returns (uint) { borrowUnderlyingID; /* No NFT borrowing for now */ return fail(Error.MTROLLER_REJECTION, FailureInfo.BORROW_MTROLLER_REJECTION); }
41,473
90
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 );
VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 );
6,936
364
// Refunds any ETH balance held by this contract to the `msg.sender`/Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps/ that use ether for the input amount
function refundETH() internal { if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance); }
function refundETH() internal { if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance); }
5,366
12
// Open to every userAllows every address to certify documents in the contract/
function openToEveryUser() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("openToEveryUser()")); if (success) { emit DelegateCallEvent("openToEveryUser", success); } else { revert(); } }
function openToEveryUser() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("openToEveryUser()")); if (success) { emit DelegateCallEvent("openToEveryUser", success); } else { revert(); } }
38,095
42
// Crowdsale.
tmp[0] = address(this);
tmp[0] = address(this);
5,977
27
// If stake is lower, user is in this level, and we need to LERP with prev level to get discount value
if (i > 0) { amountPrevLevel = stakeLevels[i - 1].amount; discountPrevLevel = stakeLevels[i - 1].discount; } else {
if (i > 0) { amountPrevLevel = stakeLevels[i - 1].amount; discountPrevLevel = stakeLevels[i - 1].discount; } else {
27,995
9
// GDPOraclizedToken This is an interface for the GDP Oracle to control the mining rate.For security reasons, two distinct functions were created: setPositiveGrowth() and setNegativeGrowth() /
contract GDPOraclizedToken is MineableToken { event GDPOracleTransferred(address indexed previousOracle, address indexed newOracle); event BlockRewardChanged(int oldBlockReward, int newBlockReward); address GDPOracle_; address pendingGDPOracle_; /** * @dev Modifier Throws if called by any account other than the GDPOracle. */ modifier onlyGDPOracle() { require(msg.sender == GDPOracle_); _; } /** * @dev Modifier throws if called by any account other than the pendingGDPOracle. */ modifier onlyPendingGDPOracle() { require(msg.sender == pendingGDPOracle_); _; } /** * @dev Allows the current GDPOracle to transfer control to a newOracle. * The new GDPOracle need to call claimOracle() to finalize * @param newOracle The address to transfer ownership to. */ function transferGDPOracle(address newOracle) public onlyGDPOracle { pendingGDPOracle_ = newOracle; } /** * @dev Allows the pendingGDPOracle_ address to finalize the transfer. */ function claimOracle() onlyPendingGDPOracle public { emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_); GDPOracle_ = pendingGDPOracle_; pendingGDPOracle_ = address(0); } /** * @dev Chnage block reward according to GDP * @param newBlockReward the new block reward in case of possible growth */ function setPositiveGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) { // protect against error / overflow require(0 <= newBlockReward); emit BlockRewardChanged(blockReward_, newBlockReward); blockReward_ = newBlockReward; } /** * @dev Chnage block reward according to GDP * @param newBlockReward the new block reward in case of negative growth */ function setNegativeGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) { require(newBlockReward < 0); emit BlockRewardChanged(blockReward_, newBlockReward); blockReward_ = newBlockReward; } /** * @dev get GDPOracle * @return the address of the GDPOracle */ function GDPOracle() public view returns (address) { // solium-disable-line mixedcase return GDPOracle_; } /** * @dev get GDPOracle * @return the address of the GDPOracle */ function pendingGDPOracle() public view returns (address) { // solium-disable-line mixedcase return pendingGDPOracle_; } }
contract GDPOraclizedToken is MineableToken { event GDPOracleTransferred(address indexed previousOracle, address indexed newOracle); event BlockRewardChanged(int oldBlockReward, int newBlockReward); address GDPOracle_; address pendingGDPOracle_; /** * @dev Modifier Throws if called by any account other than the GDPOracle. */ modifier onlyGDPOracle() { require(msg.sender == GDPOracle_); _; } /** * @dev Modifier throws if called by any account other than the pendingGDPOracle. */ modifier onlyPendingGDPOracle() { require(msg.sender == pendingGDPOracle_); _; } /** * @dev Allows the current GDPOracle to transfer control to a newOracle. * The new GDPOracle need to call claimOracle() to finalize * @param newOracle The address to transfer ownership to. */ function transferGDPOracle(address newOracle) public onlyGDPOracle { pendingGDPOracle_ = newOracle; } /** * @dev Allows the pendingGDPOracle_ address to finalize the transfer. */ function claimOracle() onlyPendingGDPOracle public { emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_); GDPOracle_ = pendingGDPOracle_; pendingGDPOracle_ = address(0); } /** * @dev Chnage block reward according to GDP * @param newBlockReward the new block reward in case of possible growth */ function setPositiveGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) { // protect against error / overflow require(0 <= newBlockReward); emit BlockRewardChanged(blockReward_, newBlockReward); blockReward_ = newBlockReward; } /** * @dev Chnage block reward according to GDP * @param newBlockReward the new block reward in case of negative growth */ function setNegativeGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) { require(newBlockReward < 0); emit BlockRewardChanged(blockReward_, newBlockReward); blockReward_ = newBlockReward; } /** * @dev get GDPOracle * @return the address of the GDPOracle */ function GDPOracle() public view returns (address) { // solium-disable-line mixedcase return GDPOracle_; } /** * @dev get GDPOracle * @return the address of the GDPOracle */ function pendingGDPOracle() public view returns (address) { // solium-disable-line mixedcase return pendingGDPOracle_; } }
38,901
23
// Adds a new rebalancer. Only governance can add new rebalancers. /
function addRebalancer(address _rebalancer) external onlyGovernance { require(_rebalancer != address(0x0), "rebalancer not set"); require(!rebalancers[_rebalancer], "rebalancer exist"); rebalancers[_rebalancer] = true; emit RebalancerUpdated(_rebalancer, true); }
function addRebalancer(address _rebalancer) external onlyGovernance { require(_rebalancer != address(0x0), "rebalancer not set"); require(!rebalancers[_rebalancer], "rebalancer exist"); rebalancers[_rebalancer] = true; emit RebalancerUpdated(_rebalancer, true); }
71,201