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
37
// Allows the owner to change the name of the contract /
function changeName(bytes32 newName) onlyOwner() public { name = newName; }
function changeName(bytes32 newName) onlyOwner() public { name = newName; }
74,285
18
// Fire when the end of a rewards regime has been updated endTimestamp New end time for a pool rewardscurrencyId Reward currency - 1 = ETH, 2 = PRIME
event EndTimestampUpdated(uint256 endTimestamp, uint256 indexed currencyID);
event EndTimestampUpdated(uint256 endTimestamp, uint256 indexed currencyID);
21,135
1
// OtokenFactory key
bytes32 private constant OTOKEN_FACTORY = keccak256("OTOKEN_FACTORY");
bytes32 private constant OTOKEN_FACTORY = keccak256("OTOKEN_FACTORY");
27,542
116
// Adds new project `_projectName` by `_artistAddress`. _projectName Project name. _artistAddress Artist's address. token price now stored on minter /
function addProject( string memory _projectName, address payable _artistAddress
function addProject( string memory _projectName, address payable _artistAddress
13,063
233
// ... all the way to uint8(i_bytes[31])
string[5] memory part; string memory colorEye = string(abi.encodePacked(Strings.toString(attribute_a), ",", Strings.toString(attribute_b), ",", Strings.toString(attribute_c))); string memory colorBody = string(abi.encodePacked(Strings.toString(attribute_b), ",", Strings.toString(attribute_c), ",", Strings.toString(attribute_a))); string memory colorExtra = string(abi.encodePacked(Strings.toString(attribute_c), ",", Strings.toString(attribute_a), ",", Strings.toString(attribute_b)));
string[5] memory part; string memory colorEye = string(abi.encodePacked(Strings.toString(attribute_a), ",", Strings.toString(attribute_b), ",", Strings.toString(attribute_c))); string memory colorBody = string(abi.encodePacked(Strings.toString(attribute_b), ",", Strings.toString(attribute_c), ",", Strings.toString(attribute_a))); string memory colorExtra = string(abi.encodePacked(Strings.toString(attribute_c), ",", Strings.toString(attribute_a), ",", Strings.toString(attribute_b)));
14,758
15
// this means that we have an index variable called funderIndex and its going ot start from 0, this loop is going to finish whenever funder index is greater than or equal to the length of the funders and every time a loop is finished 1 will be added to the funder indexalso, and every time a peice of code in this for loop executes we're going to restart at the top
for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++){ address funder = funders[funderIndex]; addressToAmountFunded[funder]=0; }
for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++){ address funder = funders[funderIndex]; addressToAmountFunded[funder]=0; }
18,923
112
// Creates `amount` tokens of token type `id`, and assigns them to `account`. Should be callable only by MintableERC1155PredicateMake sure minting is done only by this function account user address for whom token is being minted id token which is being minted amount amount of token being minted data extra byte data to be accompanied with minted tokens /
function mint(address account, uint256 id, uint256 amount, bytes calldata data) external;
function mint(address account, uint256 id, uint256 amount, bytes calldata data) external;
16,523
54
// this is a guard that can be checked by resolution transactions as a Green signal
res.status = ResStatus.Executing; for(uint8 index=0; index < uint8(res.transaction_counter); index += 1) { require( this.call(res.transactions[index]) ); }
res.status = ResStatus.Executing; for(uint8 index=0; index < uint8(res.transaction_counter); index += 1) { require( this.call(res.transactions[index]) ); }
27,557
3
// Half-life of 12h. 12h = 720 min(1/2) = d^720 => d = (1/2)^(1/720) /
uint constant public MINUTE_DECAY_FACTOR = 999037758833783000; uint constant public REDEMPTION_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5% uint constant public MAX_BORROWING_FEE = DECIMAL_PRECISION / 100 * 5; // 5%
uint constant public MINUTE_DECAY_FACTOR = 999037758833783000; uint constant public REDEMPTION_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5% uint constant public MAX_BORROWING_FEE = DECIMAL_PRECISION / 100 * 5; // 5%
9,080
222
// The funding cycle structure represents a project stewarded by an address, and accounts for which addresses have helped sustain the project.
struct FundingCycle { // A unique number that's incremented for each new funding cycle, starting with 1. uint256 id; // The ID of the project contract that this funding cycle belongs to. uint256 projectId; // The number of this funding cycle for the project. uint256 number; // The ID of a previous funding cycle that this one is based on. uint256 basedOn; // The time when this funding cycle was last configured. uint256 configured; // The number of cycles that this configuration should last for before going back to the last permanent. uint256 cycleLimit; // A number determining the amount of redistribution shares this funding cycle will issue to each sustainer. uint256 weight; // The ballot contract to use to determine a subsequent funding cycle's reconfiguration status. IFundingCycleBallot ballot; // The time when this funding cycle will become active. uint256 start; // The number of seconds until this funding cycle's surplus is redistributed. uint256 duration; // The amount that this funding cycle is targeting in terms of the currency. uint256 target; // The currency that the target is measured in. uint256 currency; // The percentage of each payment to send as a fee to the Juicebox admin. uint256 fee; // A percentage indicating how much more weight to give a funding cycle compared to its predecessor. uint256 discountRate; // The amount of available funds that have been tapped by the project in terms of the currency. uint256 tapped; // A packed list of extra data. The first 8 bytes are reserved for versioning. uint256 metadata; }
struct FundingCycle { // A unique number that's incremented for each new funding cycle, starting with 1. uint256 id; // The ID of the project contract that this funding cycle belongs to. uint256 projectId; // The number of this funding cycle for the project. uint256 number; // The ID of a previous funding cycle that this one is based on. uint256 basedOn; // The time when this funding cycle was last configured. uint256 configured; // The number of cycles that this configuration should last for before going back to the last permanent. uint256 cycleLimit; // A number determining the amount of redistribution shares this funding cycle will issue to each sustainer. uint256 weight; // The ballot contract to use to determine a subsequent funding cycle's reconfiguration status. IFundingCycleBallot ballot; // The time when this funding cycle will become active. uint256 start; // The number of seconds until this funding cycle's surplus is redistributed. uint256 duration; // The amount that this funding cycle is targeting in terms of the currency. uint256 target; // The currency that the target is measured in. uint256 currency; // The percentage of each payment to send as a fee to the Juicebox admin. uint256 fee; // A percentage indicating how much more weight to give a funding cycle compared to its predecessor. uint256 discountRate; // The amount of available funds that have been tapped by the project in terms of the currency. uint256 tapped; // A packed list of extra data. The first 8 bytes are reserved for versioning. uint256 metadata; }
79,943
793
// Removes a LendingPoolAddressesProvider from the list of registered addresses provider provider The LendingPoolAddressesProvider address /
function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); }
function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); }
47,779
71
// Do not allow if gasprice is bigger than the maximum This is for fair-chance for all contributors, so no one can set a too-high transaction price and be able to buy earlier
require(tx.gasprice <= maxTxGas);
require(tx.gasprice <= maxTxGas);
42,814
4
// blind box token uri
string public blindBoxTokenURI;
string public blindBoxTokenURI;
40,432
46
// Returns whether or not there's a duplicate. Runs in O(n^2).A Array to search return Returns true if duplicate, false otherwise/
function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; }
function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; }
12,874
584
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
11,021
8
// returns the address of the staticAToken's lending pool / solhint-disable-next-line func-name-mixedcase
function LENDING_POOL() external view returns (ILendingPool);
function LENDING_POOL() external view returns (ILendingPool);
67,742
46
// allows token owner to list a token for lending. emits the Lending event. Requirements: ‼ contract should not be paused. ‼ caller must be the owner of the the token `tokenId + serialNo`. ‼ token with `tokenId + serialNo` must not be already listed for auction or fixed price. ‼ token with `tokenId + serialNo` must not be already listed for lending. ‼ token with `tokenId + serialNo` must be active. ‼ `lendingPeriod` must be multiple of day and must atleast 3 days. ‼ lending cannot be held before all tokens from contract are sold. ‼ token with `tokenId` must
function listForLending( uint256 tokenId, uint256 serialNo, uint32 lendingPeriod, uint104 amount
function listForLending( uint256 tokenId, uint256 serialNo, uint32 lendingPeriod, uint104 amount
9,744
179
// Function to change DHV staking pool in case of emergency./Caution! all actions for migration of the pool should be performed before this call./_stakingDHV Address of the DHV staking pool MasterChief./_pid DHV staking pool id.
function setStakingDHV(address _stakingDHV, uint256 _pid) external onlyRole(DEFAULT_ADMIN_ROLE) { stakingDHV = _stakingDHV; dhvPID = _pid; }
function setStakingDHV(address _stakingDHV, uint256 _pid) external onlyRole(DEFAULT_ADMIN_ROLE) { stakingDHV = _stakingDHV; dhvPID = _pid; }
34,574
62
// Function to set the protocol fee percentage.Only can be called by the pool factory. newFee Value of the new protocol fee. /
function setFee(uint256 newFee) external override { onlyFactory(); _setFee(newFee); }
function setFee(uint256 newFee) external override { onlyFactory(); _setFee(newFee); }
31,359
24
// Unwraps the contract's WETH9 balance and sends it to recipient as ETH./The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users./amountMinimum The minimum amount of WETH9 to unwrap/recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable
16,288
2
// INTERFACES /
IHomeFi public homeFi; IEvents public eventsInstance;
IHomeFi public homeFi; IEvents public eventsInstance;
29,563
0
// Event to log the main NFT token IDs used for a burn
event MainNFTUsedForBurn(address indexed user, uint256 indexed mainNFTId); event BurnWithoutMainNFT(address indexed user); constructor( address _defaultAdmin, string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps, address _mainNFT,
event MainNFTUsedForBurn(address indexed user, uint256 indexed mainNFTId); event BurnWithoutMainNFT(address indexed user); constructor( address _defaultAdmin, string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps, address _mainNFT,
4,482
141
// Abstract base contract for token sales. Handle- start and end dates- accepting investments- minimum funding goal and refund- various statistics during the crowdfund- different pricing strategies- different investment policies (require server side customer id, allow only whitelisted addresses)/
contract CrowdsaleExt is Allocatable, Haltable { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; using SafeMathLibExt for uint; /* The token we are selling */ FractionalERC20Ext public token; /* How we are going to price our offering */ PricingStrategy public pricingStrategy; /* Post-success callback */ FinalizeAgent public finalizeAgent; TokenVesting public tokenVesting; /* name of the crowdsale tier */ string public name; /* tokens will be transfered from this address */ address public multisigWallet; /* if the funding goal is not reached, investors may withdraw their funds */ uint public minimumFundingGoal; /* the UNIX timestamp start date of the crowdsale */ uint public startsAt; /* the UNIX timestamp end date of the crowdsale */ uint public endsAt; /* the number of tokens already sold through this contract*/ uint public tokensSold = 0; /* How many wei of funding we have raised */ uint public weiRaised = 0; /* How many distinct addresses have invested */ uint public investorCount = 0; /* Has this crowdsale been finalized */ bool public finalized; bool public isWhiteListed; /* Token Vesting Contract */ address public tokenVestingAddress; address[] public joinedCrowdsales; uint8 public joinedCrowdsalesLen = 0; uint8 public joinedCrowdsalesLenMax = 50; struct JoinedCrowdsaleStatus { bool isJoined; uint8 position; } mapping (address => JoinedCrowdsaleStatus) public joinedCrowdsaleState; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) public investedAmountOf; /** How much tokens this crowdsale has credited for each investor address */ mapping (address => uint256) public tokenAmountOf; struct WhiteListData { bool status; uint minCap; uint maxCap; } //is crowdsale updatable bool public isUpdatable; /** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */ mapping (address => WhiteListData) public earlyParticipantWhitelist; /** List of whitelisted addresses */ address[] public whitelistedParticipants; /** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */ uint public ownerTestValue; /** State machine * * - Preparing: All contract initialization calls and variables have not been set yet * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Success: Minimum funding goal reached * - Failure: Minimum funding goal not reached before ending time * - Finalized: The finalized has been called and succesfully executed */ enum State { Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized } // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); // Address early participation whitelist status changed event Whitelisted(address addr, bool status, uint minCap, uint maxCap); event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); // Crowdsale start time has been changed event StartsAtChanged(uint newStartsAt); // Crowdsale end time has been changed event EndsAtChanged(uint newEndsAt); constructor(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed, address _tokenVestingAddress) public { owner = msg.sender; name = _name; tokenVestingAddress = _tokenVestingAddress; token = FractionalERC20Ext(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if (multisigWallet == 0) { revert(); } if (_start == 0) { revert(); } startsAt = _start; if (_end == 0) { revert(); } endsAt = _end; // Don't mess the dates if (startsAt >= endsAt) { revert(); } // Minimum funding goal can be zero minimumFundingGoal = _minimumFundingGoal; isUpdatable = _isUpdatable; isWhiteListed = _isWhiteListed; } /** * Don't expect to just send in money and get tokens. */ function() external payable { buy(); } /** * The basic entry point to participate the crowdsale process. * * Pay for funding, get invested tokens back in the sender address. */ function buy() public payable { invest(msg.sender); } /** * Allow anonymous contributions to this crowdsale. */ function invest(address addr) public payable { investInternal(addr, 0); } /** * Make an investment. * * Crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * @param customerId (optional) UUID v4 to track the successful payments on the server side * */ function investInternal(address receiver, uint128 customerId) private stopInEmergency { // Determine if it's a good time to accept investment from this participant if (getState() == State.PreFunding) { // Are we whitelisted for early deposit revert(); } else if (getState() == State.Funding) { // Retail participants can only come in when the crowdsale is running // pass if (isWhiteListed) { if (!earlyParticipantWhitelist[receiver].status) { revert(); } } } else { // Unwanted state revert(); } uint weiAmount = msg.value; // Account presale sales separately, so that they do not count against pricing tranches uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, tokensSold, token.decimals()); if (tokenAmount == 0) { // Dust transaction revert(); } if (isWhiteListed) { if (weiAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { // weiAmount < minCap for investor revert(); } // Check that we did not bust the investor's cap if (isBreakingInvestorCap(receiver, weiAmount)) { revert(); } updateInheritedEarlyParticipantWhitelist(receiver, weiAmount); } else { if (weiAmount < token.minCap() && tokenAmountOf[receiver] == 0) { revert(); } } if (investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); // Update totals weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); // Check that we did not bust the cap if (isBreakingCap(tokensSold)) { revert(); } assignTokens(receiver, tokenAmount); // Pocket the money if (!multisigWallet.send(weiAmount)) revert(); // Tell us invest was success emit Invested(receiver, weiAmount, tokenAmount, customerId); } /** * allocate tokens for the early investors. * * Preallocated tokens have been sold before the actual crowdsale opens. * This function mints the tokens and moves the crowdsale needle. * * Investor count is not handled; it is assumed this goes for multiple investors * and the token distribution happens outside the smart contract flow. * * No money is exchanged, as the crowdsale team already have received the payment. * * param weiPrice Price of a single full token in wei * */ function allocate(address receiver, uint256 tokenAmount, uint128 customerId, uint256 lockedTokenAmount) public onlyAllocateAgent { // cannot lock more than total tokens require(lockedTokenAmount <= tokenAmount); uint weiPrice = pricingStrategy.oneTokenInWei(tokensSold, token.decimals()); // This can be also 0, we give out tokens for free uint256 weiAmount = (weiPrice * tokenAmount)/10**uint256(token.decimals()); weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); // assign locked token to Vesting contract if (lockedTokenAmount > 0) { tokenVesting = TokenVesting(tokenVestingAddress); // to prevent minting of tokens which will be useless as vesting amount cannot be updated require(!tokenVesting.isVestingSet(receiver)); assignTokens(tokenVestingAddress, lockedTokenAmount); // set vesting with default schedule tokenVesting.setVestingWithDefaultSchedule(receiver, lockedTokenAmount); } // assign remaining tokens to contributor if (tokenAmount - lockedTokenAmount > 0) { assignTokens(receiver, tokenAmount - lockedTokenAmount); } // Tell us invest was success emit Invested(receiver, weiAmount, tokenAmount, customerId); } // // Modifiers // /** Modified allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { if (getState() != state) revert(); _; } function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if (finalized) { revert(); } // Finalizing is optional. We only call it if we are given a finalizing agent. if (address(finalizeAgent) != address(0)) { finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); } } function areReservedTokensDistributed() public view returns (bool) { return finalizeAgent.reservedTokensAreDistributed(); } function canDistributeReservedTokens() public view returns(bool) { CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; return false; } /** * Finalize a succcesful crowdsale. * * The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if (finalized) { revert(); } // Finalizing is optional. We only call it if we are given a finalizing agent. if (address(finalizeAgent) != address(0)) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } /** * Allow to (re)set finalize agent. * * Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes. */ function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { assert(address(addr) != address(0)); assert(address(finalizeAgent) == address(0)); finalizeAgent = addr; // Don't allow setting bad agent if (!finalizeAgent.isFinalizeAgent()) { revert(); } } /** * Allow addresses to do early participation. */ function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { if (!isWhiteListed) revert(); assert(addr != address(0)); assert(maxCap > 0); assert(minCap <= maxCap); assert(now <= endsAt); if (!isAddressWhitelisted(addr)) { whitelistedParticipants.push(addr); emit Whitelisted(addr, status, minCap, maxCap); } else { emit WhitelistItemChanged(addr, status, minCap, maxCap); } earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); } function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { if (!isWhiteListed) revert(); assert(now <= endsAt); assert(addrs.length == statuses.length); assert(statuses.length == minCaps.length); assert(minCaps.length == maxCaps.length); for (uint iterator = 0; iterator < addrs.length; iterator++) { setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); } } function updateEarlyParticipantWhitelist(address addr, uint weiAmount) public { if (!isWhiteListed) revert(); assert(addr != address(0)); assert(now <= endsAt); assert(isTierJoined(msg.sender)); if (weiAmount < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) revert(); //if (addr != msg.sender && contractAddr != msg.sender) throw; uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; newMaxCap = newMaxCap.minus(weiAmount); earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); } function updateInheritedEarlyParticipantWhitelist(address reciever, uint weiAmount) private { if (!isWhiteListed) revert(); if (weiAmount < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) revert(); uint8 tierPosition = getTierPosition(this); for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); crowdsale.updateEarlyParticipantWhitelist(reciever, weiAmount); } } function isAddressWhitelisted(address addr) public view returns(bool) { for (uint i = 0; i < whitelistedParticipants.length; i++) { if (whitelistedParticipants[i] == addr) { return true; break; } } return false; } function whitelistedParticipantsLength() public view returns (uint) { return whitelistedParticipants.length; } function isTierJoined(address addr) public view returns(bool) { return joinedCrowdsaleState[addr].isJoined; } function getTierPosition(address addr) public view returns(uint8) { return joinedCrowdsaleState[addr].position; } function getLastTier() public view returns(address) { if (joinedCrowdsalesLen > 0) return joinedCrowdsales[joinedCrowdsalesLen - 1]; else return address(0); } function setJoinedCrowdsales(address addr) private onlyOwner { assert(addr != address(0)); assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); assert(!isTierJoined(addr)); joinedCrowdsales.push(addr); joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ isJoined: true, position: joinedCrowdsalesLen }); joinedCrowdsalesLen++; } function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { assert(addrs.length > 0); assert(joinedCrowdsalesLen == 0); assert(addrs.length <= joinedCrowdsalesLenMax); for (uint8 iter = 0; iter < addrs.length; iter++) { setJoinedCrowdsales(addrs[iter]); } } function setStartsAt(uint time) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= time); // Don't change past assert(time <= endsAt); assert(now <= startsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if (lastTierCntrct.finalized()) revert(); uint8 tierPosition = getTierPosition(this); //start time should be greater then end time of previous tiers for (uint8 j = 0; j < tierPosition; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); assert(time >= crowdsale.endsAt()); } startsAt = time; emit StartsAtChanged(startsAt); } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setEndsAt(uint time) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= time);// Don't change past assert(startsAt <= time); assert(now <= endsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if (lastTierCntrct.finalized()) revert(); uint8 tierPosition = getTierPosition(this); for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); assert(time <= crowdsale.startsAt()); } endsAt = time; emit EndsAtChanged(endsAt); } /** * Allow to (re)set pricing strategy. * * Design choice: no state restrictions on the set, so that we can fix fat finger mistakes. */ function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { assert(address(_pricingStrategy) != address(0)); assert(address(pricingStrategy) == address(0)); pricingStrategy = _pricingStrategy; // Don't allow setting bad agent if (!pricingStrategy.isPricingStrategy()) { revert(); } } /** * Allow to (re)set Token. * @param _token upgraded token address */ function setCrowdsaleTokenExtv1(address _token) public onlyOwner { assert(_token != address(0)); token = FractionalERC20Ext(_token); if (address(finalizeAgent) != address(0)) { finalizeAgent.setCrowdsaleTokenExtv1(_token); } } /** * Allow to change the team multisig address in the case of emergency. * * This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun * (we have done only few test transactions). After the crowdsale is going * then multisig address stays locked for the safety reasons. */ function setMultisig(address addr) public onlyOwner { // Change if (investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { revert(); } multisigWallet = addr; } /** * @return true if the crowdsale has raised enough money to be a successful. */ function isMinimumGoalReached() public view returns (bool reached) { return weiRaised >= minimumFundingGoal; } /** * Check if the contract relationship looks good. */ function isFinalizerSane() public view returns (bool sane) { return finalizeAgent.isSane(); } /** * Check if the contract relationship looks good. */ function isPricingSane() public view returns (bool sane) { return pricingStrategy.isSane(); } /** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, * so there is no chance of the variable being stale. */ function getState() public view returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane()) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else return State.Failure; } /** Interface marker. */ function isCrowdsale() public pure returns (bool) { return true; } // // Abstract functions // /** * Check if the current invested breaks our cap rules. * * * The child contract must define their own cap setting rules. * We allow a lot of flexibility through different capping strategies (ETH, token count) * Called from invest(). * * @param tokensSoldTotal What would be our total sold tokens count after this transaction * * @return true if taking this investment would break our cap rules */ function isBreakingCap(uint tokensSoldTotal) public view returns (bool limitBroken); function isBreakingInvestorCap(address receiver, uint tokenAmount) public view returns (bool limitBroken); /** * Check if the current crowdsale is full and we can no longer sell any tokens. */ function isCrowdsaleFull() public view returns (bool); /** * Create new tokens or transfer issued tokens to the investor depending on the cap model. */ function assignTokens(address receiver, uint tokenAmount) private; }
contract CrowdsaleExt is Allocatable, Haltable { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; using SafeMathLibExt for uint; /* The token we are selling */ FractionalERC20Ext public token; /* How we are going to price our offering */ PricingStrategy public pricingStrategy; /* Post-success callback */ FinalizeAgent public finalizeAgent; TokenVesting public tokenVesting; /* name of the crowdsale tier */ string public name; /* tokens will be transfered from this address */ address public multisigWallet; /* if the funding goal is not reached, investors may withdraw their funds */ uint public minimumFundingGoal; /* the UNIX timestamp start date of the crowdsale */ uint public startsAt; /* the UNIX timestamp end date of the crowdsale */ uint public endsAt; /* the number of tokens already sold through this contract*/ uint public tokensSold = 0; /* How many wei of funding we have raised */ uint public weiRaised = 0; /* How many distinct addresses have invested */ uint public investorCount = 0; /* Has this crowdsale been finalized */ bool public finalized; bool public isWhiteListed; /* Token Vesting Contract */ address public tokenVestingAddress; address[] public joinedCrowdsales; uint8 public joinedCrowdsalesLen = 0; uint8 public joinedCrowdsalesLenMax = 50; struct JoinedCrowdsaleStatus { bool isJoined; uint8 position; } mapping (address => JoinedCrowdsaleStatus) public joinedCrowdsaleState; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) public investedAmountOf; /** How much tokens this crowdsale has credited for each investor address */ mapping (address => uint256) public tokenAmountOf; struct WhiteListData { bool status; uint minCap; uint maxCap; } //is crowdsale updatable bool public isUpdatable; /** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */ mapping (address => WhiteListData) public earlyParticipantWhitelist; /** List of whitelisted addresses */ address[] public whitelistedParticipants; /** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */ uint public ownerTestValue; /** State machine * * - Preparing: All contract initialization calls and variables have not been set yet * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Success: Minimum funding goal reached * - Failure: Minimum funding goal not reached before ending time * - Finalized: The finalized has been called and succesfully executed */ enum State { Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized } // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); // Address early participation whitelist status changed event Whitelisted(address addr, bool status, uint minCap, uint maxCap); event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); // Crowdsale start time has been changed event StartsAtChanged(uint newStartsAt); // Crowdsale end time has been changed event EndsAtChanged(uint newEndsAt); constructor(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed, address _tokenVestingAddress) public { owner = msg.sender; name = _name; tokenVestingAddress = _tokenVestingAddress; token = FractionalERC20Ext(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if (multisigWallet == 0) { revert(); } if (_start == 0) { revert(); } startsAt = _start; if (_end == 0) { revert(); } endsAt = _end; // Don't mess the dates if (startsAt >= endsAt) { revert(); } // Minimum funding goal can be zero minimumFundingGoal = _minimumFundingGoal; isUpdatable = _isUpdatable; isWhiteListed = _isWhiteListed; } /** * Don't expect to just send in money and get tokens. */ function() external payable { buy(); } /** * The basic entry point to participate the crowdsale process. * * Pay for funding, get invested tokens back in the sender address. */ function buy() public payable { invest(msg.sender); } /** * Allow anonymous contributions to this crowdsale. */ function invest(address addr) public payable { investInternal(addr, 0); } /** * Make an investment. * * Crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * @param customerId (optional) UUID v4 to track the successful payments on the server side * */ function investInternal(address receiver, uint128 customerId) private stopInEmergency { // Determine if it's a good time to accept investment from this participant if (getState() == State.PreFunding) { // Are we whitelisted for early deposit revert(); } else if (getState() == State.Funding) { // Retail participants can only come in when the crowdsale is running // pass if (isWhiteListed) { if (!earlyParticipantWhitelist[receiver].status) { revert(); } } } else { // Unwanted state revert(); } uint weiAmount = msg.value; // Account presale sales separately, so that they do not count against pricing tranches uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, tokensSold, token.decimals()); if (tokenAmount == 0) { // Dust transaction revert(); } if (isWhiteListed) { if (weiAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { // weiAmount < minCap for investor revert(); } // Check that we did not bust the investor's cap if (isBreakingInvestorCap(receiver, weiAmount)) { revert(); } updateInheritedEarlyParticipantWhitelist(receiver, weiAmount); } else { if (weiAmount < token.minCap() && tokenAmountOf[receiver] == 0) { revert(); } } if (investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); // Update totals weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); // Check that we did not bust the cap if (isBreakingCap(tokensSold)) { revert(); } assignTokens(receiver, tokenAmount); // Pocket the money if (!multisigWallet.send(weiAmount)) revert(); // Tell us invest was success emit Invested(receiver, weiAmount, tokenAmount, customerId); } /** * allocate tokens for the early investors. * * Preallocated tokens have been sold before the actual crowdsale opens. * This function mints the tokens and moves the crowdsale needle. * * Investor count is not handled; it is assumed this goes for multiple investors * and the token distribution happens outside the smart contract flow. * * No money is exchanged, as the crowdsale team already have received the payment. * * param weiPrice Price of a single full token in wei * */ function allocate(address receiver, uint256 tokenAmount, uint128 customerId, uint256 lockedTokenAmount) public onlyAllocateAgent { // cannot lock more than total tokens require(lockedTokenAmount <= tokenAmount); uint weiPrice = pricingStrategy.oneTokenInWei(tokensSold, token.decimals()); // This can be also 0, we give out tokens for free uint256 weiAmount = (weiPrice * tokenAmount)/10**uint256(token.decimals()); weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); // assign locked token to Vesting contract if (lockedTokenAmount > 0) { tokenVesting = TokenVesting(tokenVestingAddress); // to prevent minting of tokens which will be useless as vesting amount cannot be updated require(!tokenVesting.isVestingSet(receiver)); assignTokens(tokenVestingAddress, lockedTokenAmount); // set vesting with default schedule tokenVesting.setVestingWithDefaultSchedule(receiver, lockedTokenAmount); } // assign remaining tokens to contributor if (tokenAmount - lockedTokenAmount > 0) { assignTokens(receiver, tokenAmount - lockedTokenAmount); } // Tell us invest was success emit Invested(receiver, weiAmount, tokenAmount, customerId); } // // Modifiers // /** Modified allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { if (getState() != state) revert(); _; } function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if (finalized) { revert(); } // Finalizing is optional. We only call it if we are given a finalizing agent. if (address(finalizeAgent) != address(0)) { finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); } } function areReservedTokensDistributed() public view returns (bool) { return finalizeAgent.reservedTokensAreDistributed(); } function canDistributeReservedTokens() public view returns(bool) { CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; return false; } /** * Finalize a succcesful crowdsale. * * The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if (finalized) { revert(); } // Finalizing is optional. We only call it if we are given a finalizing agent. if (address(finalizeAgent) != address(0)) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } /** * Allow to (re)set finalize agent. * * Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes. */ function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { assert(address(addr) != address(0)); assert(address(finalizeAgent) == address(0)); finalizeAgent = addr; // Don't allow setting bad agent if (!finalizeAgent.isFinalizeAgent()) { revert(); } } /** * Allow addresses to do early participation. */ function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { if (!isWhiteListed) revert(); assert(addr != address(0)); assert(maxCap > 0); assert(minCap <= maxCap); assert(now <= endsAt); if (!isAddressWhitelisted(addr)) { whitelistedParticipants.push(addr); emit Whitelisted(addr, status, minCap, maxCap); } else { emit WhitelistItemChanged(addr, status, minCap, maxCap); } earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); } function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { if (!isWhiteListed) revert(); assert(now <= endsAt); assert(addrs.length == statuses.length); assert(statuses.length == minCaps.length); assert(minCaps.length == maxCaps.length); for (uint iterator = 0; iterator < addrs.length; iterator++) { setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); } } function updateEarlyParticipantWhitelist(address addr, uint weiAmount) public { if (!isWhiteListed) revert(); assert(addr != address(0)); assert(now <= endsAt); assert(isTierJoined(msg.sender)); if (weiAmount < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) revert(); //if (addr != msg.sender && contractAddr != msg.sender) throw; uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; newMaxCap = newMaxCap.minus(weiAmount); earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); } function updateInheritedEarlyParticipantWhitelist(address reciever, uint weiAmount) private { if (!isWhiteListed) revert(); if (weiAmount < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) revert(); uint8 tierPosition = getTierPosition(this); for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); crowdsale.updateEarlyParticipantWhitelist(reciever, weiAmount); } } function isAddressWhitelisted(address addr) public view returns(bool) { for (uint i = 0; i < whitelistedParticipants.length; i++) { if (whitelistedParticipants[i] == addr) { return true; break; } } return false; } function whitelistedParticipantsLength() public view returns (uint) { return whitelistedParticipants.length; } function isTierJoined(address addr) public view returns(bool) { return joinedCrowdsaleState[addr].isJoined; } function getTierPosition(address addr) public view returns(uint8) { return joinedCrowdsaleState[addr].position; } function getLastTier() public view returns(address) { if (joinedCrowdsalesLen > 0) return joinedCrowdsales[joinedCrowdsalesLen - 1]; else return address(0); } function setJoinedCrowdsales(address addr) private onlyOwner { assert(addr != address(0)); assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); assert(!isTierJoined(addr)); joinedCrowdsales.push(addr); joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ isJoined: true, position: joinedCrowdsalesLen }); joinedCrowdsalesLen++; } function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { assert(addrs.length > 0); assert(joinedCrowdsalesLen == 0); assert(addrs.length <= joinedCrowdsalesLenMax); for (uint8 iter = 0; iter < addrs.length; iter++) { setJoinedCrowdsales(addrs[iter]); } } function setStartsAt(uint time) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= time); // Don't change past assert(time <= endsAt); assert(now <= startsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if (lastTierCntrct.finalized()) revert(); uint8 tierPosition = getTierPosition(this); //start time should be greater then end time of previous tiers for (uint8 j = 0; j < tierPosition; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); assert(time >= crowdsale.endsAt()); } startsAt = time; emit StartsAtChanged(startsAt); } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setEndsAt(uint time) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= time);// Don't change past assert(startsAt <= time); assert(now <= endsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if (lastTierCntrct.finalized()) revert(); uint8 tierPosition = getTierPosition(this); for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); assert(time <= crowdsale.startsAt()); } endsAt = time; emit EndsAtChanged(endsAt); } /** * Allow to (re)set pricing strategy. * * Design choice: no state restrictions on the set, so that we can fix fat finger mistakes. */ function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { assert(address(_pricingStrategy) != address(0)); assert(address(pricingStrategy) == address(0)); pricingStrategy = _pricingStrategy; // Don't allow setting bad agent if (!pricingStrategy.isPricingStrategy()) { revert(); } } /** * Allow to (re)set Token. * @param _token upgraded token address */ function setCrowdsaleTokenExtv1(address _token) public onlyOwner { assert(_token != address(0)); token = FractionalERC20Ext(_token); if (address(finalizeAgent) != address(0)) { finalizeAgent.setCrowdsaleTokenExtv1(_token); } } /** * Allow to change the team multisig address in the case of emergency. * * This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun * (we have done only few test transactions). After the crowdsale is going * then multisig address stays locked for the safety reasons. */ function setMultisig(address addr) public onlyOwner { // Change if (investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { revert(); } multisigWallet = addr; } /** * @return true if the crowdsale has raised enough money to be a successful. */ function isMinimumGoalReached() public view returns (bool reached) { return weiRaised >= minimumFundingGoal; } /** * Check if the contract relationship looks good. */ function isFinalizerSane() public view returns (bool sane) { return finalizeAgent.isSane(); } /** * Check if the contract relationship looks good. */ function isPricingSane() public view returns (bool sane) { return pricingStrategy.isSane(); } /** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, * so there is no chance of the variable being stale. */ function getState() public view returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane()) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else return State.Failure; } /** Interface marker. */ function isCrowdsale() public pure returns (bool) { return true; } // // Abstract functions // /** * Check if the current invested breaks our cap rules. * * * The child contract must define their own cap setting rules. * We allow a lot of flexibility through different capping strategies (ETH, token count) * Called from invest(). * * @param tokensSoldTotal What would be our total sold tokens count after this transaction * * @return true if taking this investment would break our cap rules */ function isBreakingCap(uint tokensSoldTotal) public view returns (bool limitBroken); function isBreakingInvestorCap(address receiver, uint tokenAmount) public view returns (bool limitBroken); /** * Check if the current crowdsale is full and we can no longer sell any tokens. */ function isCrowdsaleFull() public view returns (bool); /** * Create new tokens or transfer issued tokens to the investor depending on the cap model. */ function assignTokens(address receiver, uint tokenAmount) private; }
36,480
74
// Refund ether to the investors (invoke from only token)
function refund(address _to) public refundAllowed { require(msg.sender == tokenContractAddress); uint256 valueToReturn = balances[_to]; // update states balances[_to] = 0; weiRaised = weiRaised.sub(valueToReturn); _to.transfer(valueToReturn); }
function refund(address _to) public refundAllowed { require(msg.sender == tokenContractAddress); uint256 valueToReturn = balances[_to]; // update states balances[_to] = 0; weiRaised = weiRaised.sub(valueToReturn); _to.transfer(valueToReturn); }
25,859
7
// string memory kudoJSON = '{"who":' + tempKudos.who + '}'; string memory kudoJSONString = string(abi.encodePacked('{"giver":"',string(abi.encodePacked(tempKudos.giver)),'"}'));
string memory kudoSvgString = string(abi.encodePacked('{"image": "data:image/svg+xml;base64,',Base64.encode(bytes(imageSVG)),'"}'));
string memory kudoSvgString = string(abi.encodePacked('{"image": "data:image/svg+xml;base64,',Base64.encode(bytes(imageSVG)),'"}'));
16,858
81
// Executes a specified dispute's ruling./_disputeID The ID of the dispute.
function executeRuling(uint256 _disputeID) external { Dispute storage dispute = disputes[_disputeID]; if (dispute.period != Period.execution) revert NotExecutionPeriod(); if (dispute.ruled) revert RulingAlreadyExecuted(); (uint256 winningChoice, , ) = currentRuling(_disputeID); dispute.ruled = true; emit Ruling(dispute.arbitrated, _disputeID, winningChoice); dispute.arbitrated.rule(_disputeID, winningChoice); }
function executeRuling(uint256 _disputeID) external { Dispute storage dispute = disputes[_disputeID]; if (dispute.period != Period.execution) revert NotExecutionPeriod(); if (dispute.ruled) revert RulingAlreadyExecuted(); (uint256 winningChoice, , ) = currentRuling(_disputeID); dispute.ruled = true; emit Ruling(dispute.arbitrated, _disputeID, winningChoice); dispute.arbitrated.rule(_disputeID, winningChoice); }
20,453
253
// Get sender tokensHeld and amountOwed underlying from the cToken // Fail if the sender has a borrow balance // Fail if the sender is not permitted to redeem all of their tokens // Return true if the sender is not already ‘in’ the market // Set cToken account membership to false // Delete cToken from the account’s list of assets / load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; }
CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; }
7,479
48
// Approve a trade (if the tokens involved in the trade are controlled) This function can only be called by a token controller of one of the tokens involved in the trade. Indeed, when a token smart contract is controlled by an owner, the owner can decide to open thesecondary market by: - Whitelisting the DVP smart contract - Setting "token controllers" in the DVP smart contract, in order to approve all the trades made with his tokenindex Index of the trade to be executed. approved 'true' if trade is approved, 'false' if not. /
function approveTrade(uint256 index, bool approved) external { Trade storage trade = _trades[index]; require(trade.state == State.Pending, "Trade is not pending"); (address tokenAddress1,,,,,) = abi.decode(trade.tokenData1, (address, uint256, bytes32, string, bool, bool)); (address tokenAddress2,,,,,) = abi.decode(trade.tokenData2, (address, uint256, bytes32, string, bool, bool)); require(_isTokenController[tokenAddress1][msg.sender] || _isTokenController[tokenAddress2][msg.sender], "Only token controllers of involved tokens can approve a trade"); if (_isTokenController[tokenAddress1][msg.sender]) { (, uint256 tokenValue1, bytes32 tokenId1, string memory tokenStandard1, bool accepted1,) = abi.decode(trade.tokenData1, (address, uint256, bytes32, string, bool, bool)); trade.tokenData1 = abi.encode(tokenAddress1, tokenValue1, tokenId1, tokenStandard1, accepted1, approved); } if (_isTokenController[tokenAddress2][msg.sender]) { (, uint256 tokenValue2, bytes32 tokenId2, string memory tokenStandard2, bool accepted2,) = abi.decode(trade.tokenData2, (address, uint256, bytes32, string, bool, bool)); trade.tokenData2 = abi.encode(tokenAddress2, tokenValue2, tokenId2, tokenStandard2, accepted2, approved); } if (trade.executer == address(0) && _tradeisAccepted(index) && _tradeisApproved(index)) { _executeTrade(index); } }
function approveTrade(uint256 index, bool approved) external { Trade storage trade = _trades[index]; require(trade.state == State.Pending, "Trade is not pending"); (address tokenAddress1,,,,,) = abi.decode(trade.tokenData1, (address, uint256, bytes32, string, bool, bool)); (address tokenAddress2,,,,,) = abi.decode(trade.tokenData2, (address, uint256, bytes32, string, bool, bool)); require(_isTokenController[tokenAddress1][msg.sender] || _isTokenController[tokenAddress2][msg.sender], "Only token controllers of involved tokens can approve a trade"); if (_isTokenController[tokenAddress1][msg.sender]) { (, uint256 tokenValue1, bytes32 tokenId1, string memory tokenStandard1, bool accepted1,) = abi.decode(trade.tokenData1, (address, uint256, bytes32, string, bool, bool)); trade.tokenData1 = abi.encode(tokenAddress1, tokenValue1, tokenId1, tokenStandard1, accepted1, approved); } if (_isTokenController[tokenAddress2][msg.sender]) { (, uint256 tokenValue2, bytes32 tokenId2, string memory tokenStandard2, bool accepted2,) = abi.decode(trade.tokenData2, (address, uint256, bytes32, string, bool, bool)); trade.tokenData2 = abi.encode(tokenAddress2, tokenValue2, tokenId2, tokenStandard2, accepted2, approved); } if (trade.executer == address(0) && _tradeisAccepted(index) && _tradeisApproved(index)) { _executeTrade(index); } }
29,322
659
// voting quorum not met -> close proposal without execution.
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) { outcome = Outcome.QuorumNotMet; }
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) { outcome = Outcome.QuorumNotMet; }
3,435
57
// When voting stage is over, any citizen can call this function to end the election and start a new mandate./
function End_Election()external override { require(In_election_stage, "Not in Election time"); uint num_mandate = Actual_Mandate; //uint new_num_mandate = num_mandate.add(1); In_election_stage=false; Actual_Mandate = num_mandate + 1; emit New_Mandate(); Delegation_Uils.Transition_Mandate(Mandates, Mandates_Versions[Mandates[num_mandate].Version].Ivote_address, num_mandate, Internal_Governance_Version); }
function End_Election()external override { require(In_election_stage, "Not in Election time"); uint num_mandate = Actual_Mandate; //uint new_num_mandate = num_mandate.add(1); In_election_stage=false; Actual_Mandate = num_mandate + 1; emit New_Mandate(); Delegation_Uils.Transition_Mandate(Mandates, Mandates_Versions[Mandates[num_mandate].Version].Ivote_address, num_mandate, Internal_Governance_Version); }
44,467
15
// fetch post
Post memory _post = posts[_id];
Post memory _post = posts[_id];
40,409
7
// Controla que solo se permita ejecución desde el Creador
modifier soloCreador{ require(msg.sender == creador, "Solo el creador de la tienda puede utilizar esta funcion"); _; }
modifier soloCreador{ require(msg.sender == creador, "Solo el creador de la tienda puede utilizar esta funcion"); _; }
17,275
3,582
// 1792
entry "bloodyminded" : ENG_ADJECTIVE
entry "bloodyminded" : ENG_ADJECTIVE
18,404
71
// After calling this function the {_defaultSecondaryTradingLimit}/ will apply to addresses from array `_accountsToReset`/ instead of there {individualTransactionCountLimit} (if they had it)/Allowed only for ComplianceOfficer./Function blocked when contract is paused./Function just changes flag {hasOwnTransactionCountLimit} to `false`/for the addresses from `_accountsToReset`/and contract will ignore value which is set in/the parametr {individualTransactionCountLimit} for each account from array/_accountsToReset array of addresses to reset limit to default
function resetTransactionCountLimitToDefault( address[] memory _accountsToReset ) external whenNotPaused onlyRole(COMPLIANCE_OFFICER_ROLE) { for (uint256 i = 0; i < _accountsToReset.length; i++) { userData[_accountsToReset[i]].hasOwnTransactionCountLimit = false; }
function resetTransactionCountLimitToDefault( address[] memory _accountsToReset ) external whenNotPaused onlyRole(COMPLIANCE_OFFICER_ROLE) { for (uint256 i = 0; i < _accountsToReset.length; i++) { userData[_accountsToReset[i]].hasOwnTransactionCountLimit = false; }
26,887
355
// just in case, role could be dropped after claims for immutability
function setClaimInterval(uint256 _startTime, uint256 _endTime) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); claimStart = _startTime; claimEnd = _endTime; }
function setClaimInterval(uint256 _startTime, uint256 _endTime) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); claimStart = _startTime; claimEnd = _endTime; }
24,030
6
// initialization function/ _totalAllocatedAmount total allocated amount/ _totalClaims total available claim count/ _startTime start time / _periodTimesPerClaim period time per claim
function initialize( uint256 _totalAllocatedAmount, uint256 _totalClaims, uint256 _startTime, uint256 _periodTimesPerClaim
function initialize( uint256 _totalAllocatedAmount, uint256 _totalClaims, uint256 _startTime, uint256 _periodTimesPerClaim
12,597
6
// TODO define a mapping to store unique solutions submitted
mapping (bytes32 => Solutions) unisolutions;
mapping (bytes32 => Solutions) unisolutions;
48,934
48
// Used to get the most recent vault for the token using the registry.return An instance of a VaultAPI /
function bestVault() public view virtual returns (VaultAPI) { return baseRouter.bestVault(address(token)); }
function bestVault() public view virtual returns (VaultAPI) { return baseRouter.bestVault(address(token)); }
29,037
16
// --- Administration ---/Modify uint256 parametersparameter Name of the parameter to modifydata New parameter value/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "validityFlag") { require(either(data == 1, data == 0), "ConverterFeed/invalid-data"); validityFlag = data; } else if (parameter == "scalingFactor") { require(data > 0, "ConverterFeed/invalid-data"); converterFeedScalingFactor = data; } else revert("ConverterFeed/modify-unrecognized-param"); emit ModifyParameters(parameter, data); }
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "validityFlag") { require(either(data == 1, data == 0), "ConverterFeed/invalid-data"); validityFlag = data; } else if (parameter == "scalingFactor") { require(data > 0, "ConverterFeed/invalid-data"); converterFeedScalingFactor = data; } else revert("ConverterFeed/modify-unrecognized-param"); emit ModifyParameters(parameter, data); }
26,401
168
// Removes a value from a set. O(1). Returns true if the key was removed from the map, that is if it was present. /
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); }
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); }
696
8
// donationsCount: the total number of donations received by the campaign
uint256 public donationsCount;
uint256 public donationsCount;
44,681
67
// Yields the excess beyond the floor of x for positive numbers and the part of the number to the right/ of the radix point for negative numbers./Based on the odd function definition. https:en.wikipedia.org/wiki/Fractional_part/x The signed 59.18-decimal fixed-point number to get the fractional part of./result The fractional part of x as a signed 59.18-decimal fixed-point number.
function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } }
function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } }
8,431
45
// Get stored items of player for NFT
function getStorageItemIds( IERC721 _tokenAddress
function getStorageItemIds( IERC721 _tokenAddress
30,725
22
// Queue grant role transaction _target Address of contract or account to call _value Amount of ETH to send _data ABI encoded data send. _timestamp Timestamp after which the transaction can be executed. Requirements:- the caller must have the `DEFAULT_ADMIN_ROLE`. /
function queueGrantRoleTransaction(address _target, uint _value, bytes memory _data, uint256 _timestamp) public virtual onlyAdmin{ // Create tx id bytes32 txId = keccak256( abi.encode(_target, _value, _data, _timestamp) ); // Check transaction exists require(!grantRoleQueue[txId], "Mgmt Contract: Transaction is already in the queue!!"); // Check timestamp between min and max delay // --------|--------------|---------------------|--------- // block block + min block + max uint256 blockTimestamp = getBlockTimestamp(); require(_timestamp >= blockTimestamp.add(MINIMUM_GRANT_ROLE_DELAY), "Mgmt Contract: Timelock timstamp below range"); require(_timestamp <= blockTimestamp.add(MAXIMUM_GRANT_ROLE_DELAY), "Mgmt Contract: Timelock timstamp above range"); // Put tx in queue grantRoleQueue[txId] = true; grantRoleTxList.push(txId); emit QueueGrantRoleTransactionEvent(txId, _target, _value, _data, _timestamp); }
function queueGrantRoleTransaction(address _target, uint _value, bytes memory _data, uint256 _timestamp) public virtual onlyAdmin{ // Create tx id bytes32 txId = keccak256( abi.encode(_target, _value, _data, _timestamp) ); // Check transaction exists require(!grantRoleQueue[txId], "Mgmt Contract: Transaction is already in the queue!!"); // Check timestamp between min and max delay // --------|--------------|---------------------|--------- // block block + min block + max uint256 blockTimestamp = getBlockTimestamp(); require(_timestamp >= blockTimestamp.add(MINIMUM_GRANT_ROLE_DELAY), "Mgmt Contract: Timelock timstamp below range"); require(_timestamp <= blockTimestamp.add(MAXIMUM_GRANT_ROLE_DELAY), "Mgmt Contract: Timelock timstamp above range"); // Put tx in queue grantRoleQueue[txId] = true; grantRoleTxList.push(txId); emit QueueGrantRoleTransactionEvent(txId, _target, _value, _data, _timestamp); }
33,149
322
// be specified by overriding the virtual {_implementation} function. Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to adifferent contract through the {_delegate} function. The success and return data of the delegated call will be returned back to the caller of the proxy. /
abstract contract Proxy {
abstract contract Proxy {
4,508
6
// POT refers to Powers of Tau
uint256 internal constant MAX_POT_DEGREE = (2 ** 28); uint256 internal constant POT_TREE_HEIGHT = 28;
uint256 internal constant MAX_POT_DEGREE = (2 ** 28); uint256 internal constant POT_TREE_HEIGHT = 28;
38,720
23
// Send fauna army to conquer certain field fieldID ID of the field attackerID ID of the fauna attacker minion/
function faunaConquer(uint fieldID, uint attackerID) external preCheck(fieldID) { require( !faunaOnField[attackerID], "Battlefield: the fauna minion already on field"); require( faunaArmy.ownerOf(attackerID) == msg.sender, "Battlefield: not the commander of the fauna minion"); uint[] memory defender = fieldDefender[fieldID]; if (defender.length > 0) { uint defenderID = defender[0]; if (isFloraField[fieldID]) { _fight(faunaArmy, attackerID, floraArmy, defenderID); floraOnField[defenderID] = false; floraFieldCount--; faunaFieldCount++; } else { _fight(faunaArmy, attackerID, faunaArmy, defenderID); faunaOnField[defenderID] = false; } fieldDefender[fieldID][0] = attackerID; } else { fieldDefender[fieldID].push(attackerID); faunaFieldCount++; } faunaOnField[attackerID] = true; isFloraField[fieldID] = false; emit FieldState(fieldID, msg.sender, false, fieldDefender[fieldID]); }
function faunaConquer(uint fieldID, uint attackerID) external preCheck(fieldID) { require( !faunaOnField[attackerID], "Battlefield: the fauna minion already on field"); require( faunaArmy.ownerOf(attackerID) == msg.sender, "Battlefield: not the commander of the fauna minion"); uint[] memory defender = fieldDefender[fieldID]; if (defender.length > 0) { uint defenderID = defender[0]; if (isFloraField[fieldID]) { _fight(faunaArmy, attackerID, floraArmy, defenderID); floraOnField[defenderID] = false; floraFieldCount--; faunaFieldCount++; } else { _fight(faunaArmy, attackerID, faunaArmy, defenderID); faunaOnField[defenderID] = false; } fieldDefender[fieldID][0] = attackerID; } else { fieldDefender[fieldID].push(attackerID); faunaFieldCount++; } faunaOnField[attackerID] = true; isFloraField[fieldID] = false; emit FieldState(fieldID, msg.sender, false, fieldDefender[fieldID]); }
2,054
37
// Calculates the account liquidity given a modified collateral, collateral amount, bond and debt amount,/ using the current prices provided by the oracle.//Works by summing up each collateral amount multiplied by the USD value of each unit and divided by its/ respective collateral ratio, then dividing the sum by the total amount of debt drawn by the user.// Caveats:/ - This function expects that the "collateralList" and the "bondList" are each modified in advance to include/ the collateral and bond due to be modified.//account The account to make the query against./collateralModify The collateral to make the check against./collateralAmountModify The hypothetical normalized
function getHypotheticalAccountLiquidity( address account, IErc20 collateralModify, uint256 collateralAmountModify, IHToken bondModify, uint256 debtAmountModify ) external view returns (uint256 excessLiquidity, uint256 shortfallLiquidity);
function getHypotheticalAccountLiquidity( address account, IErc20 collateralModify, uint256 collateralAmountModify, IHToken bondModify, uint256 debtAmountModify ) external view returns (uint256 excessLiquidity, uint256 shortfallLiquidity);
5,693
296
// Return any remaining ether after the buy
uint256 remaining = msg.value.sub(price); if (remaining > 0) { (bool success, ) = msg.sender.call{value: remaining}("");
uint256 remaining = msg.value.sub(price); if (remaining > 0) { (bool success, ) = msg.sender.call{value: remaining}("");
30,400
203
// Set the oracle smart contract address./_oracle The new oracle smart contract address.
function setOracle(IOracle _oracle) external onlyGov { require(address(_oracle) != address(0), 'cannot set zero address oracle'); oracle = _oracle; emit SetOracle(address(_oracle)); }
function setOracle(IOracle _oracle) external onlyGov { require(address(_oracle) != address(0), 'cannot set zero address oracle'); oracle = _oracle; emit SetOracle(address(_oracle)); }
15,192
117
// allow unlocked transfers to special account
bool public returnsLocked;
bool public returnsLocked;
22,473
243
// DEPOSIT function
function deposit( address dfWallet, uint256 amountDAI, uint256 amountUSDC, uint256 amountWBTC, uint256 flashloanDAI, uint256 flashloanUSDC, FlashloanProvider flashloanType, address flashloanFromAddress
function deposit( address dfWallet, uint256 amountDAI, uint256 amountUSDC, uint256 amountWBTC, uint256 flashloanDAI, uint256 flashloanUSDC, FlashloanProvider flashloanType, address flashloanFromAddress
30,355
23
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) { return; }
if (currAuthority == address(0)) { return; }
12,407
5
// Set a flag if this is an NFI.
if (isNF) { type_ = type_ | TYPE_NF_BIT; }
if (isNF) { type_ = type_ | TYPE_NF_BIT; }
34,526
52
// return any unused funds balance
uint driver_balance_refund_due = driver_balance; driver_balance = 0; msg.sender.transfer(driver_balance_refund_due); agreement_state = LeaseAgreementStates.Ended; emit AgreementDriverFinalized(the_car, the_driver);
uint driver_balance_refund_due = driver_balance; driver_balance = 0; msg.sender.transfer(driver_balance_refund_due); agreement_state = LeaseAgreementStates.Ended; emit AgreementDriverFinalized(the_car, the_driver);
37,745
74
// require(_poolFee == 3000 || _poolFee == 500 || _poolFee == 10000, "Wrong poolFee!");
address poolAddress = computeAddress(_poolFee); poolMap[poolAddress] = true;
address poolAddress = computeAddress(_poolFee); poolMap[poolAddress] = true;
21,507
135
// Returns last active schain of a node. /
function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); }
function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); }
83,509
26
// return locking status userAddress address of to checkreturn locking status in true or false /
function getLockingStatus(address userAddress) external view returns(bool){ if (now < time[userAddress]){ return true; } else{ return false; } }
function getLockingStatus(address userAddress) external view returns(bool){ if (now < time[userAddress]){ return true; } else{ return false; } }
4,436
99
// If buyer or seller sets status fields and transfers either the premium or underlying /
function accept(uint optionUID) public { Option memory option = options[optionUID]; bool isSeller = option.seller == msg.sender || option.seller == address(0); bool isBuyer = option.buyer == msg.sender || option.buyer == address(0); require(isSeller || isBuyer, "accept(): Must either buyer or seller"); if (isBuyer){ _acceptBuyer(optionUID); } else if (isSeller) { _acceptSeller(optionUID); } }
function accept(uint optionUID) public { Option memory option = options[optionUID]; bool isSeller = option.seller == msg.sender || option.seller == address(0); bool isBuyer = option.buyer == msg.sender || option.buyer == address(0); require(isSeller || isBuyer, "accept(): Must either buyer or seller"); if (isBuyer){ _acceptBuyer(optionUID); } else if (isSeller) { _acceptSeller(optionUID); } }
36,099
165
// 更新利息
function accrueInterest() public onlyRestricted { uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; // 太短 零利息 if (accrualBlockNumberPrior == currentBlockNumber) { return; } uint256 cashPrior = controller.getCashPrior(underlying); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; // // 计算借贷利率 uint256 borrowRate = interestRateModel.getBorrowRate( cashPrior, borrowsPrior, reservesPrior ); // // 不能超过最大利率 require(borrowRate <= borrowRateMax, "borrow rate is too high"); // // 计算块差 uint256 blockDelta = currentBlockNumber.sub(accrualBlockNumberPrior); /* * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ uint256 simpleInterestFactor; uint256 interestAccumulated; uint256 totalBorrowsNew; uint256 totalReservesNew; uint256 borrowIndexNew; simpleInterestFactor = mulScalar(borrowRate, blockDelta); interestAccumulated = divExp( mulExp(simpleInterestFactor, borrowsPrior), expScale ); totalBorrowsNew = addExp(interestAccumulated, borrowsPrior); totalReservesNew = addExp( divExp(mulExp(reserveFactor, interestAccumulated), expScale), reservesPrior ); borrowIndexNew = addExp( divExp(mulExp(simpleInterestFactor, borrowIndexPrior), expScale), borrowIndexPrior ); accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; borrowRate = interestRateModel.getBorrowRate( cashPrior, totalBorrows, totalReserves ); // 不能超过最大利率 require(borrowRate <= borrowRateMax, "borrow rate is too high"); }
function accrueInterest() public onlyRestricted { uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; // 太短 零利息 if (accrualBlockNumberPrior == currentBlockNumber) { return; } uint256 cashPrior = controller.getCashPrior(underlying); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; // // 计算借贷利率 uint256 borrowRate = interestRateModel.getBorrowRate( cashPrior, borrowsPrior, reservesPrior ); // // 不能超过最大利率 require(borrowRate <= borrowRateMax, "borrow rate is too high"); // // 计算块差 uint256 blockDelta = currentBlockNumber.sub(accrualBlockNumberPrior); /* * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ uint256 simpleInterestFactor; uint256 interestAccumulated; uint256 totalBorrowsNew; uint256 totalReservesNew; uint256 borrowIndexNew; simpleInterestFactor = mulScalar(borrowRate, blockDelta); interestAccumulated = divExp( mulExp(simpleInterestFactor, borrowsPrior), expScale ); totalBorrowsNew = addExp(interestAccumulated, borrowsPrior); totalReservesNew = addExp( divExp(mulExp(reserveFactor, interestAccumulated), expScale), reservesPrior ); borrowIndexNew = addExp( divExp(mulExp(simpleInterestFactor, borrowIndexPrior), expScale), borrowIndexPrior ); accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; borrowRate = interestRateModel.getBorrowRate( cashPrior, totalBorrows, totalReserves ); // 不能超过最大利率 require(borrowRate <= borrowRateMax, "borrow rate is too high"); }
13,477
26
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned for accounts without code, i.e. `keccak256('')`
bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
2,305
7
// Bag left peaks one-by-one
for(uint i = numLeftPeaks; i > 0; i--) { bagger = keccak256(abi.encodePacked(bagger, proofItems[i-1])); }
for(uint i = numLeftPeaks; i > 0; i--) { bagger = keccak256(abi.encodePacked(bagger, proofItems[i-1])); }
47,113
173
// Removes a key-value pair from a map. O(1). Returns true if the key was removed from the map, that is if it was present. /
function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } }
function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } }
2,184
79
// low level token purchase function /
function buyTokens() public payable whenNotPaused { // Do not allow if gasprice is bigger than the maximum // This is for fair-chance for all contributors, so no one can // set a too-high transaction price and be able to buy earlier require(tx.gasprice <= maxTxGas); // valid purchase identifies which stage the contract is at (PreState/Token Sale) // making sure were inside the contribution period and the user // is sending enough Wei for the stage's rules require(validPurchase()); address sender = msg.sender; uint256 weiAmountSent = msg.value; // calculate token amount to be created uint256 rate = getRate(weiAmountSent); uint256 newTokens = weiAmountSent.mul(rate); // look if we have not yet reached the cap uint256 totalTokensSold = tokensSold.add(newTokens); if (isCrowdSaleRunning()) { require(totalTokensSold <= GMR_TOKEN_SALE_CAP); } else if (isPreSaleRunning()) { require(totalTokensSold <= PRE_SALE_GMR_TOKEN_CAP); } // update supporter state Supporter storage sup = supportersMap[sender]; uint256 totalWei = sup.weiSpent.add(weiAmountSent); sup.weiSpent = totalWei; // update contract state weiRaised = weiRaised.add(weiAmountSent); tokensSold = totalTokensSold; // mint the coins token.mint(sender, newTokens); TokenPurchase(sender, weiAmountSent, newTokens); // forward the funds to the wallet fundWallet.transfer(msg.value); }
function buyTokens() public payable whenNotPaused { // Do not allow if gasprice is bigger than the maximum // This is for fair-chance for all contributors, so no one can // set a too-high transaction price and be able to buy earlier require(tx.gasprice <= maxTxGas); // valid purchase identifies which stage the contract is at (PreState/Token Sale) // making sure were inside the contribution period and the user // is sending enough Wei for the stage's rules require(validPurchase()); address sender = msg.sender; uint256 weiAmountSent = msg.value; // calculate token amount to be created uint256 rate = getRate(weiAmountSent); uint256 newTokens = weiAmountSent.mul(rate); // look if we have not yet reached the cap uint256 totalTokensSold = tokensSold.add(newTokens); if (isCrowdSaleRunning()) { require(totalTokensSold <= GMR_TOKEN_SALE_CAP); } else if (isPreSaleRunning()) { require(totalTokensSold <= PRE_SALE_GMR_TOKEN_CAP); } // update supporter state Supporter storage sup = supportersMap[sender]; uint256 totalWei = sup.weiSpent.add(weiAmountSent); sup.weiSpent = totalWei; // update contract state weiRaised = weiRaised.add(weiAmountSent); tokensSold = totalTokensSold; // mint the coins token.mint(sender, newTokens); TokenPurchase(sender, weiAmountSent, newTokens); // forward the funds to the wallet fundWallet.transfer(msg.value); }
16,217
365
// Vote ended?
if (_isVoteOpen(vote_)) { return false; }
if (_isVoteOpen(vote_)) { return false; }
62,655
14
// buy Land with DAI using the merkle proof associated with it buyer address that perform the payment to address that will own the purchased Land reserved the reserved address (if any) x x coordinate of the Land y y coordinate of the Land size size of the pack of Land to purchase priceInSand price in SAND to purchase that Land proof merkleProof for that particular Land /
function buyLandWithDAI( address buyer, address to, address reserved, uint256 x, uint256 y, uint256 size, uint256 priceInSand, bytes32 salt, uint256[] calldata assetIds,
function buyLandWithDAI( address buyer, address to, address reserved, uint256 x, uint256 y, uint256 size, uint256 priceInSand, bytes32 salt, uint256[] calldata assetIds,
30,617
3
// Airdrop /
contract Airdrop is Pausable { using SafeMath for uint256; GenbbyToken public token; uint256 public tokens_sold; uint256 public constant decimals = 18; uint256 public constant factor = 10 ** decimals; uint256 public constant total_tokens = 500000 * factor; // 1% 5 % hard cap event Drop(address to, uint256 amount); /** * @dev The `owner` can set the token that uses the crowdsale */ function setToken(address tokenAddress) onlyOwner public { token = GenbbyToken(tokenAddress); } /** * @dev Function to give tokens to Airdrop participants * @param _to The address that will receive the tokens * @param _amount The amount of tokens to give * @return A boolean that indicates if the operation was successful */ function drop(address _to, uint256 _amount) onlyOwner whenNotPaused public returns (bool) { require (tokens_sold.add(_amount) <= total_tokens); token.mint(_to, _amount); tokens_sold = tokens_sold.add(_amount); Drop(_to, _amount); return true; } /* * @dev Do not allow direct deposits */ function () public payable { revert(); } }
contract Airdrop is Pausable { using SafeMath for uint256; GenbbyToken public token; uint256 public tokens_sold; uint256 public constant decimals = 18; uint256 public constant factor = 10 ** decimals; uint256 public constant total_tokens = 500000 * factor; // 1% 5 % hard cap event Drop(address to, uint256 amount); /** * @dev The `owner` can set the token that uses the crowdsale */ function setToken(address tokenAddress) onlyOwner public { token = GenbbyToken(tokenAddress); } /** * @dev Function to give tokens to Airdrop participants * @param _to The address that will receive the tokens * @param _amount The amount of tokens to give * @return A boolean that indicates if the operation was successful */ function drop(address _to, uint256 _amount) onlyOwner whenNotPaused public returns (bool) { require (tokens_sold.add(_amount) <= total_tokens); token.mint(_to, _amount); tokens_sold = tokens_sold.add(_amount); Drop(_to, _amount); return true; } /* * @dev Do not allow direct deposits */ function () public payable { revert(); } }
47,290
15
// Store NFT info
mapping(address => NftInfo) internal _nftInfo;
mapping(address => NftInfo) internal _nftInfo;
41,351
16
// Set the owner of this Smart Walletslot for owner = bytes32(uint256(keccak256('eip1967.proxy.owner')) - 1) = a7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126a
bytes32 ownerCell = keccak256(abi.encodePacked(owner)); assembly { sstore( 0xa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126a, ownerCell ) }
bytes32 ownerCell = keccak256(abi.encodePacked(owner)); assembly { sstore( 0xa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126a, ownerCell ) }
24,964
41
// Restore
mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3)
mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3)
8,674
87
// Getter for the terminated state of the futurereturn true if this vault is terminated /
function isTerminated() public view returns (bool) { return terminated; }
function isTerminated() public view returns (bool) { return terminated; }
61,134
0
// help variables
address internal lastPlayed; uint internal turnsTaken; bool public gameOver; address payable internal winner;
address internal lastPlayed; uint internal turnsTaken; bool public gameOver; address payable internal winner;
51,079
12
// Claim RGT/set timestamp for initial transfer of RDPT to `account`
if (balanceOf(account) > 0) rariGovernanceTokenDistributor.distributeRgt(account, IRariGovernanceTokenDistributor.RariPool.Stable); else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(account, IRariGovernanceTokenDistributor.RariPool.Stable);
if (balanceOf(account) > 0) rariGovernanceTokenDistributor.distributeRgt(account, IRariGovernanceTokenDistributor.RariPool.Stable); else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(account, IRariGovernanceTokenDistributor.RariPool.Stable);
13,291
310
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
set._values[toDeleteIndex] = lastvalue;
359
37
// function addAttributes ( tuple[] _attributes ) external;
function addContractToWhitelist(address _contract) external; function addMinterRole(address _address) external; function addToPreSaleList(address[] memory entries) external;
function addContractToWhitelist(address _contract) external; function addMinterRole(address _address) external; function addToPreSaleList(address[] memory entries) external;
34,666
175
// ToDaMoon with Governance.
contract ToDaMoon is BEP20('Moon Token', 'MOON') { /// @dev Creates `_amount` token to `_to`. Must only be called by the owner (BullFarm). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from ,uint256 _amount) public onlyOwner { _burn(_from, _amount); _moveDelegates(address(0), _delegates[_from], _amount); } // The BULL TOKEN! BullToken public bull; constructor( BullToken _bull ) public { bull = _bull; } // Safe bull transfer function, just in case if rounding error causes pool to not have enough BULLs. function safeBullTransfer(address _to, uint256 _amount) public onlyOwner { uint256 bullBal = bull.balanceOf(address(this)); if (_amount > bullBal) { bull.transfer(_to, bullBal); } else { bull.transfer(_to, _amount); } } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @dev A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @dev A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @dev The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @dev The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @dev The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @dev A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @dev An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @dev An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @dev Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @dev Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @dev Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "BULL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "BULL::delegateBySig: invalid nonce"); require(now <= expiry, "BULL::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @dev Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "BULL::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BULLs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "BULL::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract ToDaMoon is BEP20('Moon Token', 'MOON') { /// @dev Creates `_amount` token to `_to`. Must only be called by the owner (BullFarm). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from ,uint256 _amount) public onlyOwner { _burn(_from, _amount); _moveDelegates(address(0), _delegates[_from], _amount); } // The BULL TOKEN! BullToken public bull; constructor( BullToken _bull ) public { bull = _bull; } // Safe bull transfer function, just in case if rounding error causes pool to not have enough BULLs. function safeBullTransfer(address _to, uint256 _amount) public onlyOwner { uint256 bullBal = bull.balanceOf(address(this)); if (_amount > bullBal) { bull.transfer(_to, bullBal); } else { bull.transfer(_to, _amount); } } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @dev A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @dev A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @dev The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @dev The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @dev The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @dev A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @dev An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @dev An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @dev Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @dev Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @dev Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "BULL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "BULL::delegateBySig: invalid nonce"); require(now <= expiry, "BULL::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @dev Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "BULL::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BULLs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "BULL::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
11,442
91
// Removes a NFT from owner.Use and override this function with caution. Wrong usage can have serious consequences._from Address from wich we want to remove the NFT._tokenId Which NFT we want to remove./
function _removeNFToken( address _from, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == _from); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); }
function _removeNFToken( address _from, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == _from); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); }
651
319
// Gets the amount1 delta between two prices/Calculates liquidity(sqrt(upper) - sqrt(lower))/sqrtRatioAX96 A sqrt price/sqrtRatioBX96 Another sqrt price/liquidity The amount of usable liquidity/roundUp Whether to round the amount up, or down/ return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp
function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp
3,900
0
// 用于标记余额存储的情况
mapping(address => bool) private isIncluded; address[] private included;
mapping(address => bool) private isIncluded; address[] private included;
8,502
271
// voteInfo returns the vote and the amount of reputation of the user committed to this proposal _proposalId the ID of the proposal _voter the address of the voterreturn uint256 vote - the voters vote uint256 reputation - amount of reputation committed by _voter to _proposalId /
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) { Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); }
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) { Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); }
11,173
96
// move v to r position
mstore(add(_signature, 0x20), v) result := and( and(
mstore(add(_signature, 0x20), v) result := and( and(
31,753
80
// Timestamps when token started to sell
uint256 public openTime = block.timestamp;
uint256 public openTime = block.timestamp;
25,646
317
// cumulate the balance of the sender
(, uint256 fromBalance, uint256 fromBalanceIncrease, uint256 fromIndex ) = cumulateBalanceInternal(_from);
(, uint256 fromBalance, uint256 fromBalanceIncrease, uint256 fromIndex ) = cumulateBalanceInternal(_from);
51,477
11
// _name = "Yearn Finance Insurance";_symbol = "YFIn";
_name = "Yearn Finance Insurance"; _symbol = "YFIn"; _decimals = 18; _totalSupply = 30000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply);
_name = "Yearn Finance Insurance"; _symbol = "YFIn"; _decimals = 18; _totalSupply = 30000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply);
10,047
0
// A generic resolver interface which includes all the functions including the ones deprecated /
interface Resolver{ event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); event ContenthashChanged(bytes32 indexed node, bytes hash); /* Deprecated events */ event ContentChanged(bytes32 indexed node, bytes32 hash); function ABI(bytes32 _node, uint256 _contentTypes) external view returns (uint256, bytes memory); function addr(bytes32 _node) external view returns (address); function addr(bytes32 _node, uint _coinType) external view returns(bytes memory); function contenthash(bytes32 _node) external view returns (bytes memory); function dnsrr(bytes32 _node) external view returns (bytes memory); function name(bytes32 _node) external view returns (string memory); function pubkey(bytes32 _node) external view returns (bytes32 x, bytes32 y); function text(bytes32 _node, string calldata _key) external view returns (string memory); function interfaceImplementer(bytes32 _node, bytes4 _interfaceID) external view returns (address); function setABI(bytes32 _node, uint256 _contentType, bytes calldata _data) external; function setAddr(bytes32 _node, address _addr) external; function setAddr(bytes32 _node, uint _coinType, bytes calldata _a) external; function setContenthash(bytes32 _node, bytes calldata _hash) external; function setDnsrr(bytes32 _node, bytes calldata _data) external; function setName(bytes32 _node, string calldata _name) external; function setPubkey(bytes32 _node, bytes32 _x, bytes32 _y) external; function setText(bytes32 _node, string calldata _key, string calldata _value) external; function setInterface(bytes32 _node, bytes4 _interfaceID, address _implementer) external; function supportsInterface(bytes4 _interfaceID) external pure returns (bool); function multicall(bytes[] calldata _data) external returns(bytes[] memory results); /* Deprecated functions */ function content(bytes32 _node) external view returns (bytes32); function multihash(bytes32 _node) external view returns (bytes memory); function setContent(bytes32 _node, bytes32 hash) external; function setMultihash(bytes32 _node, bytes calldata _hash) external; }
interface Resolver{ event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); event ContenthashChanged(bytes32 indexed node, bytes hash); /* Deprecated events */ event ContentChanged(bytes32 indexed node, bytes32 hash); function ABI(bytes32 _node, uint256 _contentTypes) external view returns (uint256, bytes memory); function addr(bytes32 _node) external view returns (address); function addr(bytes32 _node, uint _coinType) external view returns(bytes memory); function contenthash(bytes32 _node) external view returns (bytes memory); function dnsrr(bytes32 _node) external view returns (bytes memory); function name(bytes32 _node) external view returns (string memory); function pubkey(bytes32 _node) external view returns (bytes32 x, bytes32 y); function text(bytes32 _node, string calldata _key) external view returns (string memory); function interfaceImplementer(bytes32 _node, bytes4 _interfaceID) external view returns (address); function setABI(bytes32 _node, uint256 _contentType, bytes calldata _data) external; function setAddr(bytes32 _node, address _addr) external; function setAddr(bytes32 _node, uint _coinType, bytes calldata _a) external; function setContenthash(bytes32 _node, bytes calldata _hash) external; function setDnsrr(bytes32 _node, bytes calldata _data) external; function setName(bytes32 _node, string calldata _name) external; function setPubkey(bytes32 _node, bytes32 _x, bytes32 _y) external; function setText(bytes32 _node, string calldata _key, string calldata _value) external; function setInterface(bytes32 _node, bytes4 _interfaceID, address _implementer) external; function supportsInterface(bytes4 _interfaceID) external pure returns (bool); function multicall(bytes[] calldata _data) external returns(bytes[] memory results); /* Deprecated functions */ function content(bytes32 _node) external view returns (bytes32); function multihash(bytes32 _node) external view returns (bytes memory); function setContent(bytes32 _node, bytes32 hash) external; function setMultihash(bytes32 _node, bytes calldata _hash) external; }
26,380
11
// we first set the allowance to the uniswap router
if (Token(params.tokenIn).allowance(address(this), UNISWAP_V3_SWAP_ROUTER_ADDRESS) < params.amountIn) { safeApproveInternal(params.tokenIn, UNISWAP_V3_SWAP_ROUTER_ADDRESS, type(uint).max); }
if (Token(params.tokenIn).allowance(address(this), UNISWAP_V3_SWAP_ROUTER_ADDRESS) < params.amountIn) { safeApproveInternal(params.tokenIn, UNISWAP_V3_SWAP_ROUTER_ADDRESS, type(uint).max); }
1,374
81
// Allow to spend foundation tokens only after 48 weeks after minting is finished
return now < mintingStopDate + 48 weeks;
return now < mintingStopDate + 48 weeks;
14,089
2
// Get this contract reward's from rewarderpool.
uint256 contractReward = TheRewarderPool(target).rewardToken().balanceOf(address(this));
uint256 contractReward = TheRewarderPool(target).rewardToken().balanceOf(address(this));
42,958
122
// Liquidate up to `_amountNeeded` of `want` of this strategy's positions,irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.This function should return the amount of `want` tokens made available by theliquidation. If there is a difference between them, `_loss` indicates whether thedifference is due to a realized loss, or if there is some other sitution at play(e.g. locked funds) where the amount made available is less than what is needed.This function is used during emergency exit instead of `prepareReturn()` toliquidate all of the Strategy's positions back to the Vault. NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
1,488
58
// Constructor //Constructs the `EnhancedAppealableArbitrator` contract. _arbitrationPrice The amount to be paid for arbitration. _arbitrator The back up arbitrator. _arbitratorExtraData Not used by this contract. _timeOut The time out for the appeal period./
constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut
constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut
15,584
33
// This function returns whether or not a given user is allowed to trade a given amount and removing the staked amount from their balance if they are staked_user address of user_amount to check if the user can spend return true if they are allowed to spend the amount being checked/
function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked if (balanceOf(self, _user)- self.uintVars[stakeAmount] >= _amount) { return true; } return false; } return (balanceOf(self, _user) >= _amount); }
function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked if (balanceOf(self, _user)- self.uintVars[stakeAmount] >= _amount) { return true; } return false; } return (balanceOf(self, _user) >= _amount); }
25,441
55
// returns the number of whitelisted pools return number of whitelisted pools/
function whitelistedPoolCount() external view returns (uint256) { return poolWhitelist.length; }
function whitelistedPoolCount() external view returns (uint256) { return poolWhitelist.length; }
23,137
9
// Fallback function for balancer flashloan. Fallback function for balancer flashloan. _amounts list of amounts for the corresponding assets or amount of ether to borrow as collateral for flashloan. _fees list of fees for the corresponding addresses for flashloan. _data extra data passed(includes route info aswell)./
function receiveFlashLoan( IERC20[] memory, uint256[] memory _amounts, uint256[] memory _fees, bytes memory _data
function receiveFlashLoan( IERC20[] memory, uint256[] memory _amounts, uint256[] memory _fees, bytes memory _data
41,726
220
// Override isApprovedForAll to allowlist user's OpenSea proxy accounts to enable gas-less listings. /
function isApprovedForAll(address owner, address operator) public view override returns (bool)
function isApprovedForAll(address owner, address operator) public view override returns (bool)
4,568
396
// Set the state of the OpenSea operator filter value Flag indicating if the operator filter should be applied to transfers and approvals /
function setOperatorFilteringEnabled(bool value)
function setOperatorFilteringEnabled(bool value)
8,973
5
// Ensure sending is to valid address! 0x0 address cane be used to burn()
require(_to != address(0)); balanceOf[_from] = balanceOf[_from] - (_value); balanceOf[_to] = balanceOf[_to] + (_value); emit Transfer(_from, _to, _value);
require(_to != address(0)); balanceOf[_from] = balanceOf[_from] - (_value); balanceOf[_to] = balanceOf[_to] + (_value); emit Transfer(_from, _to, _value);
44,453
10
// Sets the Dev contract /
event NewDev(address oldDev, address newDev);
event NewDev(address oldDev, address newDev);
10,170
110
// Get minimum amount of loan asset get after swapping collateral asset.
uint256 minAmount = Util.calcMinAmount(globals, address(collateralAsset), liquidityAsset, liquidationAmt);
uint256 minAmount = Util.calcMinAmount(globals, address(collateralAsset), liquidityAsset, liquidationAmt);
1,555
10
// FinaLounge is the coolest lounge in the office. You come in with some Fina, and leave with more! The longer you stay, the more Fina you get. This contract handles swapping to and from xFina, FinaSwap's staking token.
contract FinaLounge is ERC20("FinaLounge", "xFNA"){ using SafeMath for uint256; IERC20 public fina; // Define the Fina token contract constructor(IERC20 _fina) public { fina = _fina; } // Enter the lounge. Pay some FNAs. Earn some shares. // Locks Fina and mints xFina function enter(uint256 _amount) public { // Gets the amount of Fina locked in the contract uint256 totalFina = fina.balanceOf(address(this)); // Gets the amount of xFina in existence uint256 totalShares = totalSupply(); // If no xFina exists, mint it 1:1 to the amount put in if (totalShares == 0 || totalFina == 0) { _mint(msg.sender, _amount); } // Calculate and mint the amount of xFina the Fina is worth. The ratio will change overtime, as xFina is burned/minted and Fina deposited + gained from fees / withdrawn. else { uint256 what = _amount.mul(totalShares).div(totalFina); _mint(msg.sender, what); } // Lock the Fina in the contract fina.transferFrom(msg.sender, address(this), _amount); } // Leave the lounge. Claim back your FNAs. // Unlocks the staked + gained Fina and burns xFina function leave(uint256 _share) public { // Gets the amount of xFina in existence uint256 totalShares = totalSupply(); // Calculates the amount of Fina the xFina is worth uint256 what = _share.mul(fina.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); fina.transfer(msg.sender, what); } }
contract FinaLounge is ERC20("FinaLounge", "xFNA"){ using SafeMath for uint256; IERC20 public fina; // Define the Fina token contract constructor(IERC20 _fina) public { fina = _fina; } // Enter the lounge. Pay some FNAs. Earn some shares. // Locks Fina and mints xFina function enter(uint256 _amount) public { // Gets the amount of Fina locked in the contract uint256 totalFina = fina.balanceOf(address(this)); // Gets the amount of xFina in existence uint256 totalShares = totalSupply(); // If no xFina exists, mint it 1:1 to the amount put in if (totalShares == 0 || totalFina == 0) { _mint(msg.sender, _amount); } // Calculate and mint the amount of xFina the Fina is worth. The ratio will change overtime, as xFina is burned/minted and Fina deposited + gained from fees / withdrawn. else { uint256 what = _amount.mul(totalShares).div(totalFina); _mint(msg.sender, what); } // Lock the Fina in the contract fina.transferFrom(msg.sender, address(this), _amount); } // Leave the lounge. Claim back your FNAs. // Unlocks the staked + gained Fina and burns xFina function leave(uint256 _share) public { // Gets the amount of xFina in existence uint256 totalShares = totalSupply(); // Calculates the amount of Fina the xFina is worth uint256 what = _share.mul(fina.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); fina.transfer(msg.sender, what); } }
11,923
0
// JUST FOR TESTING - ITS OKAY TO REMOVE ALL OF THESE VARS
address public lastTokenBorrow; uint public lastAmount; address public lastTokenPay; uint public lastamountToRepay; bytes public lastUserData;
address public lastTokenBorrow; uint public lastAmount; address public lastTokenPay; uint public lastamountToRepay; bytes public lastUserData;
46,804