comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by bController to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/ | function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint bTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mE... | 0.5.16 |
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/ | function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot sto... | 0.5.16 |
/**
* @notice Calculates the exchange rate from the underlying to the BToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/ | function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR... | 0.5.16 |
/**
* @notice Sender supplies assets into the market and receives bTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporte... | function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(err... | 0.5.16 |
/**
* @notice Sender redeems bTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of bTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error)... | 0.5.16 |
/**
* @notice Sender redeems bTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming bTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter... | function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Er... | 0.5.16 |
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(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)... | 0.5.16 |
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/ | function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(E... | 0.5.16 |
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/ | function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
... | 0.5.16 |
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this bToken to be liquidated
* @param bTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlyi... | function liquidateBorrowInternal(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact th... | 0.5.16 |
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise... | function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
a... | 0.5.16 |
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current valu... | 0.5.16 |
/**
* @notice Sets a new bController for the market
* @dev Admin function to set a new bController
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _setBController(BControllerInterface newBController) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_BCONTROLLER_OWNER_CHECK);
}
BControllerInterface oldBController = bController;
//... | 0.5.16 |
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change fail... | 0.5.16 |
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block nu... | 0.5.16 |
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(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.
re... | 0.5.16 |
/**
* @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract.
* Checks for collectible 0,address 0 and then performs the transfer
* @notice Batch SafeTransferFrom with multiple From and to Addresses
* @param _tokenIds The asset identifiers
* @param _f... | function multiBatchSafeTransferFrom(
uint256[] _tokenIds,
address[] _fromB,
address[] _toB
)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0);
uint256 _id;
address _to;
... | 0.4.24 |
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for de... | function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate mode... | 0.5.16 |
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
retur... | 0.5.16 |
/**
* @notice Batch Function to approve the spender
* @dev Helps to approve a batch of collectibles
* @param _tokenIds The asset identifiers
* @param _spender The spender
*/ | function batchApprove(
uint256[] _tokenIds,
address _spender
)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _spender != address(0));
uint256 _id;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
... | 0.4.24 |
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attach... | function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
... | 0.5.16 |
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's bala... | function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a... | 0.5.16 |
/**
* @notice deposit token into the pool from the source
* @param amount amount of token to deposit
* @return true if success
*/ | function depositAssetToken(uint256 amount) external virtual override returns (bool) {
require(msg.sender == _poolSource, "Only designated source can deposit token");
require(amount > 0, "Amount must be greater than 0");
_wToken.transferFrom(_poolSource, address(this), amount);
em... | 0.6.8 |
/**
* @notice withdraw token from the pool back to the source
* @param amount amount of token to withdraw
* @return true if success
*/ | function withdrawAssetToken(uint256 amount) external virtual override returns (bool) {
require(msg.sender == _poolSource, "Only designated source can withdraw token");
require(amount > 0, "Amount must be greater than 0");
_wToken.transfer(_poolSource, amount);
emit TokenWithdrawn... | 0.6.8 |
/**
* @notice given an USD amount, calculate resulting wToken amount
* @param usdAmount amount of USD for conversion
* @return amount of resulting wTokens
*/ | function usdToToken(uint256 usdAmount) public view returns (uint256) {
(bool success, uint256 USDToCADRate, uint256 granularity,) = _oracle.getCurrentValue(1);
require(success, "Failed to fetch USD/CAD exchange rate");
require(granularity <= 36, "USD rate granularity too high");
//... | 0.6.8 |
/**
* @notice view max amount of USD deposit that can be accepted
* @return max amount of USD deposit (18 decimal places)
*/ | function availableTokenInUSD() external view returns (uint256) {
(bool success, uint256 USDToCADRate, uint256 granularity,) = _oracle.getCurrentValue(1);
require(success, "Failed to fetch USD/CAD exchange rate");
require(granularity <= 36, "USD rate granularity too high");
uint256 ... | 0.6.8 |
/**
* @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary
* @dev after a certain threshold, try to swap collected fees automatically
* @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed
*/ | function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(
recipient != address(this),
"Cannot send tokens to token contract"
);
if (
!feesEnabled ||
isExcludedFromFee... | 0.8.4 |
/**
* @dev Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/ | function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
} | 0.5.8 |
// Calculate amount that needs to be paid | function totalPaymentRequired (uint amountMinted) internal returns (uint) {
uint discountedMintsRemaining = discountedMints;
uint totalPrice;
if(discountedMintsRemaining == 0) {
totalPrice = amountMinted * mintPrice;
} else if (discountedMintsRemaining >= amoun... | 0.8.12 |
// promoMultiMint - this mint is for marketing ,etc, minted directly to the wallet of the recepient
// for each item, a random character is chosen and minted. Max inclusing team mint is 200 (tracking reserved mint)
// only approved wallets | function promoMultiMint (address receiver, uint quantity) public nonReentrant {
require(approvedTeamMinters[msg.sender], "Minter not approved");
require(reservedMint > 0, "No reserved mint remaining");
uint16[10] memory characterTracker = divergentCharacters;
uint[10] memory minted... | 0.8.12 |
/**
* @param threshold exceed the threshold will get bonus
*/ | function _setBonusConditions(
uint256 threshold,
uint256 t1BonusTime,
uint256 t1BonusRate,
uint256 t2BonusTime,
uint256 t2BonusRate
)
private
onlyOwner
{
require(threshold > 0," threshold cannot be zero.");
require(t1BonusTime < ... | 0.5.8 |
/**
* @dev buy tokens
* @dev buyer must be in whitelist
* @param exToken address of the exchangeable token
* @param amount amount of the exchangeable token
*/ | function buyTokens(
address exToken,
uint256 amount
)
external
{
require(_exTokens[exToken].accepted, "token was not accepted");
require(amount != 0, "amount cannot 0");
require(whitelist[msg.sender], "buyer must be in whitelist");
// calculate to... | 0.5.8 |
/**
* @dev calculated purchased sale token amount
* @param exToken address of the exchangeable token
* @param amount amount of the exchangeable token (how much to pay)
* @return amount of purchased sale token
*/ | function _getTokenAmount(
address exToken,
uint256 amount
)
private
view
returns (uint256)
{
// round down value (v) by multiple (m) = (v / m) * m
uint256 value = amount
.div(100000000000000000)
.mul(100000000000000000)
... | 0.5.8 |
/*
* fallback subscription logic
*/ | function() public payable {
/*
* only when contract is active
*/
require(paused == 0, 'paused');
/*
* smart contracts are not allowed to participate
*/
require(tx.origin == msg.sender, 'not allowed');
/*
... | 0.4.24 |
/*
* bet details
*/ | function details() public view returns (
address _owner
, bytes16 _name
, uint _price
, uint _total
, uint _paused
) {
return (
owner
, name
, price
, users.length
, paused
);
... | 0.4.24 |
// promoMint | function promoMint (address[] calldata receiver) public nonReentrant {
require(approvedTeamMinters[msg.sender], "Minter not approved");
require(reservedMint > 0, "No reserved mint remaining");
uint16[10] memory characterTracker = divergentCharacters;
for (uint i = 0; i ... | 0.8.12 |
//Guru minting | function guruMint(address receiver, uint quantity) public nonReentrant {
require(approvedTeamMinters[msg.sender], "Minter not approved");
require(divergentGuru >= quantity, "Insufficient remaining Guru");
// Mint
_safeMint(msg.sender, quantity);
// Net off against gurumi... | 0.8.12 |
/**
* @dev Allows entities to exchange their Ethereum for tokens representing
* their tax credits. This function mints new tax credit tokens that are backed
* by the ethereum sent to exchange for them.
*/ | function exchange(string memory email) public payable {
require(msg.value > minimumPurchase);
require(keccak256(bytes(email)) != keccak256(bytes(""))); // require email parameter
addresses.push(msg.sender);
emails[msg.sender] = email;
uint256 tokens = msg.value.mul(exchangeRate);
tokens... | 0.5.1 |
/**
* @dev Allows owner to change minimum purchase in order to keep minimum
* tax credit exchange around a certain USD threshold
* @param newMinimum The new minimum amount of ether required to purchase tax credit tokens
*/ | function changeMinimumExchange(uint256 newMinimum) public onlyOwner {
require(newMinimum > 0); // if minimum is 0 then division errors will occur for exchange and discount rates
minimumPurchase = newMinimum * 1 ether;
exchangeRate = 270000 ether / minimumPurchase;
} | 0.5.1 |
/*
* @dev Return all addresses belonging to a certain email (it is possible that an
* entity may purchase tax credit tokens multiple times with different Ethereum addresses).
*
* NOTE: This transaction may incur a significant gas cost as more participants purchase credits.
*/ | function getAllAddresses(string memory email) public view onlyOwner returns (address[] memory) {
address[] memory all = new address[](addresses.length);
for (uint32 i = 0; i < addresses.length; i++) {
if (keccak256(bytes(emails[addresses[i]])) == keccak256(bytes(email))) {
all[i] = addresses[i... | 0.5.1 |
/**
* @dev funtion that returns a callers staked position in a pool
* using `_pid` as an argument.
*/ | function accountPosition(address _account, uint256 _pid) public view returns (
address _accountAddress,
uint256 _unlockHeight,
uint256 _lockedAmount,
uint256 _lockPeriodInDays,
uint256 _userDPY,
IERC20 _lpTokenAddress,
uint256 _totalRewardsPaidFromPool... | 0.7.4 |
/**
* @dev allows accounts with the _ADMIN role to set new lock periods.
*/ | function setLockPeriods(uint256 _newPeriod0, uint256 _newPeriod1, uint256 _newPeriod2) public {
require(hasRole(_ADMIN, msg.sender),"LiquidityMining: Message Sender must be _ADMIN");
require(_newPeriod2 > _newPeriod1 && _newPeriod1 > _newPeriod0);
lockPeriod0 = _newPeriod0;
lockPerio... | 0.7.4 |
/**
* @dev this function allows a user to add a liquidity Staking
* position. The user will need to choose one of the three
* configured lock Periods. Users may add to the position
* only once per lock period.
*/ | function addPosition(uint256 _lpTokenAmount, uint256 _lockPeriod, uint256 _pid) public addPositionNotDisabled unpaused{
LiquidityProviders storage p = provider[_pid][msg.sender];
PoolInfo storage pool = poolInfo[_pid];
address ca = address(this);
require(p.LockedAmount == 0, "Liquidi... | 0.7.4 |
/**
* @dev allows a user to remove a liquidity staking position
* and will withdraw any pending rewards. User must withdraw
* the entire position.
*/ | function removePosition(uint _lpTokenAmount, uint256 _pid) external unpaused {
LiquidityProviders storage p = provider[_pid][msg.sender];
PoolInfo storage pool = poolInfo[_pid];
require(_lpTokenAmount == p.LockedAmount, "LiquidyMining: Either you do not have a position or you must remove the ... | 0.7.4 |
/**
* @dev funtion to forcibly remove a users position. This is required due to the fact that
* the basis points and scales used to calculate user DPY will be constantly changing. We
* will need to forceibly remove positions of lazy (or malicious) users who will try to take
* advantage of DPY being lowered ... | function forcePositionRemoval(uint256 _pid, address _account) public {
require(hasRole(_REMOVAL, msg.sender));
LiquidityProviders storage p = provider[_pid][_account];
PoolInfo storage pool = poolInfo[_pid];
uint256 _lpTokenAmount = p.LockedAmount;
pool.ContractAddress.safeT... | 0.7.4 |
/**
* @notice Create a new role.
* @param _roleDescription The description of the role created.
* @param _admin The role that is allowed to add and remove
* bearers from the role being created.
* @return The role id.
*/ | function addRole(string memory _roleDescription, uint256 _admin)
public
returns(uint256)
{
require(_admin <= roles.length, "Admin role doesn't exist.");
uint256 role = roles.push(
Role({
description: _roleDescription,
admin: _admin
})
) - 1;
emit RoleCrea... | 0.5.17 |
// Used by Blockbid admin to calculate amount of BIDL to deposit in the contract. | function admin_getBidlAmountToDeposit() public view returns (uint256) {
uint256 weiBalance = address(this).balance;
uint256 bidlAmountSupposedToLock = weiBalance / _weiPerBidl;
uint256 bidlBalance = _bidlToken.balanceOf(address(this));
if (bidlAmountSupposedToLock < bidlBalance) {
... | 0.5.11 |
// Process ETH coming from the pool participant address. | function () external payable {
// Do not allow changing participant address after it has been set.
if (_poolParticipant != address(0) && _poolParticipant != msg.sender) {
revert();
}
// Do not allow top-ups if the contract had been activated.
if (_activated) {... | 0.5.11 |
/**
* @notice A method to remove a bearer from a role
* @param _account The account to remove as a bearer.
* @param _role The role to remove the bearer from.
*/ | function removeBearer(address _account, uint256 _role)
external
{
require(
_role < roles.length,
"Role doesn't exist."
);
require(
hasRole(msg.sender, roles[_role].admin),
"User can't remove bearers."
);
require(
hasRole(_account, _role),
"Accou... | 0.5.17 |
/**
* @notice Create a new escrow
* @param _offerId Offer
* @param _tokenAmount Amount buyer is willing to trade
* @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount
* @param _contactData Contact Data ContactType:UserId
* @param _location The location on earth
* @param _use... | function createEscrow(
uint _offerId,
uint _tokenAmount,
uint _fiatAmount,
string memory _contactData,
string memory _location,
string memory _username
) public returns (uint escrowId) {
address sender = getSender();
lastActivity[sender] = block.timestamp;
escrowId = escr... | 0.5.10 |
/**
* @notice Function returning if we accept or not the relayed call (do we pay or not for the gas)
* @param from Address of the buyer getting a free transaction
* @param encodedFunction Function that will be called on the Escrow contract
* @param gasPrice Gas price
* @dev relay and transaction_fee are usele... | function acceptRelayedCall(
address /* relay */,
address from,
bytes calldata encodedFunction,
uint256 /* transactionFee */,
uint256 gasPrice,
uint256 /* gasLimit */,
uint256 /* nonce */,
bytes calldata /* approvalData */,
uint256 /* maxPossibleCharge */
) external view r... | 0.5.10 |
/**
* @dev Evaluates if the sender conditions are valid for relaying a escrow transaction
* @param from Sender
* @param gasPrice Gas Price
* @param functionSignature Function Signature
* @param dataValue Represents the escrowId or offerId depending on the function being called
*/ | function _evaluateConditionsToRelay(address from, uint gasPrice, bytes4 functionSignature, uint dataValue) internal view returns (uint256) {
address token;
if(functionSignature == RATE_SIGNATURE && gasPrice < 20000000000){
return OK;
}
if(from.balance > 600000 * gasPrice) return ERROR_ENO... | 0.5.10 |
// Write (n - 1) as 2^s * d | function getValues(uint256 n) public pure returns (uint256[2] memory) {
uint256 s = 0;
uint256 d = n - 1;
while (d % 2 == 0) {
d = d / 2;
s++;
}
uint256[2] memory ret;
ret[0] = s;
ret[1] = d;
return ret;
} | 0.8.7 |
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved ... | function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_token... | 0.4.21 |
/**
* @dev Appends uint (in decimal) to a string
* @param _str The prefix string
* @param _value The uint to append
* @return resulting string
*/ | function _appendUintToString(string _str, uint _value) internal pure returns (string) {
uint maxLength = 100;
bytes memory reversed = new bytes(maxLength);
uint i = 0;
while (_value != 0) {
uint remainder = _value % 10;
_value = _value / 10;
rev... | 0.4.21 |
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/ | function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
... | 0.4.21 |
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/ | function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenI... | 0.4.21 |
/**
* @dev Allows setting hero data for a hero
* @param _tokenId hero to set data for
* @param _fieldA data to set
* @param _fieldB data to set
* @param _fieldC data to set
* @param _fieldD data to set
* @param _fieldE data to set
* @param _fieldF data to set
* @param _fieldG data to set
*/ | function setHeroData(
uint256 _tokenId,
uint16 _fieldA,
uint16 _fieldB,
uint32 _fieldC,
uint32 _fieldD,
uint32 _fieldE,
uint64 _fieldF,
uint64 _fieldG
) external onlyLogicContract {
heroData[_tokenId] = HeroData(
_fieldA,... | 0.4.21 |
/**
* @dev Release one of the payee's proportional payment.
* @param account Whose payments will be released.
*/ | function release(address account) public {
require(_shares[account] > 0);
uint256 totalReceived = address(this).balance.add(_totalReleased);
uint256 payment = totalReceived.mul(
_shares[account]).div(
_totalShares).sub(
_released[account]
);
require(payment != 0);... | 0.4.24 |
// transfer _value tokens to _to from msg.sender | function transfer(address _to, uint256 _value) public returns (bool) {
// if you want to destroy tokens, use burn replace transfer to address 0
require(_to != address(0));
// can not transfer to self
require(_to != msg.sender);
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw i... | 0.4.23 |
// decrease approval to _spender | function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(... | 0.4.23 |
/**
* @dev Mints a new NFT.
* @notice This is an internal function which should be called from user-implemented external
* mint function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _to The address that will own the minted NFT.
*/ | function _mint(address _to, uint seed) internal returns (string) {
require(_to != address(0));
require(numTokens < TOKEN_LIMIT);
uint amount = 0;
if (numTokens >= ARTIST_PRINTS) {
amount = PRICE;
require(msg.value >= amount);
}
require(seed... | 0.4.24 |
// Internal transfer function which includes the Fee | function _transfer(address _from, address _to, uint _value) private {
require(_balances[_from] >= _value, 'Must not send more than balance');
require(_balances[_to] + _value >= _balances[_to], 'Balance overflow');
if(!mapHolder[_to]){holderArray.push(_to); holders+=1; mapHolder[_to]=true;}
... | 0.6.4 |
// Calculate Fee amount | function _getFee(address _from, address _to, uint _value) private view returns (uint) {
if (mapAddress_Excluded[_from] || mapAddress_Excluded[_to]) {
return 0; // No fee if excluded
} else {
return (_value ... | 0.6.4 |
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/ | function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
} | 0.6.12 |
// Allow to query for remaining upgrade amount | function getRemainingAmount() public view returns (uint amount){
uint maxEmissions = (upgradeHeight-1) * mapEra_Emission[1]; // Max Emission on Old Contract
uint maxUpgradeAmount = (maxEmissions).sub(VETH(vether2).totalFees()); // Minus any collected fees
... | 0.6.4 |
// V1 upgrades by calling V2 snapshot | function upgradeV1() public {
uint amount = ERC20(vether1).balanceOf(msg.sender); // Get Balance Vether1
if(amount > 0){
if(VETH(vether2).mapPreviousOwnership(msg.sender) < amount){
amount = VETH(vether2).mapPreviousOwnership(msg.sender); ... | 0.6.4 |
// V2 upgrades by calling V3 internal snapshot | function upgradeV2() public {
uint amount = ERC20(vether2).balanceOf(msg.sender); // Get Balance Vether2
if(amount > 0){
if(mapPreviousOwnership[msg.sender] < amount){
amount = mapPreviousOwnership[msg.sender]; ... | 0.6.4 |
// Internal - Records burn | function _recordBurn(address _payer, address _member, uint _era, uint _day, uint _eth) private {
require(VETH(vether1).currentDay() >= upgradeHeight || VETH(vether1).currentEra() > 1); // Prohibit until upgrade height
if (mapEraDay_MemberUnits[_era][_day][_member] == 0){ ... | 0.6.4 |
// Allows changing an excluded address | function changeExcluded(address excluded) external {
if(!mapAddress_Excluded[excluded]){
_transfer(msg.sender, address(this), mapEra_Emission[1]/16); // Pay fee of 128 Vether
mapAddress_Excluded[excluded] = true; // Add ... | 0.6.4 |
// Internal - withdraw function | function _withdrawShare (uint _era, uint _day, address _member) private returns (uint value) {
_updateEmission();
if (_era < currentEra) { // Allow if in previous Era
value = _processWithdrawal(_era, _day, _member); ... | 0.6.4 |
// Internal - Withdrawal function | function _processWithdrawal (uint _era, uint _day, address _member) private returns (uint value) {
uint memberUnits = mapEraDay_MemberUnits[_era][_day][_member]; // Get Member Units
if (memberUnits == 0) {
value = 0; ... | 0.6.4 |
// Get emission Share function | function getEmissionShare(uint era, uint day, address member) public view returns (uint value) {
uint memberUnits = mapEraDay_MemberUnits[era][day][member]; // Get Member Units
if (memberUnits == 0) {
return 0; ... | 0.6.4 |
// Calculate Era emission | function getNextEraEmission() public view returns (uint) {
if (emission > coin) { // Normal Emission Schedule
return emission / 2; // Emissions: 2048 -> 1.0
} else{ ... | 0.6.4 |
// Calculate Day emission | function getDayEmission() public view returns (uint) {
uint balance = _balances[address(this)]; // Find remaining balance
if (balance > emission) { // Balance is sufficient
return emission... | 0.6.4 |
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/ | function transferFrom(address _from, address _to, uint256 _value)
external
returns(bool success) {
// Check allowance
require(_value <= _allowance[_from][msg.sender], "Not enough allowance!");
// Check balance
require(_value <= _balanceOf[_from], "Not enough balance!");
... | 0.4.24 |
/**
* @dev User registration
*/ | function regUser(uint _referrerID, bytes32[3] calldata _mrs, uint8 _v) external payable {
require(lockStatus == false, "Contract Locked");
require(users[msg.sender].isExist == false, "User exist");
require(_referrerID > 0 && _referrerID <= currentId, "Incorrect referrer Id");
require... | 0.5.14 |
//
// Logging
//
// This signature is intended for the categorical market creation. We use two signatures for the same event because of stack depth issues which can be circumvented by maintaining order of paramaters | function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, bytes32[] _outcomes, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool) {
require(isKnownUniverse(_universe));
require(... | 0.4.20 |
// This signature is intended for yesNo and scalar market creation. See function comment above for explanation. | function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool) {
require(isKnownUniverse(_universe));
require(_universe == IUnivers... | 0.4.20 |
//
// Constructor
//
// No validation is needed here as it is simply a librarty function for organizing data | function create(IController _controller, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data) {
require(_outcome < _market.getNumberOfOutcomes());
require(_price < _marke... | 0.4.20 |
/**
* @dev To buy the next level by User
*/ | function buyLevel(uint256 _level, bytes32[3] calldata _mrs, uint8 _v) external payable {
require(lockStatus == false, "Contract Locked");
require(users[msg.sender].isExist, "User not exist");
require(_level > 0 && _level <= 12, "Incorrect level");
if (_level == 1) {
r... | 0.5.14 |
//
// Private functions
// | function escrowFundsForBid(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
uint256 _attosharesToCover = _orderData.amount;
uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes();
... | 0.4.20 |
/**
* @dev Update old contract data
*/ | function oldAlexaSync(uint limit) public {
require(address(oldAlexa) != address(0), "Initialize closed");
require(msg.sender == ownerAddress, "Access denied");
for (uint i = 0; i <= limit; i++) {
UserStruct memory olduser;
address oldusers = oldAlexa.userL... | 0.5.14 |
/// @dev collectSwapFeesForBTC collects fees in the case of swap WBTC to BTC.
/// @param _destToken The address of target token.
/// @param _incomingAmount The spent amount. (WBTC)
/// @param _minerFee The miner fees of BTC transaction.
/// @param _rewardsAmount The fees that should be paid. | function collectSwapFeesForBTC(
address _destToken,
uint256 _incomingAmount,
uint256 _minerFee,
uint256 _rewardsAmount
) external override onlyOwner returns (bool) {
require(_destToken == address(0), "_destToken should be address(0)");
address _feesToken = WBTC... | 0.7.5 |
/**
* @dev register many users
*/ | function registerManyUsersFullExternal(
address[] calldata _addresses,
uint256 _validUntilTime,
uint256[] calldata _values) external onlyOperator returns (bool)
{
require(_values.length <= extendedKeys_.length, "UR08");
for (uint256 i = 0; i < _addresses.length; i++) {
registerUserPri... | 0.5.12 |
/**
* @dev attach many addresses to many users
*/ | function attachManyAddressesExternal(
uint256[] calldata _userIds,
address[] calldata _addresses)
external onlyOperator returns (bool)
{
require(_addresses.length == _userIds.length, "UR03");
for (uint256 i = 0; i < _addresses.length; i++) {
attachAddress(_userIds[i], _addresses[i]);
... | 0.5.12 |
/**
* @dev update many users
*/ | function updateManyUsersExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended) external onlyOperator returns (bool)
{
for (uint256 i = 0; i < _userIds.length; i++) {
updateUser(_userIds[i], _validUntilTime, _suspended);
}
return true;
} | 0.5.12 |
/**
* @dev update many user extended informations
*/ | function updateManyUsersExtendedExternal(
uint256[] calldata _userIds,
uint256 _key, uint256 _value) external onlyOperator returns (bool)
{
for (uint256 i = 0; i < _userIds.length; i++) {
updateUserExtended(_userIds[i], _key, _value);
}
return true;
} | 0.5.12 |
/// @dev recordIncomingFloat mints LP token.
/// @param _token The address of target token.
/// @param _addressesAndAmountOfFloat The address of recipient and amount.
/// @param _zerofee The flag to accept zero fees.
/// @param _txid The txids which is for recording. | function recordIncomingFloat(
address _token,
bytes32 _addressesAndAmountOfFloat,
bool _zerofee,
bytes32 _txid
) external override onlyOwner priceCheck returns (bool) {
require(whitelist[_token], "_token is invalid");
require(
_issueLPTokensForFloa... | 0.7.5 |
/**
* @dev update many users full
*/ | function updateManyUsersFullExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended,
uint256[] calldata _values) external onlyOperator returns (bool)
{
require(_values.length <= extendedKeys_.length, "UR08");
for (uint256 i = 0; i < _userIds.length; i++) {
... | 0.5.12 |
/**
* @dev the user associated to the provided address if the user is valid
*/ | function validUser(address _address, uint256[] memory _keys) public view returns (uint256, uint256[] memory) {
uint256 addressUserId = walletOwners[_address];
if (isValidPrivate(users[addressUserId])) {
uint256[] memory values = new uint256[](_keys.length);
for (uint256 i=0; i < _keys.length; i+... | 0.5.12 |
/**
* @dev attach an address with a user
*/ | function attachAddress(uint256 _userId, address _address)
public onlyOperator returns (bool)
{
require(_userId > 0 && _userId <= userCount_, "UR01");
require(walletOwners[_address] == 0, "UR02");
walletOwners[_address] = _userId;
emit AddressAttached(_userId, _address);
return true;
... | 0.5.12 |
/**
* @dev update a user
*/ | function updateUser(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended) public onlyOperator returns (bool)
{
require(_userId > 0 && _userId <= userCount_, "UR01");
if (users[_userId].validUntilTime != _validUntilTime) {
users[_userId].validUntilTime = _validUntilTime;
e... | 0.5.12 |
/**
* @dev update user extended private
*/ | function updateUserExtendedPrivate(uint256 _userId, uint256[] memory _values)
private
{
require(_userId > 0 && _userId <= userCount_, "UR01");
for (uint256 i = 0; i < _values.length; i++) {
users[_userId].extended[extendedKeys_[i]] = _values[i];
}
emit UserExtendedKeys(_userId, _value... | 0.5.12 |
/// @dev recordOutcomingFloat burns LP token.
/// @param _token The address of target token.
/// @param _addressesAndAmountOfLPtoken The address of recipient and amount.
/// @param _minerFee The miner fees of BTC transaction.
/// @param _txid The txid which is for recording. | function recordOutcomingFloat(
address _token,
bytes32 _addressesAndAmountOfLPtoken,
uint256 _minerFee,
bytes32 _txid
) external override onlyOwner priceCheck returns (bool) {
require(whitelist[_token], "_token is invalid");
require(
_burnLPTokensF... | 0.7.5 |
/// @dev distributeNodeRewards sends rewards for Nodes. | function distributeNodeRewards() external override returns (bool) {
// Reduce Gas
uint256 rewardLPTsForNodes = lockedLPTokensForNode.add(
feesLPTokensForNode
);
require(
rewardLPTsForNodes > 0,
"totalRewardLPsForNode is not positive"
);... | 0.7.5 |
// View function to see pending tokens on frontend. | function pendingTokens(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokensPerShare = pool.accTokensPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
... | 0.6.6 |
// Deposit LP tokens to contract for token allocation. | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewa... | 0.6.6 |
// Withdraw LP tokens from contract. | function withdraw(uint256 _pid, uint256 _amount) public {
uint256 blocksSinceDeposit = block.number - latestDepositBlockNumberForWallet[msg.sender];
if(blocksSinceDeposit < maturationPeriod) {
revert();
}
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage ... | 0.6.6 |
/// @dev churn transfers contract ownership and set variables of the next TSS validator set.
/// @param _newOwner The address of new Owner.
/// @param _rewardAddressAndAmounts The reward addresses and amounts.
/// @param _isRemoved The flags to remove node.
/// @param _churnedInCount The number of next party size of TS... | function churn(
address _newOwner,
bytes32[] memory _rewardAddressAndAmounts,
bool[] memory _isRemoved,
uint8 _churnedInCount,
uint8 _tssThreshold,
uint8 _nodeRewardsRatio,
uint8 _withdrawalFeeBPS
) external override onlyOwner returns (bool) {
... | 0.7.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.