comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @notice Recovers the source address which signed a message * @dev Comparing to a claimed address would add nothing, * as the caller could simply perform the recover and claim that address. * @param message The data that was presumably signed * @param signature The fingerprint of the data + private key ...
function source(bytes memory message, bytes memory signature) public pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message))); return ecrecove...
0.6.10
// decode a uq112x112 into a uint with 18 decimals of precision
function decode112with18(uq112x112 memory self) internal pure returns (uint) { // we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous // instead, get close to: // (x * 1e18) >> 112 // without risk of overflowing, e.g.: // (x) / 2 ** (112 - lg(...
0.6.10
/** * @notice Get the underlying price of a cToken * @dev Implements the PriceOracle interface for Compound v2. * @param cToken The cToken address for price retrieval * @return Price denominated in USD, with 18 decimals, for the given cToken address */
function getUnderlyingPrice(address cToken) external view returns (uint) { TokenConfig memory config = getTokenConfigByCToken(cToken); // Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit) // Since the prices in this view have 6 decimals, we must scale them by 1e(36 - ...
0.6.10
/** * @notice Post open oracle reporter prices, and recalculate stored price by comparing to anchor * @dev We let anyone pay to post anything, but only prices from configured reporter will be stored in the view. * @param messages The messages to post to the oracle * @param signatures The signatures for the corr...
function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external { require(messages.length == signatures.length, "messages and signatures must be 1:1"); // Save the prices for (uint i = 0; i < messages.length; i++) { priceData.put(...
0.6.10
/** * @dev Get time-weighted average prices for a token at the current timestamp. * Update new and old observations of lagging window if period elapsed. */
function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) { bytes32 symbolHash = config.symbolHash; uint cumulativePrice = currentCumulativePrice(config); Observation memory newObservation = newObservations[symbolHash]; // Update new and old observa...
0.6.10
/** * @notice Invalidate the reporter, and fall back to using anchor directly in all cases * @dev Only the reporter may sign a message which allows it to invalidate itself. * To be used in cases of emergency, if the reporter thinks their key may be compromised. * @param message The data that was presumably sig...
function invalidateReporter(bytes memory message, bytes memory signature) external { (string memory decodedMessage, ) = abi.decode(message, (string, address)); require(keccak256(abi.encodePacked(decodedMessage)) == rotateHash, "invalid message must be 'rotate'"); require(source(message, signa...
0.6.10
// @notice investors can vote to call this function for the new assetManager to then call // @dev new assetManager must approve this contract to transfer in and lock _ amount of platform tokens
function changeAssetManager(address _assetAddress, address _newAssetManager, uint256 _amount, bool _withhold) external returns (bool) { require(_newAssetManager != address(0)); require(msg.sender == database.addressStorage(keccak256(abi.encodePacked("asset.dao.admin", _assetAddress))), "Only the...
0.4.24
/// @dev Overflow proof multiplication
function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "multiplication overflow"); return c; }
0.6.10
/** * @notice Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. * @return A boolean that indicates if the operation was successful. */
function transfer(address to, uint256 value) public returns (bool) { // Call super's transfer, including event emission bool transferred = super.transfer(to, value); if (transferred) { // Adjust balance blocks addBalanceBlocks(msg.sender); ...
0.4.25
/** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @dev Beware that to change the approve amount you first have to reduce the addresses' * allowance to zero by calling `approve(spender, 0)` if it is not already 0 to mitigate the race * condition described...
function approve(address spender, uint256 value) public returns (bool) { // Prevent the update of non-zero allowance require(0 == value || 0 == allowance(msg.sender, spender)); // Call super's approve, including event emission return super.approve(spender, value); ...
0.4.25
/** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred * @return A boolean that indicates if the operation was succes...
function transferFrom(address from, address to, uint256 value) public returns (bool) { // Call super's transferFrom, including event emission bool transferred = super.transferFrom(from, to, value); if (transferred) { // Adjust balance blocks addBalan...
0.4.25
/** * @notice Calculate the amount of balance blocks, i.e. the area under the curve (AUC) of * balance as function of block number * @dev The AUC is used as weight for the share of revenue that a token holder may claim * @param account The account address for which calculation is done * @param startBlock The ...
function balanceBlocksIn(address account, uint256 startBlock, uint256 endBlock) public view returns (uint256) { require(startBlock < endBlock); require(account != address(0)); if (balanceBlockNumbers[account].length == 0 || endBlock < balanceBlockNumbers[account][0]) ...
0.4.25
/** * @notice Get the subset of holders (optionally with positive balance only) in the given 0 based index range * @param low The lower inclusive index * @param up The upper inclusive index * @param posOnly List only positive balance holders * @return The subset of positive balance registered holders in the g...
function holdersByIndices(uint256 low, uint256 up, bool posOnly) public view returns (address[]) { require(low <= up); up = up > holders.length - 1 ? holders.length - 1 : up; uint256 length = 0; if (posOnly) { for (uint256 i = low; i <= up; i++) ...
0.4.25
/// @notice Destroy this contract
function triggerSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Require that self-destruction has not been disabled require(!selfDestructionDisabled); // Emit event emit TriggerSelfDe...
0.4.25
/// @notice Set the deployer of this contract /// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { // Set new deployer address oldDeployer = deployer; deployer = newDeployer; // Emit event emit ...
0.4.25
/// @notice Set the operator of this contract /// @param newOperator The address of the new operator
function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { // Set new operator address oldOperator = operator; operator = newOperator; // Emit event emit ...
0.4.25
/// @notice Set the address of token /// @param _token The address of token
function setToken(IERC20 _token) public onlyOperator notNullOrThisAddress(_token) { // Require that the token has not previously been set require(address(token) == address(0)); // Update beneficiary token = _token; // Emit event emit SetToken...
0.4.25
/// @notice Define a set of new releases /// @param earliestReleaseTimes The timestamp after which the corresponding amount may be released /// @param amounts The amounts to be released /// @param releaseBlockNumbers The set release block numbers for releases whose earliest release time /// is in the past
function defineReleases(uint256[] earliestReleaseTimes, uint256[] amounts, uint256[] releaseBlockNumbers) onlyOperator public { require(earliestReleaseTimes.length == amounts.length); require(earliestReleaseTimes.length >= releaseBlockNumbers.length); // Require that token ad...
0.4.25
/// @notice Set the block number of a release that is not done /// @param index The index of the release /// @param blockNumber The updated block number
function setReleaseBlockNumber(uint256 index, uint256 blockNumber) public onlyBeneficiary { // Require that the release is not done require(!releases[index].done); // Update the release block number releases[index].blockNumber = blockNumber; // Emit event ...
0.4.25
/// @notice Transfers tokens held in the indicated release to beneficiary. /// @param index The index of the release
function release(uint256 index) public onlyBeneficiary { // Get the release object Release storage _release = releases[index]; // Require that this release has been properly defined by having non-zero amount require(0 < _release.amount); // Require that th...
0.4.25
/// @notice Calculate the released amount blocks, i.e. the area under the curve (AUC) of /// release amount as function of block number /// @param startBlock The start block number considered /// @param endBlock The end block number considered /// @return The calculated AUC
function releasedAmountBlocksIn(uint256 startBlock, uint256 endBlock) public view returns (uint256) { require(startBlock < endBlock); if (executedReleasesCount == 0 || endBlock < releases[0].blockNumber) return 0; uint256 i = 0; while (i < execute...
0.4.25
/** * @notice Get price from BAND protocol. * @param symbol The symbol that used to get price of * @return The price, scaled by 1e18 */
function getPriceFromBAND(string memory symbol) internal view returns (uint256) { StdReferenceInterface.ReferenceData memory data = ref.getReferenceData(symbol, QUOTE_SYMBOL); require(data.rate > 0, "invalid price"); // Price from BAND is always 1e18 base. return data.rate; }
0.5.17
/** * @notice Set ChainLink aggregators for multiple tokens * @param tokenAddresses The list of underlying tokens * @param bases The list of ChainLink aggregator bases * @param quotes The list of ChainLink aggregator quotes, currently support 'ETH' and 'USD' */
function _setAggregators( address[] calldata tokenAddresses, address[] calldata bases, address[] calldata quotes ) external { require(msg.sender == admin || msg.sender == guardian, "only the admin or guardian may set the aggregators"); require(tokenAddresses.length == bases.l...
0.5.17
/** * @notice Set Band references for multiple tokens * @param tokenAddresses The list of underlying tokens * @param symbols The list of symbols used by Band reference */
function _setReferences(address[] calldata tokenAddresses, string[] calldata symbols) external { require(msg.sender == admin || msg.sender == guardian, "only the admin or guardian may set the references"); require(tokenAddresses.length == symbols.length, "mismatched data"); for (uint256 i = 0; i...
0.5.17
/// @notice Calculate the vested and unclaimed days and tokens available for `_grantId` to claim /// Due to rounding errors once grant duration is reached, returns the entire left grant amount /// Returns (0, 0) if cliff has not been reached
function calculateGrantClaim(uint256 _grantId) public view returns (uint16, uint256) { Grant storage tokenGrant = tokenGrants[_grantId]; require(tokenGrant.recipient == msg.sender || owner() == msg.sender, '!recipient'); // For grants created with a future start date, that hasn't been reached, return 0, 0 ...
0.6.12
/// @notice Allows a grant recipient to claim their vested tokens. Errors if no tokens have vested /// It is advised recipients check they are entitled to claim via `calculateGrantClaim` before calling this
function claimVestedTokens(uint256 _grantId) external { uint16 daysVested; uint256 amountVested; (daysVested, amountVested) = calculateGrantClaim(_grantId); require(amountVested > 0, "amountVested is 0"); Grant storage tokenGrant = tokenGrants[_grantId]; tokenGrant.daysClaimed = uint16(tokenGra...
0.6.12
/** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tok...
function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256) { /* Fail if transfer not allowed */ uint256 allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { ...
0.5.17
/** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizin...
function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256) { /* Fail if seize not allowed */ uint256 allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeToke...
0.5.17
/** @dev Mint in the public sale * @param quantity The quantity of tokens to mint */
function publicMint(uint256 quantity) public payable { bytes32 _contractState = keccak256(abi.encodePacked(contractState)); require( _contractState == publicMintState, "Public minting is not active" ); // check the txn value require( msg.value ...
0.8.4
/** * @dev Create a new instance of the SwissCryptoExchange contract. * @param _admin address Admin address * @param _feeAccount address Fee Account address * @param _accountLevelsAddr address AccountLevels contract address * @param _feeMake uint256 FeeMake amount * @param _feeT...
function SwissCryptoExchange( address _admin, address _feeAccount, address _accountLevelsAddr, uint256 _feeMake, uint256 _feeTake, uint256 _feeRebate ) public { // Ensure the admin address is valid. require(_admin != 0x0); // Store the values. admin = _admi...
0.4.24
/** * @dev Change the admin address. * @param _admin address The new admin address */
function changeAdmin(address _admin) public onlyAdmin { // The provided address should be valid and different from the current one. require(_admin != 0x0 && admin != _admin); // Store the new value. admin = _admin; }
0.4.24
/** * @dev Change the feeTake amount. * @param _feeTake uint256 New fee take. */
function changeFeeTake(uint256 _feeTake) public onlyAdmin { // The new feeTake should be greater than or equal to the feeRebate. require(_feeTake >= feeRebate); // Store the new value. feeTake = _feeTake; }
0.4.24
/** * @dev Change the feeRebate amount. * @param _feeRebate uint256 New fee rebate. */
function changeFeeRebate(uint256 _feeRebate) public onlyAdmin { // The new feeRebate should be less than or equal to the feeTake. require(_feeRebate <= feeTake); // Store the new value. feeRebate = _feeRebate; }
0.4.24
/** * @dev Add a ERC20 token contract address to the whitelisted ones. * @param token address Address of the contract to be added to the whitelist. */
function addWhitelistedTokenAddr(address token) public onlyAdmin { // Token address should not be 0x0 (ether) and it should not be already whitelisted. require(token != 0x0 && !whitelistedTokens[token]); // Change the flag for this contract address to true. whitelistedTokens[token] = true; }
0.4.24
/** * @dev Remove a ERC20 token contract address from the whitelisted ones. * @param token address Address of the contract to be removed from the whitelist. */
function removeWhitelistedTokenAddr(address token) public onlyAdmin { // Token address should not be 0x0 (ether) and it should be whitelisted. require(token != 0x0 && whitelistedTokens[token]); // Change the flag for this contract address to false. whitelistedTokens[token] = false; }
0.4.24
/** * @dev Add an user address to the whitelisted ones. * @param user address Address to be added to the whitelist. */
function addWhitelistedUserAddr(address user) public onlyAdmin { // Address provided should be valid and not already whitelisted. require(user != 0x0 && !whitelistedUsers[user]); // Change the flag for this address to false. whitelistedUsers[user] = true; }
0.4.24
/** * @dev Remove an user address from the whitelisted ones. * @param user address Address to be removed from the whitelist. */
function removeWhitelistedUserAddr(address user) public onlyAdmin { // Address provided should be valid and whitelisted. require(user != 0x0 && whitelistedUsers[user]); // Change the flag for this address to false. whitelistedUsers[user] = false; }
0.4.24
/** * @dev Deposit wei into the exchange contract. */
function deposit() public payable { // Only whitelisted users can make deposits. require(whitelistedUsers[msg.sender]); // Add the deposited wei amount to the user balance. tokens[0x0][msg.sender] = tokens[0x0][msg.sender].add(msg.value); // Trigger the event. Deposit(0x0, msg.sender, ...
0.4.24
/** * @dev Withdraw wei from the exchange contract back to the user. * @param amount uint256 Wei amount to be withdrawn. */
function withdraw(uint256 amount) public { // Requester should have enough balance. require(tokens[0x0][msg.sender] >= amount); // Substract the withdrawn wei amount from the user balance. tokens[0x0][msg.sender] = tokens[0x0][msg.sender].sub(amount); // Transfer the wei to the requester....
0.4.24
/** * @dev Perform a new token deposit to the exchange contract. * @dev Remember to call ERC20(address).approve(this, amount) or this contract will not * be able to do the transfer on your behalf. * @param token address Address of the deposited token contract * @param amount uint256 Amount to be deposit...
function depositToken(address token, uint256 amount) public { // Should not deposit wei using this function and // token contract address should be whitelisted. require(token != 0x0 && whitelistedTokens[token]); // Only whitelisted users can make deposits. require(whitelistedUse...
0.4.24
/** * @dev Withdraw the given token amount from the requester balance. * @param token address Address of the withdrawn token contract * @param amount uint256 Amount of tokens to be withdrawn */
function withdrawToken(address token, uint256 amount) public { // Should not withdraw wei using this function. require(token != 0x0); // Requester should have enough balance. require(tokens[token][msg.sender] >= amount); // Substract the withdrawn token amount from the user balance. to...
0.4.24
/** * @dev Place a new order to the this contract. * @param tokenGet address * @param amountGet uint256 * @param tokenGive address * @param amountGive uint256 * @param expires uint256 * @param nonce uint256 */
function order( address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint256 nonce ) public { // Order placer address should be whitelisted. require(whitelistedUsers[msg.sender]); // Order tokens addresses should be whitel...
0.4.24
/** * @dev Cancel an existing order. * @param tokenGet address * @param amountGet uint256 * @param tokenGive address * @param amountGive uint256 * @param expires uint256 * @param nonce uint256 * @param v uint8 * @param r bytes32 * @param s bytes32 */
function cancelOrder( address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint256 nonce, uint8 v, bytes32 r, bytes32 s ) public { // Calculate the order hash. bytes32 hash = keccak256(address(this), tokenGet, amou...
0.4.24
/** * @dev Perform a trade. * @param tokenGet address * @param amountGet uint256 * @param tokenGive address * @param amountGive uint256 * @param expires uint256 * @param nonce uint256 * @param user address * @param v uint8 * @param r bytes32 * @param s ...
function trade( address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s, uint256 amount ) public { // Only whitelisted users can perform trades. re...
0.4.24
/** * @dev Check if the trade with provided parameters will pass or not. * @param tokenGet address * @param amountGet uint256 * @param tokenGive address * @param amountGive uint256 * @param expires uint256 * @param nonce uint256 * @param user address * @param v uint8 * @pa...
function testTrade( address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s, uint256 amount, address sender ) public constant returns(bool) { ...
0.4.24
/** * @dev Get the amount filled for the given order. * @param tokenGet address * @param amountGet uint256 * @param tokenGive address * @param amountGive uint256 * @param expires uint256 * @param nonce uint256 * @param user address * @return uint256 */
function amountFilled( address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint256 nonce, address user ) public constant returns (uint256) { // User should be whitelisted. require(whitelistedUsers[user]); /...
0.4.24
/** * @dev Trade balances of given tokens amounts between two users. * @param tokenGet address * @param amountGet uint256 * @param tokenGive address * @param amountGive uint256 * @param user address * @param amount uint256 */
function tradeBalances( address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, address user, uint256 amount ) private { // Calculate the constant taxes. uint256 feeMakeXfer = amount.mul(feeMake).div(1 ether); uint256 feeTakeXfer = amount.mul(f...
0.4.24
/** * @dev Validate an order hash. * @param hash bytes32 * @param user address * @param v uint8 * @param r bytes32 * @param s bytes32 * @return bool */
function validateOrderHash( bytes32 hash, address user, uint8 v, bytes32 r, bytes32 s ) private constant returns (bool) { return ( orders[user][hash] || ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user ); }
0.4.24
/** * @notice increase spend amount granted to spender * @param spender address whose allowance to increase * @param amount quantity by which to increase allowance * @return success status (always true; otherwise function will revert) */
function increaseAllowance (address spender, uint amount) virtual public returns (bool) { unchecked { mapping (address => uint) storage allowances = ERC20BaseStorage.layout().allowances[msg.sender]; uint allowance = allowances[spender]; require(allowance + amount >= allowance, 'ERC20Extended: exc...
0.8.4
/** * @inheritdoc IERC20 */
function transferFrom ( address holder, address recipient, uint amount ) override virtual public returns (bool) { uint256 currentAllowance = ERC20BaseStorage.layout().allowances[holder][msg.sender]; require(currentAllowance >= amount, 'ERC20: transfer amount exceeds allowance'); unchecked { ...
0.8.4
// @notice ContractManager will be the only contract that can add/remove contracts on the platform. // @param (address) _contractManager is the contract which can upgrade/remove contracts to platform
function enableContractManagement(address _contractManager) external returns (bool){ require(_contractManager != address(0), "Empty address"); require(boolStorage[keccak256(abi.encodePacked("owner", msg.sender))], "Not owner"); require(addressStorage[keccak256(abi.encodePacked("cont...
0.4.24
/** * @notice enable spender to spend tokens on behalf of holder * @param holder address on whose behalf tokens may be spent * @param spender recipient of allowance * @param amount quantity of tokens approved for spending */
function _approve ( address holder, address spender, uint amount ) virtual internal { require(holder != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); ERC20BaseStorage.layout().allowances[holder][spender] = amount; ...
0.8.4
/** * @notice mint tokens for given account * @param account recipient of minted tokens * @param amount quantity of tokens minted */
function _mint ( address account, uint amount ) virtual internal { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); ERC20BaseStorage.Layout storage l = ERC20BaseStorage.layout(); l.totalSupply += amount; l.balances[acco...
0.8.4
/** * @notice burn tokens held by given account * @param account holder of burned tokens * @param amount quantity of tokens burned */
function _burn ( address account, uint amount ) virtual internal { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); ERC20BaseStorage.Layout storage l = ERC20BaseStorage.layout(); uint256 balance = l.balances[account]; ...
0.8.4
/** * @notice transfer tokens from holder to recipient * @param holder owner of tokens to be transferred * @param recipient beneficiary of transfer * @param amount quantity of tokens transferred */
function _transfer ( address holder, address recipient, uint amount ) virtual internal { require(holder != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(holder, recipient, amount); ERC20...
0.8.4
/** @notice stake GWS to enter warmup @param _amount uint @return bool */
function stake( uint _amount, address _recipient ) external returns ( bool ) { if( initialStake[ _recipient ] == 0 ) { initialStake[ _recipient ] = epoch.number.add(initialUnstakeBlock); } rebase(); IERC20( GWS ).safeTransferFrom( msg.sender, address(this), _...
0.7.5
/** @notice retrieve sGWS from warmup @param _recipient address */
function claim ( address _recipient ) public { Claim memory info = warmupInfo[ _recipient ]; if ( epoch.number >= info.expiry && info.expiry != 0 ) { delete warmupInfo[ _recipient ]; IWarmup( warmupContract ).retrieve( _recipient, IsGWS( sGWS ).balanceForGons( info.gons ) ); ...
0.7.5
/** @notice forfeit sGWS in warmup and retrieve GWS */
function forfeit() external { Claim memory info = warmupInfo[ msg.sender ]; delete warmupInfo[ msg.sender ]; IWarmup( warmupContract ).retrieve( address(this), IsGWS( sGWS ).balanceForGons( info.gons ) ); IERC20( GWS ).safeTransfer( msg.sender, info.deposit ); }
0.7.5
/** @notice redeem sGWS for GWS @param _amount uint @param _trigger bool */
function unstake( uint _amount, bool _trigger ) external { require( epoch.number >= initialStake[ msg.sender ] , 'Has not reached the initial unstake block' ); if ( _trigger ) { rebase(); } IERC20( sGWS ).safeTransferFrom( msg.sender, address(this), _amount ); ...
0.7.5
/** @notice trigger rebase if epoch over */
function rebase() public { if( epoch.endBlock <= block.number ) { IsGWS( sGWS ).rebase( epoch.distribute, epoch.number ); epoch.endBlock = epoch.endBlock.add( epoch.length ); epoch.number++; if ( distributor != address(0) ) { IDistribut...
0.7.5
/** @notice sets the contract address for LP staking @param _contract address */
function setContract( CONTRACTS _contract, address _address ) external onlyManager() { if( _contract == CONTRACTS.DISTRIBUTOR ) { // 0 distributor = _address; } else if ( _contract == CONTRACTS.WARMUP ) { // 1 require( warmupContract == address( 0 ), "Warmup cannot be set mor...
0.7.5
/** * Link blockchain address with CNPJ - It can be a cliente or a supplier * The link still needs to be validated by BNDES * This method can only be called by BNDESToken contract because BNDESToken can pause. * @param cnpj Brazilian identifier to legal entities * @param idFinancialSupportAgreement contract n...
function registryLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, address addr, string memory idProofHash) onlyTokenAddress public { // Endereço não pode ter sido cadastrado anteriormente require (isAvailableAccount(addr), "Endereço não pode ter sido cadastrado a...
0.5.0
/** * Changes the original link between CNPJ and Ethereum account. * The new link still needs to be validated by BNDES. * This method can only be called by BNDESToken contract because BNDESToken can pause and because there are * additional instructions there. * @param cnpj Brazilian identifier to legal enti...
function changeAccountLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, address newAddr, string memory idProofHash) onlyTokenAddress public { address oldAddr = getBlockchainAccount(cnpj, idFinancialSupportAgreement); // Tem que haver um endereço associado a e...
0.5.0
/** * Validates the initial registry of a legal entity or the change of its registry * @param addr Ethereum address that needs to be validated * @param idProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account. * This PDF is signed with eC...
function validateRegistryLegalEntity(address addr, string memory idProofHash) public { require(isResponsibleForRegistryValidation(msg.sender), "Somente o responsável pela validação pode validar contas"); require(legalEntitiesInfo[addr].state == BlockchainAccountState.WAITING_VALIDATION, "A conta p...
0.5.0
/** * The transfer funcion follows ERC20 token signature. * Using them, it is possible to disburse money to the client, transfer from client to supplier and redeem. * @param to the Ethereum address to where the money should be sent * @param value how much BNDESToken the supplier wants to redeem */
function transfer (address to, uint256 value) public whenNotPaused returns (bool) { address from = msg.sender; require(from != to, "Não pode transferir token para si mesmo"); if (registry.isResponsibleForDisbursement(from)) { require(registry.isValidatedClient(to), "O end...
0.5.0
/** * Using this function, the Responsible for Settlement indicates that he has made the FIAT money transfer. * @param redemptionTransactionHash hash of the redeem transaction in which the FIAT money settlement occurred. * @param receiptHash hash that proof the FIAT money transfer */
function notifyRedemptionSettlement(string memory redemptionTransactionHash, string memory receiptHash) public whenNotPaused { require (registry.isResponsibleForSettlement(msg.sender), "A liquidação só não pode ser realizada pelo endereço que submeteu a transação"); require (registry.isVali...
0.5.0
/** * Changes the original link between CNPJ and Ethereum account. * The new link still needs to be validated by BNDES. * IMPORTANT: The BNDESTOKENs are transfered from the original to the new Ethereum address * @param cnpj Brazilian identifier to legal entities * @param idFinancialSupportAgreement contract...
function changeAccountLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, string memory idProofHash) public whenNotPaused { address oldAddr = registry.getBlockchainAccount(cnpj, idFinancialSupportAgreement); address newAddr = msg.sender; re...
0.5.0
/** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */
function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } e...
0.5.17
/** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed ...
0.5.17
/** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */
function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow fai...
0.5.17
/** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize co...
function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accru...
0.5.17
/** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce rese...
0.5.17
//mint a @param number of NFTs in presale
function presaleMint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable { State saleState_ = saleState(); require(saleState_ != State.NoSale, "Sale in not open yet!"); require(saleState_ != State.PublicSale, "Presale has closed, Check out Public Sale...
0.8.7
//mint a @param number of NFTs in public sale
function publicSaleMint(uint256 number) public payable { State saleState_ = saleState(); require(saleState_ == State.PublicSale, "Public Sale in not open yet!"); require(numberOfTotalTokens + number <= maxTotalTokens - (maxReservedMintsTeam + maxReservedMintsGiveaways - _reservedMintsTeam - _...
0.8.7
//reserved NFTs for creator
function reservedMintTeam(uint number, address recipient) public onlyOwner { require(_reservedMintsTeam + number <= maxReservedMintsTeam, "Not enough Reserved NFTs left to mint.."); for (uint i = 0; i < number; i++) { _safeMint(recipient, tokenId()); mintsPerAddress[recipie...
0.8.7
//retrieve all funds recieved from minting
function withdraw() public onlyOwner { uint256 balance = accountBalance(); require(balance > 0, 'No Funds to withdraw, Balance is 0'); _withdraw(shareholder5, (balance * 20) / 100); _withdraw(shareholder4, (balance * 20) / 100); _withdraw(shareholder3, (balance * 2...
0.8.7
//see current state of sale //see the current state of the sale
function saleState() public view returns(State){ if (presaleLaunchTime == 0 || paused == true) { return State.NoSale; } else if (publicSaleLaunchTime == 0) { return State.Presale; } else { return State.PublicSale; } }
0.8.7
//gets the cost of current mint
function mintCost(uint number) public view returns(uint) { require(0 < number && number < 6, "Incorrect Amount!"); State saleState_ = saleState(); if (saleState_ == State.NoSale || saleState_ == State.Presale) { if (number == 1) { return 0.04 ether; ...
0.8.7
//Exclude from draw array
function ExcludeFEA (address _address) private { for (uint256 j = 0; j < _DrawHolders.length; j++) { if( _DrawHolders[j] == _address){ _DrawHolders[j] = _DrawHolders[_DrawHolders.length - 1]; _ExistInDrawHolders[_address] = false; _Dr...
0.8.7
//Called when no more ETH is in the contract and everything needs to be manually reset.
function minter(string _currency, uint128 _Multiplier) { //,uint8 _DecimalPlaces // CONSTRUCTOR Currency=_currency; Multiplier = _Multiplier; // can't add new contracts here as it gives out of gas messages. Too much code. }
0.4.16
//****************************// // Constant functions (Ones that don't write to the blockchain)
function StaticEthAvailable() constant returns (uint128) { /** @dev Returns the total amount of eth that can be sent to buy StatiCoins * @return amount of Eth */ return StaticEthAvailable(cast(Risk.totalSupply()), cast(this.balance)); }
0.4.16
//****************************// // Only owner can access the following functions
function setFee(uint128 _newFee) onlyOwner { /** @dev Allows the minting fee to be changed, only owner can modify * Fee is only charged on coin creation * @param _newFee Size of new fee * return nothing */ mintFee=_newFee; }
0.4.16
//****************************// // Only Pricer can access the following function
function PriceReturn(uint _TransID,uint128 _Price) onlyPricer { /** @dev Return function for the Pricer contract only. Controls melting and minting of new coins. * @param _TransID Tranasction ID issued by the minter. * @param _Price Quantity of Base currency per ETH delivered by the Pr...
0.4.16
/** factory role config nft clone * * @param localNFT nft on this chain * @param destNFT nft on L2 * @param originNFTChainId origin NFT ChainId * @param destGasLimit L2 gas limit */
function configNFT(address localNFT, address destNFT, uint256 originNFTChainId, uint32 destGasLimit) external payable onlyRole(NFT_FACTORY_ROLE) { uint256 localChainId = getChainID(); require((originNFTChainId == DEST_CHAINID || originNFTChainId == localChainId), "ChainId not supported"); ...
0.8.9
/** deposit nft into L1 deposit * * @param localNFT nft on this chain * @param destTo owns nft on L2 * @param id nft id * @param nftStandard nft type * @param destGasLimit L2 gas limit */
function depositTo(address localNFT, address destTo, uint256 id, nftenum nftStandard, uint32 destGasLimit) external onlyEOA() payable { require(clone[localNFT] != address(0), "NFT not config."); require(isDeposit[localNFT][id] == false, "Don't redeposit."); uint32 minGasLimit = ...
0.8.9
/** deposit messenger * * @param chainId L2 chainId * @param destNFT nft on L2 * @param from msg.sender * @param destTo owns nft on L2 * @param id nft id * @param amount amount * @param nftStandard nft type * @param destGasLimit L2 gas limit */
function _messenger(uint256 chainId, address destNFT, address from, address destTo, uint256 id, uint256 amount, uint8 nftStandard, uint32 destGasLimit) internal { bytes memory message = abi.encodeWithSelector( ICrollDomain.finalizeDeposit.selector, destNFT, from, ...
0.8.9
/** clone nft * * @param _localNFT nft * @param _destFrom owns nft on l2 * @param _localTo give to * @param id nft id * @param _amount nft amount * @param nftStandard nft type */
function finalizeDeposit(address _localNFT, address _destFrom, address _localTo, uint256 id, uint256 _amount, nftenum nftStandard) external onlyFromCrossDomainAccount(destNFTBridge) { if(nftenum.ERC721 == nftStandard) { if(isDeposit[_localNFT][id]){ INFTDeposit(localNFTD...
0.8.9
/** hack rollback * * @param nftStandard nft type * @param _localNFT nft * @param ids tokenid */
function rollback(nftenum nftStandard, address _localNFT, uint256[] memory ids) public onlyRole(ROLLBACK_ROLE) { for( uint256 index; index < ids.length; index++ ){ uint256 id = ids[index]; address _depositUser = depositUser[_localNFT][id]; requ...
0.8.9
/** * Fallback and entrypoint for deposits. */
function() public payable isHuman { if (msg.value == 0) { collectPayoutForAddress(msg.sender); } else { uint refId = 1; address referrer = bytesToAddress(msg.data); if (investorToDepostIndex[referrer].isExist) { refId = investorToDepostIndex[referrer].id; } d...
0.4.25
// Add a new staking token to the pool. Can only be called by the manager.
function add(uint256 _allocPoint, IERC20 _stakingToken, bool _isLP, bool _withUpdate) external { require(msg.sender == address(manager), "fund: sender is not manager"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.nu...
0.7.6
/** * Perform the Midnight Run */
function doMidnightRun() public isHuman { require(now>nextPrizeTime , "Not yet"); // set the next prize time to the next payout time (MidnightRun) nextPrizeTime = getNextPayoutTime(); if (currentPrizeStakeID > 5) { uint toPay = midnightPrize; midnightPrize = 0; if (toPay >...
0.4.25
// move LP tokens from one farm to another. only callable by Manager. // tx.origin is user EOA, msg.sender is the Manager.
function move(uint256 _pid) external { require(msg.sender == address(manager), "move: sender is not manager"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][tx.origin]; updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accERC20Pe...
0.7.6
// Deposit LP tokens to Farm for ERC20 allocation. // can come from manager or user address directly; in either case, tx.origin is the user. // In the case the call is coming from the mananger, msg.sender is the manager.
function deposit(uint256 _pid, uint256 _amount) external { require(manager.getPaused()==false, "deposit: farm paused"); address userAddress = ((msg.sender == address(manager)) ? tx.origin : msg.sender); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][us...
0.7.6
// Distribute rewards and start unstake period.
function withdraw(uint256 _pid) external { require(manager.getPaused()==false, "withdraw: farm paused"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0, "withdraw: amount must be greater than 0"); require(u...
0.7.6
// unstake LP tokens from Farm. if done within "unstakeEpochs" days, apply burn.
function unstake(uint256 _pid) external { require(manager.getPaused()==false, "unstake: farm paused"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.withdrawTime > 0, "unstake: user is not unstaking"); updatePool(_pi...
0.7.6
// claim LP tokens from Farm.
function claim(uint256 _pid) external { require(manager.getPaused() == false, "claim: farm paused"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0, "claim: amount is equal to 0"); require(user.withdrawTime...
0.7.6
/** * Initialize the farming contract. This is called only once upon farm creation and the FarmGenerator * ensures the farm has the correct paramaters * * @param _rewardToken Instance of reward token contract * @param _amount Total sum of reward * @param _lpToken Instance...
function init( IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, uint256 _blockReward, uint256 _startBlock, uint256 _endBlock, uint256 _bonusEndBlock, uint256 _bonus ) external { require(msg.sender == address(farmGenerator), "FOR...
0.6.10
/** * Updates pool information to be up to date to the current block */
function updatePool() public { if (block.number <= farmInfo.lastRewardBlock) { return; } uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this)); if (lpSupply == 0) { farmInfo.lastRewardBlock = block.number < farmInfo.endBlock ? block.number : farmInfo....
0.6.10
/** * Deposit LP token function for msg.sender * * @param _amount the total deposit amount */
function deposit(uint256 _amount) external { UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt); _safeRewardTransfer(msg.sender, pending); ...
0.6.10
/** * Withdraw LP token function for msg.sender * * @param _amount the total withdrawable amount */
function withdraw(uint256 _amount) external { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "INSUFFICIENT"); updatePool(); if (user.amount == _amount && _amount > 0) { factory.userLeftFarm(msg.sender); farmInfo.numFarmers--; ...
0.6.10