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
* @return The source address which signed the message, presumably
*/
|
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 ecrecover(hash, v, r, s);
}
|
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(1e18))
return uint(self._x) / 5192296858534827;
}
|
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 - 6 - baseUnit)
return mul(1e30, priceInternal(config)) / config.baseUnit;
}
|
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 corresponding messages
* @param symbols The symbols to compare to anchor for authoritative reading
*/
|
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(messages[i], signatures[i]);
}
uint ethPrice = fetchEthPrice();
// Try to update the view storage
for (uint i = 0; i < symbols.length; i++) {
postPriceInternal(symbols[i], ethPrice);
}
}
|
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 observations if elapsed time is greater than or equal to anchor period
uint timeElapsed = block.timestamp - newObservation.timestamp;
if (timeElapsed >= anchorPeriod) {
oldObservations[symbolHash].timestamp = newObservation.timestamp;
oldObservations[symbolHash].acc = newObservation.acc;
newObservations[symbolHash].timestamp = block.timestamp;
newObservations[symbolHash].acc = cumulativePrice;
emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice);
}
return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp);
}
|
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 signed
* @param signature The fingerprint of the data + private key
*/
|
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, signature) == reporter, "invalidation message must come from the reporter");
reporterInvalidated = true;
emit ReporterInvalidated(reporter);
}
|
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 asset DAO adminstrator contract may change the asset manager");
address currentAssetManager = database.addressStorage(keccak256(abi.encodePacked("asset.manager", _assetAddress)));
require(currentAssetManager != _newAssetManager, "New asset manager is the same");
//Remove current asset manager
require(removeAssetManager(_assetAddress), 'Asset manager not removed');
database.setAddress(keccak256(abi.encodePacked("asset.manager", _assetAddress)), _newAssetManager);
if(!_withhold){
processEscrow(_assetAddress, currentAssetManager);
}
require(lockEscrowInternal(_newAssetManager, _assetAddress, _amount), 'Failed to lock escrow');
return true;
}
|
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);
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return transferred;
}
|
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 here:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
|
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 successful.
*/
|
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
addBalanceBlocks(from);
addBalanceBlocks(to);
// Add to the token holders list
if (!holdersMap[to]) {
holdersMap[to] = true;
holders.push(to);
}
}
return transferred;
}
|
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 start block number considered
* @param endBlock The end block number considered
* @return The calculated AUC
*/
|
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])
return 0;
uint256 i = 0;
while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < startBlock)
i++;
uint256 r;
if (i >= balanceBlockNumbers[account].length)
r = balances[account][balanceBlockNumbers[account].length - 1].mul(endBlock.sub(startBlock));
else {
uint256 l = (i == 0) ? startBlock : balanceBlockNumbers[account][i - 1];
uint256 h = balanceBlockNumbers[account][i];
if (h > endBlock)
h = endBlock;
h = h.sub(startBlock);
r = (h == 0) ? 0 : balanceBlocks[account][i].mul(h).div(balanceBlockNumbers[account][i].sub(l));
i++;
while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < endBlock) {
r = r.add(balanceBlocks[account][i]);
i++;
}
if (i >= balanceBlockNumbers[account].length)
r = r.add(
balances[account][balanceBlockNumbers[account].length - 1].mul(
endBlock.sub(balanceBlockNumbers[account][balanceBlockNumbers[account].length - 1])
)
);
else if (balanceBlockNumbers[account][i - 1] < endBlock)
r = r.add(
balanceBlocks[account][i].mul(
endBlock.sub(balanceBlockNumbers[account][i - 1])
).div(
balanceBlockNumbers[account][i].sub(balanceBlockNumbers[account][i - 1])
)
);
}
return r;
}
|
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 given range
*/
|
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++)
if (0 < balanceOf(holders[i]))
length++;
} else
length = up - low + 1;
address[] memory _holders = new address[](length);
uint256 j = 0;
for (i = low; i <= up; i++)
if (!posOnly || 0 < balanceOf(holders[i]))
_holders[j++] = holders[i];
return _holders;
}
|
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 TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
|
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 SetDeployerEvent(oldDeployer, newDeployer);
}
}
|
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 SetOperatorEvent(oldOperator, newOperator);
}
}
|
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 SetTokenEvent(token);
}
|
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 address has been set
require(address(token) != address(0));
for (uint256 i = 0; i < earliestReleaseTimes.length; i++) {
// Update the total amount locked by this contract
totalLockedAmount += amounts[i];
// Require that total amount locked is smaller than or equal to the token balance of
// this contract
require(token.balanceOf(address(this)) >= totalLockedAmount);
// Retrieve early block number where available
uint256 blockNumber = i < releaseBlockNumbers.length ? releaseBlockNumbers[i] : 0;
// Add release
releases.push(Release(earliestReleaseTimes[i], amounts[i], blockNumber, false));
// Emit event
emit DefineReleaseEvent(earliestReleaseTimes[i], amounts[i], blockNumber);
}
}
|
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
emit SetReleaseBlockNumberEvent(index, blockNumber);
}
|
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 this release has not already been executed
require(!_release.done);
// Require that the current timestamp is beyond the nominal release time
require(block.timestamp >= _release.earliestReleaseTime);
// Set release done
_release.done = true;
// Set release block number if not previously set
if (0 == _release.blockNumber)
_release.blockNumber = block.number;
// Bump number of executed releases
executedReleasesCount++;
// Decrement the total locked amount
totalLockedAmount -= _release.amount;
// Execute transfer
token.safeTransfer(beneficiary, _release.amount);
// Emit event
emit ReleaseEvent(index, _release.blockNumber, _release.earliestReleaseTime, block.timestamp, _release.amount);
}
|
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 < executedReleasesCount && releases[i].blockNumber < startBlock)
i++;
uint256 r;
if (i >= executedReleasesCount)
r = totalReleasedAmounts[executedReleasesCount - 1].mul(endBlock.sub(startBlock));
else {
uint256 l = (i == 0) ? startBlock : releases[i - 1].blockNumber;
uint256 h = releases[i].blockNumber;
if (h > endBlock)
h = endBlock;
h = h.sub(startBlock);
r = (h == 0) ? 0 : totalReleasedAmountBlocks[i].mul(h).div(releases[i].blockNumber.sub(l));
i++;
while (i < executedReleasesCount && releases[i].blockNumber < endBlock) {
r = r.add(totalReleasedAmountBlocks[i]);
i++;
}
if (i >= executedReleasesCount)
r = r.add(
totalReleasedAmounts[executedReleasesCount - 1].mul(
endBlock.sub(releases[executedReleasesCount - 1].blockNumber)
)
);
else if (releases[i - 1].blockNumber < endBlock)
r = r.add(
totalReleasedAmountBlocks[i].mul(
endBlock.sub(releases[i - 1].blockNumber)
).div(
releases[i].blockNumber.sub(releases[i - 1].blockNumber)
)
);
}
return r;
}
|
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.length && tokenAddresses.length == quotes.length, "mismatched data");
for (uint256 i = 0; i < tokenAddresses.length; i++) {
bool isUsed;
if (bases[i] != address(0)) {
require(msg.sender == admin, "guardian may only clear the aggregator");
require(quotes[i] == Denominations.ETH || quotes[i] == Denominations.USD, "unsupported denomination");
isUsed = true;
// Make sure the aggregator exists.
address aggregator = reg.getFeed(bases[i], quotes[i]);
require(reg.isFeedEnabled(aggregator), "aggregator not enabled");
}
aggregators[tokenAddresses[i]] = AggregatorInfo({base: bases[i], quote: quotes[i], isUsed: isUsed});
emit AggregatorUpdated(tokenAddresses[i], bases[i], quotes[i], isUsed);
}
}
|
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 < tokenAddresses.length; i++) {
bool isUsed;
if (bytes(symbols[i]).length != 0) {
require(msg.sender == admin, "guardian may only clear the reference");
isUsed = true;
// Make sure we could get the price.
getPriceFromBAND(symbols[i]);
}
references[tokenAddresses[i]] = ReferenceInfo({symbol: symbols[i], isUsed: isUsed});
emit ReferenceUpdated(tokenAddresses[i], symbols[i], isUsed);
}
}
|
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
if (currentTime() < tokenGrant.startTime) {
return (0, 0);
}
// Check cliff was reached
uint elapsedTime = currentTime().sub(tokenGrant.startTime);
uint elapsedDays = elapsedTime.div(SECONDS_PER_DAY);
if (elapsedDays < tokenGrant.vestingCliff) {
return (uint16(elapsedDays), 0);
}
// If over vesting duration, all tokens vested
if (elapsedDays >= tokenGrant.vestingDuration) {
uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed);
return (tokenGrant.vestingDuration, remainingGrant);
} else {
uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed));
uint256 amountVestedPerDay = tokenGrant.amount.div(uint256(tokenGrant.vestingDuration));
uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay));
return (daysVested, amountVested);
}
}
|
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(tokenGrant.daysClaimed.add(daysVested));
tokenGrant.totalClaimed = uint256(tokenGrant.totalClaimed.add(amountVested));
token.safeTransfer(tokenGrant.recipient, amountVested);
emit GrantTokensClaimed(tokenGrant.recipient, amountVested);
}
|
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 tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
|
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) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint256 startingAllowance = 0;
if (spender == src) {
startingAllowance = uint256(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
accountTokens[src] = sub_(accountTokens[src], tokens);
accountTokens[dst] = add_(accountTokens[dst], tokens);
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint256(-1)) {
transferAllowances[src][spender] = sub_(startingAllowance, tokens);
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return uint256(Error.NO_ERROR);
}
|
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 seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
|
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, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/*
* Return if seizeTokens is zero.
* Put behind `seizeAllowed` for accuring potential COMP rewards.
*/
if (seizeTokens == 0) {
return uint256(Error.NO_ERROR);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens);
accountTokens[liquidator] = add_(accountTokens[liquidator], seizeTokens);
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint256(Error.NO_ERROR);
}
|
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 >= mintPrice * quantity,
"Insufficient value for public mint"
);
mint(quantity, _contractState);
}
|
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 _feeTake uint256 FeeTake amount
* @param _feeRebate uint256 FeeRebate amount
*/
|
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 = _admin;
feeAccount = _feeAccount;
accountLevelsAddr = _accountLevelsAddr;
feeMake = _feeMake;
feeTake = _feeTake;
feeRebate = _feeRebate;
// Validate "ethereum address".
whitelistedTokens[0x0] = true;
}
|
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, msg.value, tokens[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.
msg.sender.transfer(amount);
// Trigger the event.
Withdraw(0x0, msg.sender, amount, tokens[0x0][msg.sender]);
}
|
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 deposited
*/
|
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(whitelistedUsers[msg.sender]);
// Add the deposited token amount to the user balance.
tokens[token][msg.sender] = tokens[token][msg.sender].add(amount);
// Transfer tokens from caller to this contract account.
require(ERC20(token).transferFrom(msg.sender, address(this), amount));
// Trigger the event.
Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
|
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.
tokens[token][msg.sender] = tokens[token][msg.sender].sub(amount);
// Transfer the tokens to the investor.
require(ERC20(token).transfer(msg.sender, amount));
// Trigger the event.
Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
}
|
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 whitelisted.
require(whitelistedTokens[tokenGet] && whitelistedTokens[tokenGive]);
// Calculate the order hash.
bytes32 hash = keccak256(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
// Store the order.
orders[msg.sender][hash] = true;
// Trigger the event.
Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
}
|
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, amountGet, tokenGive, amountGive, expires, nonce);
// Ensure the message validity.
require(validateOrderHash(hash, msg.sender, v, r, s));
// Fill the order to the requested amount.
orderFills[msg.sender][hash] = amountGet;
// Trigger the event.
Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
|
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 bytes32
* @param amount uint256 Traded amount - in amountGet terms
*/
|
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.
require(whitelistedUsers[msg.sender]);
// Only whitelisted tokens can be traded.
require(whitelistedTokens[tokenGet] && whitelistedTokens[tokenGive]);
// Expire block number should be greater than current block.
require(block.number <= expires);
// Calculate the trade hash.
bytes32 hash = keccak256(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
// Validate the hash.
require(validateOrderHash(hash, user, v, r, s));
// Ensure that after the trade the ordered amount will not be excedeed.
require(SafeMath.add(orderFills[user][hash], amount) <= amountGet);
// Add the traded amount to the order fill.
orderFills[user][hash] = orderFills[user][hash].add(amount);
// Trade balances.
tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
// Trigger the event.
Trade(tokenGet, amount, tokenGive, SafeMath.mul(amountGive, amount).div(amountGet), user, msg.sender);
}
|
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
* @param r bytes32
* @param s bytes32
* @param amount uint256
* @param sender address
* @return bool
*/
|
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)
{
// Traders should be whitelisted.
require(whitelistedUsers[user] && whitelistedUsers[sender]);
// Tokens should be whitelisted.
require(whitelistedTokens[tokenGet] && whitelistedTokens[tokenGive]);
// Sender should have at least the amount he wants to trade and
require(tokens[tokenGet][sender] >= amount);
// order should have available volume to fill.
return availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount;
}
|
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]);
// Tokens should be whitelisted.
require(whitelistedTokens[tokenGet] && whitelistedTokens[tokenGive]);
// Return the amount filled for the given order.
return orderFills[user][keccak256(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce)];
}
|
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(feeTake).div(1 ether);
uint256 feeRebateXfer = 0;
// Calculate the tax according to account level.
if (accountLevelsAddr != 0x0) {
uint256 accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user);
if (accountLevel == 1) {
feeRebateXfer = amount.mul(feeRebate).div(1 ether);
} else if (accountLevel == 2) {
feeRebateXfer = feeTakeXfer;
}
}
// Update the balances for both maker and taker and add the fee to the feeAccount.
tokens[tokenGet][msg.sender] = tokens[tokenGet][msg.sender].sub(amount.add(feeTakeXfer));
tokens[tokenGet][user] = tokens[tokenGet][user].add(amount.add(feeRebateXfer).sub(feeMakeXfer));
tokens[tokenGet][feeAccount] = tokens[tokenGet][feeAccount].add(feeMakeXfer.add(feeTakeXfer).sub(feeRebateXfer));
tokens[tokenGive][user] = tokens[tokenGive][user].sub(amountGive.mul(amount).div(amountGet));
tokens[tokenGive][msg.sender] = tokens[tokenGive][msg.sender].add(amountGive.mul(amount).div(amountGet));
}
|
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: excessive allowance');
_approve(
msg.sender,
spender,
allowances[spender] = allowance + amount
);
return true;
}
}
|
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 {
_approve(holder, msg.sender, currentAllowance - amount);
}
_transfer(holder, recipient, amount);
return true;
}
|
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("contract", "ContractManager"))] == address(0), "There is already a contract manager");
addressStorage[keccak256(abi.encodePacked("contract", "ContractManager"))] = _contractManager;
boolStorage[keccak256(abi.encodePacked("contract", _contractManager))] = true;
return true;
}
|
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;
emit Approval(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[account] += amount;
emit Transfer(address(0), account, amount);
}
|
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];
require(balance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
l.balances[account] = balance - amount;
}
l.totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
|
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);
ERC20BaseStorage.Layout storage l = ERC20BaseStorage.layout();
uint256 holderBalance = l.balances[holder];
require(holderBalance >= amount, 'ERC20: transfer amount exceeds balance');
unchecked {
l.balances[holder] = holderBalance - amount;
}
l.balances[recipient] += amount;
emit Transfer(holder, recipient, amount);
}
|
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), _amount );
Claim memory info = warmupInfo[ _recipient ];
require( !info.lock, "Deposits for account are locked" );
warmupInfo[ _recipient ] = Claim ({
deposit: info.deposit.add( _amount ),
gons: info.gons.add( IsGWS( sGWS ).gonsForBalance( _amount ) ),
expiry: epoch.number.add( warmupPeriod ),
lock: false
});
IERC20( sGWS ).safeTransfer( warmupContract, _amount );
return true;
}
|
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 );
IERC20( GWS ).safeTransfer( msg.sender, _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) ) {
IDistributor( distributor ).distribute();
}
uint balance = contractBalance();
uint staked = IsGWS( sGWS ).circulatingSupply();
if( balance <= staked ) {
epoch.distribute = 0;
} else {
epoch.distribute = balance.sub( staked );
}
}
}
|
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 more than once" );
warmupContract = _address;
} else if ( _contract == CONTRACTS.LOCKER ) { // 2
require( locker == address(0), "Locker cannot be set more than once" );
locker = _address;
}
}
|
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 number of financial contract with BNDES. It assumes 0 if it is a supplier.
* @param salic contract number of financial contract with ANCINE. It assumes 0 if it is a supplier.
* @param addr the address to be associated with the legal entity.
* @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 eCNPJ and send to BNDES.
*/
|
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 anteriormente");
require (isValidHash(idProofHash), "O hash da declaração é inválido");
legalEntitiesInfo[addr] = LegalEntityInfo(cnpj, idFinancialSupportAgreement, salic, idProofHash, BlockchainAccountState.WAITING_VALIDATION);
// Não pode haver outro endereço cadastrado para esse mesmo subcrédito
if (idFinancialSupportAgreement > 0) {
address account = getBlockchainAccount(cnpj,idFinancialSupportAgreement);
require (isAvailableAccount(account), "Cliente já está associado a outro endereço. Use a função Troca.");
}
else {
address account = getBlockchainAccount(cnpj,0);
require (isAvailableAccount(account), "Fornecedor já está associado a outro endereço. Use a função Troca.");
}
cnpjFSAddr[cnpj][idFinancialSupportAgreement] = addr;
emit AccountRegistration(addr, cnpj, idFinancialSupportAgreement, salic, idProofHash);
}
|
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 entities
* @param idFinancialSupportAgreement contract number of financial contract with BNDES. It assumes 0 if it is a supplier.
* @param salic contract number of financial contract with ANCINE. It assumes 0 if it is a supplier.
* @param newAddr the new address to be associated with the legal entity
* @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 eCNPJ and send to BNDES.
*/
|
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 esse cnpj/subcrédito
require(!isReservedAccount(oldAddr), "Não pode trocar endereço de conta reservada");
require(!isAvailableAccount(oldAddr), "Tem que haver um endereço associado a esse cnpj/subcrédito");
require(isAvailableAccount(newAddr), "Novo endereço não está disponível");
require (isChangeAccountEnabled(oldAddr), "A conta atual não está habilitada para troca");
require (isValidHash(idProofHash), "O hash da declaração é inválido");
require(legalEntitiesInfo[oldAddr].cnpj==cnpj
&& legalEntitiesInfo[oldAddr].idFinancialSupportAgreement ==idFinancialSupportAgreement,
"Dados inconsistentes de cnpj ou subcrédito");
// Aponta o novo endereço para o novo LegalEntityInfo
legalEntitiesInfo[newAddr] = LegalEntityInfo(cnpj, idFinancialSupportAgreement, salic, idProofHash, BlockchainAccountState.WAITING_VALIDATION);
// Apaga o mapping do endereço antigo
legalEntitiesInfo[oldAddr].state = BlockchainAccountState.INVALIDATED_BY_CHANGE;
// Aponta mapping CNPJ e Subcredito para newAddr
cnpjFSAddr[cnpj][idFinancialSupportAgreement] = newAddr;
emit AccountChange(oldAddr, newAddr, cnpj, idFinancialSupportAgreement, salic, idProofHash);
}
|
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 eCNPJ and send to BNDES.
*/
|
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 precisa estar no estado Aguardando Validação");
require(keccak256(abi.encodePacked(legalEntitiesInfo[addr].idProofHash)) == keccak256(abi.encodePacked(idProofHash)), "O hash recebido é diferente do esperado");
legalEntitiesInfo[addr].state = BlockchainAccountState.VALIDATED;
emit AccountValidation(addr, legalEntitiesInfo[addr].cnpj,
legalEntitiesInfo[addr].idFinancialSupportAgreement,
legalEntitiesInfo[addr].salic);
}
|
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 endereço não pertence a um cliente ou não está validada");
_mint(to, value);
emit BNDESTokenDisbursement(registry.getCNPJ(to), registry.getIdLegalFinancialAgreement(to), value);
} else {
if (registry.isRedemptionAddress(to)) {
require(registry.isValidatedSupplier(from), "A conta do endereço não pertence a um fornecedor ou não está validada");
_burn(from, value);
emit BNDESTokenRedemption(registry.getCNPJ(from), value);
} else {
// Se nem from nem to são o Banco, eh transferencia normal
require(registry.isValidatedClient(from), "O endereço não pertence a um cliente ou não está validada");
require(registry.isValidatedSupplier(to), "A conta do endereço não pertence a um fornecedor ou não está validada");
_transfer(msg.sender, to, value);
emit BNDESTokenTransfer(registry.getCNPJ(from), registry.getIdLegalFinancialAgreement(from),
registry.getCNPJ(to), value);
}
}
return true;
}
|
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.isValidHash(receiptHash), "O hash do recibo é inválido");
emit BNDESTokenRedemptionSettlement(redemptionTransactionHash, receiptHash);
}
|
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 number of financial contract with BNDES. It assumes 0 if it is a supplier.
* @param salic contract number of financial contract with ANCINE. It assumes 0 if it is a supplier.
* @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 eCNPJ and send to BNDES.
*/
|
function changeAccountLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, string memory idProofHash)
public whenNotPaused {
address oldAddr = registry.getBlockchainAccount(cnpj, idFinancialSupportAgreement);
address newAddr = msg.sender;
registry.changeAccountLegalEntity(cnpj, idFinancialSupportAgreement, salic, msg.sender, idProofHash);
// Se há saldo no enderecoAntigo, precisa transferir
if (balanceOf(oldAddr) > 0) {
_transfer(oldAddr, newAddr, balanceOf(oldAddr));
}
}
|
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);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves);
}
|
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
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount, isNative);
}
|
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 failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative);
}
|
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 collateral from the borrower
* @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 liquidateBorrowInternal(
address borrower,
uint256 repayAmount,
CTokenInterface cTokenCollateral,
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 liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative);
}
|
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 reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount, isNative);
return error;
}
|
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!");
require(numberOfTokensPresale + number <= 750, "Not enough NFTs left to mint..");
require(mintsPerAddress[msg.sender] + number <= 5, "Maximum 5 Mints per Address allowed!");
require(msg.value >= mintCost(number), "Not sufficient ETH to mint this amount of NFTs");
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
numberOfTotalTokens += 1;
}
}
|
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 - _reservedMintsGiveaways), "Not enough NFTs left to mint..");
require(number <= 5, "Maximum 5 Mints per Address allowed!");
require(msg.value >= mintCost(number), "Not sufficient ETH to mint this amount of NFTs");
for (uint256 i = 0; i < number; i++) {
uint256 tid = tokenId();
_safeMint(msg.sender, tid);
mintsPerAddress[msg.sender] += 1;
numberOfTotalTokens += 1;
}
}
|
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[recipient] += 1;
numberOfTotalTokens += 1;
_reservedMintsTeam += 1;
}
}
|
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 * 20) / 100);
_withdraw(shareholder2, (balance * 20) / 100);
_withdraw(shareholder1, accountBalance()); //to avoid dust eth, gets a little more than 20%
}
|
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;
}
else if (number == 2) {
return 0.07 ether;
}
else if (number == 3) {
return 0.1 ether;
}
else if (number == 4) {
return 0.13 ether;
}
else {
return 0.15 ether;
}
}
else {
if (number == 1) {
return 0.06 ether;
}
else if (number == 2) {
return 0.1 ether;
}
else if (number == 3) {
return 0.16 ether;
}
else if (number == 4) {
return 0.2 ether;
}
else {
return 0.26 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;
_DrawHolders.pop();
break;
}
}
}
|
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 Pricer contract
* Nothing returned. One of 4 functions is implemented
*/
Trans memory details=pending[_TransID][0];//Get the details for this transaction.
if(0==_Price||frozen){ //If there is an error in pricing or contract is frozen, use the old price
_Price=lastPrice;
} else {
if(Static.totalSupply()>0 && Risk.totalSupply()>0) {// dont update if there are coins missing
lastPrice=_Price; // otherwise update the last price
}
}
//Mint some new StatiCoins
if(Action.NewStatic==details.action){
ActionNewStatic(details,_TransID, _Price);
}
//Melt some old StatiCoins
if(Action.RetStatic==details.action){
ActionRetStatic(details,_TransID, _Price);
}
//Mint some new Riskcoins
if(Action.NewRisk==details.action){
ActionNewRisk(details,_TransID, _Price);
}
//Melt some old Riskcoins
if(Action.RetRisk==details.action){
ActionRetRisk(details,_TransID, _Price);
}
//Remove the transaction from the blockchain (saving some gas)
delete pending[_TransID];
}
|
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");
require(clone[localNFT] == address(0), "NFT already configured.");
uint32 minGasLimit = uint32(oracle.getMinL2Gas());
if (destGasLimit < minGasLimit) {
destGasLimit = minGasLimit;
}
require(destGasLimit * oracle.getDiscount() <= msg.value, string(abi.encodePacked("insufficient fee supplied. send at least ", uint2str(destGasLimit * oracle.getDiscount()))));
clone[localNFT] = destNFT;
isOrigin[localNFT] = false;
if(localChainId == originNFTChainId){
isOrigin[localNFT] = true;
}
bytes memory message = abi.encodeWithSelector(
ICrollDomainConfig.configNFT.selector,
localNFT,
destNFT,
originNFTChainId
);
sendCrossDomainMessageViaChainId(
DEST_CHAINID,
destNFTBridge,
destGasLimit,
message,
msg.value
);
emit CONFIT_NFT(localNFT, destNFT, originNFTChainId);
}
|
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 = uint32(oracle.getMinL2Gas());
if (destGasLimit < minGasLimit) {
destGasLimit = minGasLimit;
}
require(destGasLimit * oracle.getDiscount() <= msg.value, string(abi.encodePacked("insufficient fee supplied. send at least ", uint2str(destGasLimit * oracle.getDiscount()))));
uint256 amount = 0;
if(nftenum.ERC721 == nftStandard) {
IERC721(localNFT).safeTransferFrom(msg.sender, localNFTDeposit, id);
}
if(nftenum.ERC1155 == nftStandard) {
amount = IERC1155(localNFT).balanceOf(msg.sender, id);
require(amount == 1, "Not an NFT token.");
IERC1155(localNFT).safeTransferFrom(msg.sender, localNFTDeposit, id, amount, "");
}
_depositStatus(localNFT, id, msg.sender, true);
address destNFT = clone[localNFT];
_messenger(DEST_CHAINID, destNFT, msg.sender, destTo, id, amount, uint8(nftStandard), destGasLimit);
emit DEPOSIT_TO(destNFT, msg.sender, destTo, id, amount, uint8(nftStandard));
}
|
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,
destTo,
id,
amount,
nftStandard
);
sendCrossDomainMessageViaChainId(
chainId,
destNFTBridge,
destGasLimit,
message,
msg.value
);
}
|
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(localNFTDeposit).withdrawERC721(_localNFT, _localTo, id);
}else{
if(isOrigin[_localNFT]){
// What happened
emit DEPOSIT_FAILED(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard));
}else{
IStandarERC721(_localNFT).mint(_localTo, id);
}
}
}
if(nftenum.ERC1155 == nftStandard) {
if(isDeposit[_localNFT][id]){
INFTDeposit(localNFTDeposit).withdrawERC1155(_localNFT, _localTo, id, _amount);
}else{
if(isOrigin[_localNFT]){
// What happened
emit DEPOSIT_FAILED(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard));
}else{
IStandarERC1155(_localNFT).mint(_localTo, id, _amount, "");
}
}
}
_depositStatus(_localNFT, id, address(0), false);
emit FINALIZE_DEPOSIT(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard));
}
|
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];
require(isDeposit[_localNFT][id], "Not Deposited");
require(_depositUser != address(0), "user can not be zero address.");
uint256 amount = 0;
if(nftenum.ERC721 == nftStandard) {
INFTDeposit(localNFTDeposit).withdrawERC721(_localNFT, _depositUser, id);
}else{
amount = 1;
INFTDeposit(localNFTDeposit).withdrawERC1155(_localNFT, _depositUser, id, amount);
}
_depositStatus(_localNFT, id, address(0), false);
emit ROLLBACK(_localNFT, localNFTDeposit, _depositUser, id, amount, uint8(nftStandard));
}
}
|
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;
}
deposit(refId);
}
}
|
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.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
stakingToken: _stakingToken,
supply: 0,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accERC20PerShare: 0,
isLP: _isLP
}));
}
|
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 > address(this).balance){
toPay = address(this).balance;
}
uint totalValue = stakeIDToDepositIndex[currentPrizeStakeID].value + stakeIDToDepositIndex[currentPrizeStakeID - 1].value + stakeIDToDepositIndex[currentPrizeStakeID - 2].value + stakeIDToDepositIndex[currentPrizeStakeID - 3].value + stakeIDToDepositIndex[currentPrizeStakeID - 4].value;
stakeIDToDepositIndex[currentPrizeStakeID].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID].value).div(totalValue));
emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID].value, now);
stakeIDToDepositIndex[currentPrizeStakeID - 1].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 1].value).div(totalValue));
emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID - 1].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 1].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID - 1].value, now);
stakeIDToDepositIndex[currentPrizeStakeID - 2].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 2].value).div(totalValue));
emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID - 2].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 2].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID - 2].value, now);
stakeIDToDepositIndex[currentPrizeStakeID - 3].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 3].value).div(totalValue));
emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID - 3].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 3].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID - 3].value, now);
stakeIDToDepositIndex[currentPrizeStakeID - 4].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 4].value).div(totalValue));
emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID - 4].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 4].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID - 4].value, now);
}
}
|
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.accERC20PerShare).div(1e36).sub(user.rewardDebt);
erc20Transfer(tx.origin, pendingAmount);
pool.supply = pool.supply.sub(user.amount);
pool.stakingToken.safeTransfer(address(manager), user.amount);
user.amount = 0;
user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);
emit Withdraw(msg.sender, _pid);
}
|
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][userAddress];
require(user.withdrawTime == 0, "deposit: user is unstaking");
updatePool(_pid);
if (user.amount > 0) {
uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);
erc20Transfer(userAddress, pendingAmount);
}
pool.stakingToken.safeTransferFrom(address(msg.sender), address(this), _amount);
pool.supply = pool.supply.add(_amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);
emit Deposit(userAddress, _pid, _amount);
}
|
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(user.withdrawTime == 0, "withdraw: user is unstaking");
updatePool(_pid);
// transfer any rewards due
uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);
erc20Transfer(msg.sender, pendingAmount);
pool.supply = pool.supply.sub(user.amount);
user.rewardDebt = 0;
user.withdrawTime = block.timestamp;
emit Withdraw(msg.sender, _pid);
}
|
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(_pid);
//apply burn fee if unstaking before unstake epochs.
uint256 unstakeEpochs = manager.getUnstakeEpochs();
uint256 burnRate = manager.getBurnRate();
address redistributor = manager.getRedistributor();
if((user.withdrawTime.add(SECS_EPOCH.mul(unstakeEpochs)) > block.timestamp) && burnRate > 0){
uint penalty = user.amount.div(1000).mul(burnRate);
user.amount = user.amount.sub(penalty);
// if the staking address is an LP, send 50% of penalty to redistributor, and 50% to lp lock address.
if(pool.isLP){
pool.stakingToken.safeTransfer(redistributor, penalty.div(2));
pool.stakingToken.safeTransfer(manager.getLpLock(), penalty.div(2));
}else {
// for normal ERC20 tokens, 50% of the penalty is sent to the redistributor address, 50% is burned from the supply.
pool.stakingToken.safeTransfer(redistributor, penalty.div(2));
IBurnable(address(pool.stakingToken)).burn(penalty.div(2));
}
}
uint userAmount = user.amount;
// allows user to stake again.
user.withdrawTime = 0;
user.amount = 0;
pool.stakingToken.safeTransfer(address(msg.sender), userAmount);
emit Unstake(msg.sender, _pid);
}
|
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, "claim: user is unstaking");
updatePool(_pid);
uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);
erc20Transfer(msg.sender, pendingAmount);
user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);
user.lastClaimTime = block.timestamp;
emit Claim(msg.sender, _pid);
}
|
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 of LP token contract
* @param _blockReward Reward per block
* @param _startBlock Block number to start reward
* @param _bonusEndBlock Block number to end the bonus reward
* @param _bonus Bonus multipler which will be applied until bonus end block
*/
|
function init(
IERC20 _rewardToken,
uint256 _amount,
IERC20 _lpToken,
uint256 _blockReward,
uint256 _startBlock,
uint256 _endBlock,
uint256 _bonusEndBlock,
uint256 _bonus
) external {
require(msg.sender == address(farmGenerator), "FORBIDDEN");
_rewardToken.safeTransferFrom(msg.sender, address(this), _amount);
farmInfo.rewardToken = _rewardToken;
farmInfo.startBlock = _startBlock;
farmInfo.blockReward = _blockReward;
farmInfo.bonusEndBlock = _bonusEndBlock;
farmInfo.bonus = _bonus;
uint256 lastRewardBlock = block.number > _startBlock ? block.number : _startBlock;
farmInfo.lpToken = _lpToken;
farmInfo.lastRewardBlock = lastRewardBlock;
farmInfo.accRewardPerShare = 0;
farmInfo.endBlock = _endBlock;
farmInfo.farmableSupply = _amount;
}
|
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.endBlock;
return;
}
uint256 multiplier = getMultiplier(farmInfo.lastRewardBlock, block.number);
uint256 tokenReward = multiplier.mul(farmInfo.blockReward);
farmInfo.accRewardPerShare = farmInfo.accRewardPerShare.add(tokenReward.mul(1e12).div(lpSupply));
farmInfo.lastRewardBlock = block.number < farmInfo.endBlock ? block.number : farmInfo.endBlock;
}
|
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);
}
if (user.amount == 0 && _amount > 0) {
factory.userEnteredFarm(msg.sender);
farmInfo.numFarmers++;
}
farmInfo.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12);
emit Deposit(msg.sender, _amount);
}
|
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--;
}
uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt);
_safeRewardTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12);
farmInfo.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _amount);
}
|
0.6.10
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.