comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* Hack to get things to work automatically on OpenSea.
* Use isApprovedForAll so the frontend doesn't have to worry about different method names.
*/ | function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool)
{
if (owner() == _owner && _owner == _operator) {
return true;
}
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (
... | 0.8.4 |
/* ///////////////////////////////////////////////////////////////
EIP - 2612 LOGIC
//////////////////////////////////////////////////////////////*/ | function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) revert SignatureExpired();
// cannot realistically overflow on human timescales
... | 0.8.11 |
/* ///////////////////////////////////////////////////////////////
MINT / BURN LOGIC
//////////////////////////////////////////////////////////////*/ | function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// cannot overflow because the sum of all user
// balances can't exceed the max uint256 value
unchecked {
balanceOf[to] += amount;
}
_moveDelegates(address(0), delegates(to)... | 0.8.11 |
// VRAgent was here! | function checkIfDuckOwner(uint16 _duckID) external view returns (bool) {
require(_duckID >= 1 && _duckID <= 333, "Duck ID should be in range");
uint56 offset = ducks[_duckID - 1];
uint256 tokenID = uint256(offset) + baseNumber;
OpenStoreContract nft = OpenStoreContract(openStoreNFTAd... | 0.8.4 |
///@dev claims the base token after it has been transmuted
///
///This function reverts if there is no realisedToken balance | function claim(bool asEth) public nonReentrant() noContractAllowed() {
address sender = msg.sender;
require(realisedTokens[sender] > 0);
uint256 value = realisedTokens[sender];
realisedTokens[sender] = 0;
ensureSufficientFundsExistLocally(value);
if (asEth) {
... | 0.6.12 |
/**
* @dev Transfers ownership of the contract to the Cosmic Vault (`cosmicVault`) and
* sets the time (`unlockTime`) at which the now stored contract can be transferred back to
* the previous owner.
* NOTE Can only be called by the current owner.
*/ | function storeInCosmicVault(address cosmicVault, uint256 unlockTime) public virtual onlyOwner {
require(cosmicVault != address(0), "CVOwnable: new owner is the zero address");
_previousOwner = _owner;
_unlockTime = unlockTime;
emit OwnershipTransferred(_previousOwner, cosmicVault);
... | 0.8.4 |
/**
* @notice GoldFinch PoolToken Value in Value in term of USDC
*/ | function getGoldFinchPoolTokenBalanceInUSDC() public view returns (uint256) {
uint256 total = 0;
uint256 balance = goldFinchPoolToken.balanceOf(address(this));
for (uint256 i = 0; i < balance; i++) {
total = total.add(
getJuniorTokenValue(
address(goldFinchPoolToken),
... | 0.8.13 |
/**
* @notice An Alloy token holder can deposit their tokens and redeem them for USDC
* @param _tokenAmount Number of Alloy Tokens
*/ | function depositAlloyxBronzeTokens(uint256 _tokenAmount)
external
whenNotPaused
whenVaultStarted
returns (bool)
{
require(
alloyxTokenBronze.balanceOf(msg.sender) >= _tokenAmount,
"User has insufficient alloyx coin"
);
require(
alloyxTokenBronze.allowance(msg.s... | 0.8.13 |
/**
* @notice A Liquidity Provider can deposit supported stable coins for Alloy Tokens
* @param _tokenAmount Number of stable coin
*/ | function depositUSDCCoin(uint256 _tokenAmount)
external
whenNotPaused
whenVaultStarted
returns (bool)
{
require(usdcCoin.balanceOf(msg.sender) >= _tokenAmount, "User has insufficient stable coin");
require(
usdcCoin.allowance(msg.sender, address(this)) >= _tokenAmount,
"Us... | 0.8.13 |
/**
* @notice A Junior token holder can deposit their NFT for stable coin
* @param _tokenAddress NFT Address
* @param _tokenID NFT ID
*/ | function depositNFTToken(address _tokenAddress, uint256 _tokenID)
external
whenNotPaused
whenVaultStarted
returns (bool)
{
require(_tokenAddress == address(goldFinchPoolToken), "Not Goldfinch Pool Token");
require(isValidPool(_tokenAddress, _tokenID) == true, "Not a valid pool");
r... | 0.8.13 |
/**
* @notice Using the Goldfinch contracts, read the principal, redeemed and redeemable values
* @param _tokenAddress The backer NFT address
* @param _tokenID The backer NFT id
*/ | function getJuniorTokenValue(address _tokenAddress, uint256 _tokenID)
public
view
returns (uint256)
{
// first get the amount redeemed and the principal
IPoolTokens poolTokenContract = IPoolTokens(_tokenAddress);
IPoolTokens.TokenInfo memory tokenInfo = poolTokenContract.getTokenInfo(_t... | 0.8.13 |
// Change bet expected end time | function setExpectedEnd(uint _EXPECTED_END) payable public onlyOwnerLevel {
require(_EXPECTED_END > EXPECTED_START);
EXPECTED_END = _EXPECTED_END;
CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24;
RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30;
callOracle(EXPECTED_END, ORACLIZE_GAS); // Kicko... | 0.4.20 |
// Callback from Oraclize | function __callback(bytes32 queryId, string result, bytes proof) public canDetermineWinner {
require(msg.sender == oraclize_cbAddress());
// The Oracle must always return
// an integer (either 0 or 1, or if not then)
// it should be 2
if (keccak256(result) != keccak256("0") && keccak256(resul... | 0.4.20 |
// Returns whether winning collections are
// now available, or not. | function collectionsAvailable() public constant returns(bool) {
return (completed && winningOption != 2 && now >= (winnerDeterminedDate + 600)); // At least 10 mins has to pass between determining winner and enabling payout, so that we have time to revert the bet in case we detect suspicious betting activty (eg. a... | 0.4.20 |
// Function for user to bet on launch
// outcome | function bet(uint option) public payable {
require(canBet() == true);
require(msg.value >= MIN_BET);
require(betterInfo[msg.sender].betAmount == 0 || betterInfo[msg.sender].betOption == option);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].betAm... | 0.4.20 |
// Function that lets betters collect their
// money, either if the bet was canceled,
// or if they won. | function collect() public collectionsEnabled {
address better = msg.sender;
require(betterInfo[better].betAmount > 0);
require(!betterInfo[better].withdrawn);
require(canceled != completed);
require(canceled || (completed && betterInfo[better].betOption == winningOption));
require(now >=... | 0.4.20 |
/**
* Create presale contract where lock up period is given days
*
* @param _owner Who can load investor data and lock
* @param _freezeEndsAt UNIX timestamp when the vault unlocks
* @param _token Token contract address we are distributing
* @param _tokensToBeAllocated Total number of tokens this vault will ... | function TokenVault(address _owner, uint _freezeEndsAt, StandardTokenExt _token, uint _tokensToBeAllocated) {
owner = _owner;
// Invalid owenr
if(owner == 0) {
throw;
}
token = _token;
// Check the address looks like a token contract
if(!token.isToken()) {
throw;... | 0.4.18 |
/// @dev Add a presale participating allocation | function setInvestor(address investor, uint amount) public onlyOwner {
if(lockedAt > 0) {
// Cannot add new investors after the vault is locked
throw;
}
if(amount == 0) throw; // No empty buys
// Don't allow reset
if(balances[investor] > 0) {
throw;
}
bala... | 0.4.18 |
/// @dev Lock the vault
/// - All balances have been loaded in correctly
/// - Tokens are transferred on this vault correctly
/// - Checks are in place to prevent creating a vault that is locked with incorrect token balances. | function lock() onlyOwner {
if(lockedAt > 0) {
throw; // Already locked
}
// Spreadsheet sum does not match to what we have loaded to the investor data
if(tokensAllocatedTotal != tokensToBeAllocated) {
throw;
}
// Do not lock the vault if the given tokens are not on thi... | 0.4.18 |
/// @dev Claim N bought tokens to the investor as the msg sender | function claim() {
address investor = msg.sender;
if(lockedAt == 0) {
throw; // We were never locked
}
if(now < freezeEndsAt) {
throw; // Trying to claim early
}
if(balances[investor] == 0) {
// Not our investor
throw;
}
if(claimed[investor] ... | 0.4.18 |
/// #if_succeeds {:msg "totalSupply increase by mint amount"} old(totalSupply()) == totalSupply() - _mintAmount; | function mint(uint256 _mintAmount) public payable {
require(!isPauseMode, "Paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "Select at least 1 NFT");
require(supply + _mintAmount <= MaxCollection, "Not Enough Left");
if (msg.sender != owner()) {
require(_mintAmoun... | 0.8.9 |
// Consumption payment method, the product realization end is available for merchants to call, due to the high gas fee, this method can pass the payment cost to the merchant, reducing the user cost
// For other rules, please refer to consume1 method | function consume2(address _merchant, address _serviceProvider, uint256 _amount, uint256 time, bytes memory signature) public {
bytes32 hash = keccak256(abi.encodePacked(_merchant, _serviceProvider, _amount, time));
require(!consumeHashes[hash], "Repeat consumption.");
address userAddress = ec... | 0.6.12 |
// Withdraw LP tokens from pool. | function withdraw(uint256 _amount) public onlyMerchant {
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool();
sendReward(user, msg.sender);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.a... | 0.6.12 |
//delegated | function burnFrom( address account, uint[] calldata ids, uint[] calldata quantities ) external payable onlyDelegates {
require( ids.length == quantities.length, "ERC1155: Must provide equal ids and quantities");
for(uint i; i < ids.length; ++i ){
_burn( account, ids[i], quantities[i] );
}
} | 0.8.10 |
// Returns the sum of shares of each vault | function validate() external view onlyOwner returns (uint) {
return (
(1 ether * numerators[vaults[0]] / denominators[vaults[0]]) +
(1 ether * numerators[vaults[1]] / denominators[vaults[1]]) +
(1 ether * numerators[vaults[2]] / denominators[vaults[2]]) +
(1 ether * numerators[vaults[3]... | 0.8.8 |
// Sends balance of contract to addresses stored in `vaults` | function withdraw() external nonReentrant {
uint payment0 = address(this).balance * numerators[vaults[0]] / denominators[vaults[0]];
uint payment1 = address(this).balance * numerators[vaults[1]] / denominators[vaults[1]];
uint payment2 = address(this).balance * numerators[vaults[2]] / denominators[vaults[2]... | 0.8.8 |
/**
* @dev The declareValue function lets the valueDeclarator declare a new value when it is reached to
* allow the valueValidator to mint new tokens accordingly.
* @param _value the new validated value
* @notice This function can only be called by the valueDeclarator.
**/ | function declareValue(uint _value) external {
require(msg.sender == valueDeclarator, "validation can only be called by designated valueDeclarator");
require(_value > currentValue, "new declared value should be higher than current value");
require(_value > declaredValue, "new declared value should be high... | 0.5.11 |
/**
* @dev The validateValue function lets the valueValidator accept to mint tokens when values are reached.
* @param _value a new value to declare
* @notice This function can only be called by the valueValidator
**/ | function validateValue(uint _value) external {
require(msg.sender == valueValidator, "validation can only be called by designated valueValidator");
require(_value > currentValue, "new validated value should be higher than current value");
require(_value > validatedValue, "new validated value should be hi... | 0.5.11 |
/**
* @dev The updateCurrentValue function updates currentValue and mints new tokens accordingly.
**/ | function updateCurrentValue() private {
uint newValue = (validatedValue < declaredValue) ? validatedValue : declaredValue;
uint lastNbThresholds = currentValue.div(VALUE_THRESHOLD);
uint newNbThresholds = newValue.div(VALUE_THRESHOLD);
currentValue = newValue;
if (lastNbThresholds < newNbThresh... | 0.5.11 |
// Internal function to create a token | function _create(
uint256 tokenId,
uint256 initialSupply,
uint256 maxSupply_
) internal {
require(maxSupply_ != 0, "BaseERC1155: maxSupply cannot be 0");
require(!isCreated(tokenId), "BaseERC1155: token already created");
require(initialSupply <= maxSupply_, "B... | 0.8.9 |
/**
* @dev Creates an ERC1155 token, optionally setting a fixed price (erc20) for minting the ERC1155
* @dev Can also be used to premint the full supply of an ERC1155 to the contract owner
*/ | function createWithFixedPrice(
uint256 tokenId,
uint256 initialSupply,
uint256 maxSupply,
uint256 mintPrice,
address mintPriceTokenAddress,
string memory uri
) external onlyOwner {
if (initialSupply < maxSupply) {
require(mintPrice > 0, "I... | 0.8.9 |
/**
* @dev Mints a single ERC1155 to msg.sender
*/ | function publicMint(uint256 tokenId) external {
// Get the address & price for minting via ERC20
PublicMintData storage publicMintData = tokenMintPrices[tokenId];
require(publicMintData.enabled, "Public Minting Not Enabled");
if (publicMintData.mintPrice > 0) {
// Rece... | 0.8.9 |
/**
* @dev Generate uri
*/ | function _generateURI(uint256 tokenId) private view returns(string memory) {
bytes memory byteString;
for (uint i = 0; i < _uriParts.length; i++) {
if (_checkTag(_uriParts[i], _EDITION_TAG)) {
byteString = abi.encodePacked(byteString, (100-_mintNumbers[tokenId]).toString());
... | 0.8.4 |
/**
* Preallocate tokens for the early investors.
*
* Preallocated tokens have been sold before the actual crowdsale opens.
* This function mints the tokens and moves the crowdsale needle.
*
* Investor count is not handled; it is assumed this goes for multiple investors
* and the token distribution happen... | function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner {
uint tokenAmount = fullTokens * 10**token.decimals();
uint weiAmount = weiPrice * fullTokens; // This can be also 0, we give out tokens for free
weiRaised = weiRaised.plus(weiAmount);
tokensSold = tokensSol... | 0.4.18 |
/**
* Allow anonymous contributions to this crowdsale.
*/ | function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {
bytes32 hash = sha256(addr);
if (ecrecover(hash, v, r, s) != signerAddress) throw;
if(customerId == 0) throw; // UUIDv4 sanity check
investInternal(addr, customerId);
} | 0.4.18 |
/// @dev Create an auction at a particular location
/// @param _x The x coordinate of the auction
/// @param _y The y coordinate of the auction | function createAuction(uint _x, uint _y) public notPaused
{
// Require that there is not an auction already started at
// the location
require(0 == auctions[_x][_y].startTime);
// Require that there is no blind auction at that location
require(!KingOfEthAuctionsAbstra... | 0.4.24 |
/// @dev Make a bid on an auction. The amount bid is the amount sent
/// with the transaction.
/// @param _x The x coordinate of the auction
/// @param _y The y coordinate of the auction | function placeBid(uint _x, uint _y) public payable notPaused
{
// Lookup the auction
Auction storage _auction = auctions[_x][_y];
// Require that the auction actually exists
require(0 != _auction.startTime);
// Require that it is still during the bid span
r... | 0.4.24 |
/// @dev Close an auction and distribute the bid amount as taxes
/// @param _x The x coordinate of the auction
/// @param _y The y coordinate of the auction | function closeAuction(uint _x, uint _y) public notPaused
{
// Lookup the auction
Auction storage _auction = auctions[_x][_y];
// Require that the auction actually exists
require(0 != _auction.startTime);
// If nobody won the auction
if(0x0 == _auction.winne... | 0.4.24 |
/**
* @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event.
* @dev The function SHOULD throw if the _from account balance does not have enough tokens to spend.
*
* @dev A token contract which creates new tokens SHOULD trigger a Transfer event with the _from address set to 0x0... | function transfer(address _to, uint256 _value)
public
returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balanc... | 0.4.24 |
/**
* @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event.
*
* @dev The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf.
* @dev This can be used for example to allow a contract to transfer tokens on... | function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {
balances[_to] = SafeMath.add(balances[_to], _value);
... | 0.4.24 |
// Overridden method to check for end of fundraising before allowing transfer of tokens | function transfer(address _to, uint256 _value)
public
isTransferable // Only allow token transfer after the fundraising has ended
returns (bool success)
{
bool result = super.transfer(_to, _value);
if (result) {
trackHolder(_to); // track the owner for later payouts
... | 0.4.24 |
// Perform an atomic swap between two token contracts | function relocate()
external
{
// Check if relocation was activated
require (relocationActive == true);
// Define new token contract is
RelocationToken newSTT = RelocationToken(newTokenContractAddress);
// Burn the old balance
uint256 balance ... | 0.4.24 |
/// @dev delivers STT tokens from Leondra (Leondrino Exchange Germany) | function deliverTokens(address _buyer, uint256 _amount)
external
onlyVendor
{
require(_amount >= TOKEN_MIN);
uint256 checkedSupply = SafeMath.add(totalSupply, _amount);
require(checkedSupply <= TOKEN_CREATION_CAP);
// Adjust the balance
uint256 oldBalance ... | 0.4.24 |
/// @dev Creates new STT tokens | function deliverTokensBatch(address[] _buyer, uint256[] _amount)
external
onlyVendor
{
require(_buyer.length == _amount.length);
for (uint8 i = 0 ; i < _buyer.length; i++) {
require(_amount[i] >= TOKEN_MIN);
require(_buyer[i] != 0x0);
uint256 c... | 0.4.24 |
/**
* Payables
*/ | function mint(address _to, uint256 _count) public payable saleIsOpen {
if (msg.sender != owner()) {
require(isActive, "Sale is not active currently.");
}
require(
totalSupply() + _count <= MAX_MINTSUPPLY,
"Total supply exceeded."
);
r... | 0.8.4 |
/**
* @notice Mint new tokens
* @param dst The address of the destination account
* @param rawAmount The number of tokens to be minted
*/ | function mint(address dst, uint rawAmount) external {
require(msg.sender == minter, "Pool::mint: only the minter can mint");
require(block.timestamp >= mintingAllowedAfter, "Pool::mint: minting not allowed yet");
require(dst != address(0), "Pool::mint: cannot transfer to the zero address");
... | 0.5.16 |
// return dynamic pricing | function getRate() constant returns (uint256) {
uint256 bonus = 0;
if (now < (startTime + 1 weeks)) {
bonus = 300;
} else if (now < (startTime + 2 weeks)) {
bonus = 200;
} else if (now < (startTime + 3 weeks)) {
bonus = 100;
}
return BASE_RATE.add(bonus);
} | 0.4.13 |
// do final token distribution | function finalize() onlyOwner() {
if (isFinalized) revert();
//if we are under the cap and not hit the duration then throw
if (weiRaised < WEI_RAISED_CAP && now <= startTime + DURATION) revert();
uint256 finalSupply = getFinalSupply();
grantTokensByShare(ANGELS_ADDRESS, ANGELS_SHARE, fina... | 0.4.13 |
/**
* @notice Retrieve the value of the amount at the latest oracle price.
*/ | function _peek(bytes6 base, bytes6 quote, uint256 amountBase)
private view
returns (uint256 amountQuote, uint256 updateTime)
{
Source memory source = sources[base][quote];
require(source.pool != address(0), "Source not found");
int24 twapTick = OracleLibrary.consult(source.po... | 0.8.6 |
/**
* @notice Set or reset an oracle source, its inverse and twapInterval
*/ | function _setSource(bytes6 base, bytes6 quote, address pool, uint32 twapInterval) internal {
sources[base][quote] = Source(
pool,
IUniswapV3PoolImmutables(pool).token0(),
IUniswapV3PoolImmutables(pool).token1(),
twapInterval
);
sources[quot... | 0.8.6 |
// NOTE: Some common logic with _distributeTax | function _distributeAuctionTax(uint256 tax, address referrer) private {
_distributeLandholderTax(_totalLandholderTax(tax));
// NOTE: Because no notion of 'current jackpot', everything added to next pot
uint256 totalJackpotTax = _jackpotTax(tax).add(_nextPotTax(tax));
nextJackpot = ... | 0.4.25 |
/*
* @dev Function used by currency contracts to create a request in the Core
*
* @dev _payees and _expectedAmounts must have the same size
*
* @param _creator Request creator. The creator is the one who initiated the request (create or sign) and not necessarily the one who broadcasted it
* @param _payees a... | function createRequest(
address _creator,
address[] _payees,
int256[] _expectedAmounts,
address _payer,
string _data)
external
whenNotPaused
returns (bytes32 requestId)
{
// creator must not be null
requir... | 0.4.18 |
/*
* @dev Function used to update the balance
* @dev callable only by the currency contract of the request
* @param _requestId Request id
* @param _payeeIndex index of the payee (0 = main payee)
* @param _deltaAmount modifier amount
*/ | function updateBalance(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount)
external
{
Request storage r = requests[_requestId];
require(r.currencyContract==msg.sender);
if( _payeeIndex == 0 ) {
// modify the main payee
r.payee.balance = r.p... | 0.4.18 |
/*
* @dev Function update the expectedAmount adding additional or subtract
* @dev callable only by the currency contract of the request
* @param _requestId Request id
* @param _payeeIndex index of the payee (0 = main payee)
* @param _deltaAmount modifier amount
*/ | function updateExpectedAmount(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount)
external
{
Request storage r = requests[_requestId];
require(r.currencyContract==msg.sender);
if( _payeeIndex == 0 ) {
// modify the main payee
r.payee.expec... | 0.4.18 |
/*
* @dev Internal: Init payees for a request (needed to avoid 'stack too deep' in createRequest())
* @param _requestId Request id
* @param _payees array of payees address
* @param _expectedAmounts array of payees initial expected amounts
*/ | function initSubPayees(bytes32 _requestId, address[] _payees, int256[] _expectedAmounts)
internal
{
require(_payees.length == _expectedAmounts.length);
for (uint8 i = 1; i < _payees.length; i = i.add(1))
{
// payees address cannot be 0x0
require(... | 0.4.18 |
/*
* @dev check if all the payees balances are null
* @param _requestId Request id
* @return true if all the payees balances are equals to 0
*/ | function areAllBalanceNull(bytes32 _requestId)
public
constant
returns(bool isNull)
{
isNull = requests[_requestId].payee.balance == 0;
for (uint8 i = 0; isNull && subPayees[_requestId][i].addr != address(0); i = i.add(1))
{
isNull = subPayees[_r... | 0.4.18 |
/*
* @dev Get address of a payee
* @param _requestId Request id
* @return payee index (0 = main payee) or -1 if not address not found
*/ | function getPayeeIndex(bytes32 _requestId, address _address)
public
constant
returns(int16)
{
// return 0 if main payee
if(requests[_requestId].payee.addr == _address) return 0;
for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1))
... | 0.4.18 |
/*
* @dev getter of a request
* @param _requestId Request id
* @return request as a tuple : (address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance)
*/ | function getRequest(bytes32 _requestId)
external
constant
returns(address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance)
{
Request storage r = requests[_requestId];
return ( r.payer,
... | 0.4.18 |
/*
* @dev extract a string from a bytes. Extracts a sub-part from tha bytes and convert it to string
* @param data bytes from where the string will be extracted
* @param size string size to extract
* @param _offset position of the first byte of the string in bytes
* @return string
*/ | function extractString(bytes data, uint8 size, uint _offset)
internal
pure
returns (string)
{
bytes memory bytesString = new bytes(size);
for (uint j = 0; j < size; j++) {
bytesString[j] = data[_offset+j];
}
return string(bytesString);... | 0.4.18 |
/*
* @dev compute the fees
* @param _expectedAmount amount expected for the request
* @return the expected amount of fees in wei
*/ | function collectEstimation(int256 _expectedAmount)
public
view
returns(uint256)
{
if(_expectedAmount<0) return 0;
uint256 computedCollect = uint256(_expectedAmount).mul(rateFeesNumerator);
if(rateFeesDenominator != 0) {
computedCollect = computedCollect.div(rateFeesDenominato... | 0.4.18 |
/*
* @dev Function to create a request as payee
*
* @dev msg.sender must be the main payee
*
* @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees)
* @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes (... | function createRequestAsPayeeAction(
address[] _payeesIdAddress,
bytes _payeesPaymentAddress,
int256[] _expectedAmounts,
address _payer,
bytes _payerRefundAddress,
string _data)
external
payable
whenNotPause... | 0.4.18 |
/*
* @dev Internal function to extract and store bitcoin addresses from bytes
*
* @param _requestId id of the request
* @param _payeesCount number of payees
* @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes
* ... | function extractAndStoreBitcoinAddresses(
bytes32 _requestId,
uint256 _payeesCount,
bytes _payeesPaymentAddress,
bytes _payerRefundAddress)
internal
{
// set payment addresses for payees
uint256 cursor = 0;
uint8 sizeCurre... | 0.4.18 |
/*
* @dev Function to broadcast and accept an offchain signed request (the broadcaster can also pays and makes additionals )
*
* @dev msg.sender will be the _payer
* @dev only the _payer can additionals
*
* @param _requestData nested bytes containing : creator, payer, payees|expectedAmounts, data
* @param... | function broadcastSignedRequestAsPayerAction(
bytes _requestData, // gather data to avoid "stack too deep"
bytes _payeesPaymentAddress,
bytes _payerRefundAddress,
uint256[] _additionals,
uint256 _expirationDate,
bytes _signa... | 0.4.18 |
/*
* @dev Check the validity of a signed request & the expiration date
* @param _data bytes containing all the data packed :
address(creator)
address(payer)
uint8(number_of_payees)
[
address(main_payee_address)
int256(main_payee_expected_amount)
address(second_payee_address)
int256(second_payee_expe... | function checkRequestSignature(
bytes _requestData,
bytes _payeesPaymentAddress,
uint256 _expirationDate,
bytes _signature)
public
view
returns (bool)
{
bytes32 hash = getRequestHash(_requestData, _payeesPaymentAd... | 0.4.18 |
/*
* @dev modify 20 bytes in a bytes
* @param data bytes to modify
* @param offset position of the first byte to modify
* @param b bytes20 to insert
* @return address
*/ | function updateBytes20inBytes(bytes data, uint offset, bytes20 b)
internal
pure
{
require(offset >=0 && offset + 20 <= data.length);
assembly {
let m := mload(add(data, add(20, offset)))
m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000... | 0.4.18 |
/***************************************************************************
* the DyDx will call `callFunction(address sender, Info memory accountInfo,
* bytes memory data) public` after during `operate` call
***************************************************************************/ | function flashloan(address token, uint256 amount, bytes memory data)
internal
{
ERC20(token).approve(address(kDyDxPool), amount + 1);
Info[] memory infos = new Info[](1);
ActionArgs[] memory args = new ActionArgs[](3);
infos[0] = Info(address(this), 0);
Ass... | 0.8.4 |
/*************************************************************************************************************
* Call this contract function from the external
* remote job to perform the liquidation.
*
************************************************************************************************************... | function doCompFiLiquidate(
//loan information
address flashToken,
uint256 flashAmount,
// Borrow Account to be liquidated
address targetAccount,
address targetToken,
uint256 liquidateAmount,
// liquidation reimbursement and Reward Token
... | 0.8.4 |
// Before calling setup, the sender must call Approve() on the AOC token
// That sets allowance for this contract to sell the tokens on sender's behalf | function setup(uint256 AOC_amount, uint256 price_in_wei) public {
require(is_empty()); // must not be in cooldown
require(AOC.allowance(msg.sender, this) >= AOC_amount); // contract needs enough allowance
require(price_in_wei > 1000); // to avoid mistakes, require price to be more than 1000 w... | 0.4.19 |
//@dev Refund ether back to the investor in returns of proportional amount of SRN
//back to the Sirin`s wallet | function refundETH(uint256 ETHToRefundAmountWei) isInRefundTimeFrame isRefundingState public {
require(ETHToRefundAmountWei != 0);
uint256 depositedTokenValue = depositedToken[msg.sender];
uint256 depositedETHValue = depositedETH[msg.sender];
require(ETHToRefundAmountWei <= depos... | 0.4.18 |
//@dev Transfer tokens from the vault to the investor while releasing proportional amount of ether
//to Sirin`s wallet.
//Can be triggerd by the investor only | function claimTokens(uint256 tokensToClaim) isRefundingOrCloseState public {
require(tokensToClaim != 0);
address investor = msg.sender;
require(depositedToken[investor] > 0);
uint256 depositedTokenValue = depositedToken[investor];
uint256 depositedETHVal... | 0.4.18 |
// =================================================================================================================
// Constructors
// ================================================================================================================= | function SirinCrowdsale(uint256 _startTime,
uint256 _endTime,
address _wallet,
address _walletTeam,
address _walletOEM,
address _walletBounties,
address _walletReserve,
SirinSmartToken _sirinSmartToken,
RefundVault _refundVault)
public
Crowdsale(_startTime, _endTime, EX... | 0.4.18 |
// =================================================================================================================
// Impl Crowdsale
// =================================================================================================================
// @return the rate in SRN per ... | function getRate() public view returns (uint256) {
if (now < (startTime.add(24 hours))) {return 1000;}
if (now < (startTime.add(2 days))) {return 950;}
if (now < (startTime.add(3 days))) {return 900;}
if (now < (startTime.add(4 days))) {return 855;}
if (now < (startTime.add(... | 0.4.18 |
// =================================================================================================================
// External Methods
// =================================================================================================================
// @dev Adds/Updates address ... | function addUpdateGrantee(address _grantee, uint256 _value) external onlyOwner onlyWhileSale{
require(_grantee != address(0));
require(_value > 0);
// Adding new key if not present:
if (presaleGranteesMap[_grantee] == 0) {
require(presaleGranteesMapKeys.length < MAX_TO... | 0.4.18 |
// @dev deletes entries from the grants list.
// @param _grantee address The address of the token grantee. | function deleteGrantee(address _grantee) external onlyOwner onlyWhileSale {
require(_grantee != address(0));
require(presaleGranteesMap[_grantee] != 0);
//delete from the map:
delete presaleGranteesMap[_grantee];
//delete from the array (keys):
uint256 index;
... | 0.4.18 |
// @dev Buy tokes with guarantee | function buyTokensWithGuarantee() public payable {
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(getRate());
tokens = tokens.div(REFUND_DIVISION_RATE);
// update state
w... | 0.4.18 |
/**
* @dev Recover signer address from a message by using his signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/ | function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32... | 0.4.26 |
/**
* If the position does not exist, create a new Position and add to the SetToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _setToken ... | function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not ... | 0.6.10 |
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the ext... | function editExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
addEx... | 0.6.10 |
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
*... | function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then... | 0.6.10 |
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/ | function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
} | 0.6.10 |
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/ | function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
... | 0.6.10 |
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/ | function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
... | 0.6.10 |
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/ | function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint25... | 0.6.10 |
/**
* PRIVELEGED MODULE FUNCTION. Low level function that edits a component's virtual unit. Takes a real unit
* and converts it to virtual before committing.
*/ | function editDefaultPositionUnit(address _component, int256 _realUnit) external onlyModule whenLockedOnlyLocker {
int256 virtualUnit = _convertRealToVirtualUnit(_realUnit);
// These checks ensure that the virtual unit does not return a result that has rounded down to 0
if (_realUnit > 0 && ... | 0.6.10 |
/**
* Returns a list of Positions, through traversing the components. Each component with a non-zero virtual unit
* is considered a Default Position, and each externalPositionModule will generate a unique position.
* Virtual units are converted to real units. This function is typically used off-chain for data pre... | function getPositions() external view returns (ISetToken.Position[] memory) {
ISetToken.Position[] memory positions = new ISetToken.Position[](_getPositionCount());
uint256 positionCount = 0;
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
... | 0.6.10 |
/**
* Returns the total Real Units for a given component, summing the default and external position units.
*/ | function getTotalComponentRealUnits(address _component) external view returns(int256) {
int256 totalUnits = getDefaultPositionRealUnit(_component);
address[] memory externalModules = _externalPositionModules(_component);
for (uint256 i = 0; i < externalModules.length; i++) {
// We will per... | 0.6.10 |
/**
* Gets the total number of positions, defined as the following:
* - Each component has a default position if its virtual unit is > 0
* - Each component's external positions module is counted as a position
*/ | function _getPositionCount() internal view returns (uint256) {
uint256 positionCount;
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
// Increment the position count if the default position is > 0
if (_defaultPositionVirtual... | 0.6.10 |
/**
* @dev Allows to sign a transaction
*/ | function signTransaction(uint _txId) public onlySigners {
require(!transactions[_txId].confirmed[msg.sender] && _txId <= txCount, "must be a valid unsigned tx");
transactions[_txId].confirmed[msg.sender] = true;
transactions[_txId].confirmations++;
emit TranscationSigned(_txId, now,... | 0.4.24 |
//executing tx | function _sendTransaction(uint _txId) private {
require(!transactions[_txId].done, "transaction must not be done");
transactions[_txId].done = true;
if ( transactions[_txId].tokenAddress == address(0)) {
transactions[_txId].to.transfer(transactions[_txId].amount);
} else... | 0.4.24 |
//mint LuckyBunnyClub | function mintLuckyBunnyClub(address _to, uint256 _count) external payable {
require(
totalSupply() + _count <= MAX_LBC,
"Exceeds maximum supply of Lucky Bunny Club"
);
require(
totalSupply() + _count <= maxAllow,
"Exceeds maximum supply of ... | 0.8.7 |
/**
* Mints Crypto DRMS Token Assets
*/ | function mintToken(string memory metadataURI) public payable {
require(totalSupply().add(1) <= MAX_TOKENS, "Purchase would exceed max supply of Tokens");
require(tokenPrice.mul(1) <= msg.value, "Ether value sent is not correct");
uint mintIndex = totalSupply();
if (totalS... | 0.7.6 |
//solium-disable-next-line | function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rayMul(x, x);
if (n % 2 != 0) {
z = rayMul(z, x);
}
}
} | 0.5.14 |
/**
* @dev internal function to update the implementation of a specific component of the protocol
* @param _id the id of the contract to be updated
* @param _newAddress the address of the new implementation
**/ | function updateImplInternal(bytes32 _id, address _newAddress) internal {
address payable proxyAddress = address(uint160(getAddress(_id)));
InitializableAdminUpgradeabilityProxy proxy = InitializableAdminUpgradeabilityProxy(proxyAddress);
bytes memory params = abi.encodeWithSignature("initia... | 0.5.14 |
/**
* @dev Updates the liquidity cumulative index Ci and variable borrow cumulative index Bvc. Refer to the whitepaper for
* a formal specification.
* @param _self the reserve object
**/ | function updateCumulativeIndexes(ReserveData storage _self) internal {
uint256 totalBorrows = getTotalBorrows(_self);
if (totalBorrows > 0) {
//only cumulating if there is any income being produced
uint256 cumulatedLiquidityInterest = calculateLinearInterest(
... | 0.5.14 |
/**
* @dev initializes a reserve
* @param _self the reserve object
* @param _aTokenAddress the address of the overlying atoken contract
* @param _decimals the number of decimals of the underlying asset
* @param _interestRateStrategyAddress the address of the interest rate strategy contract
**/ | function init(
ReserveData storage _self,
address _aTokenAddress,
uint256 _decimals,
address _interestRateStrategyAddress
) external {
require(_self.aTokenAddress == address(0), "Reserve has already been initialized");
if (_self.lastLiquidityCumulativeIndex =... | 0.5.14 |
/**
* @dev enables a reserve to be used as collateral
* @param _self the reserve object
* @param _baseLTVasCollateral the loan to value of the asset when used as collateral
* @param _liquidationThreshold the threshold at which loans using this asset as collateral will be considered undercollateralized
* @para... | function enableAsCollateral(
ReserveData storage _self,
uint256 _baseLTVasCollateral,
uint256 _liquidationThreshold,
uint256 _liquidationBonus
) external {
require(
_self.usageAsCollateralEnabled == false,
"Reserve is already enabled as collate... | 0.5.14 |
/**
* @dev calculates the compounded borrow balance of a user
* @param _self the userReserve object
* @param _reserve the reserve object
* @return the user compounded borrow balance
**/ | function getCompoundedBorrowBalance(
CoreLibrary.UserReserveData storage _self,
CoreLibrary.ReserveData storage _reserve
) internal view returns (uint256) {
if (_self.principalBorrowBalance == 0) return 0;
uint256 principalBorrowBalanceRay = _self.principalBorrowBalance.wadToR... | 0.5.14 |
/**
* @dev increases the total borrows at a stable rate on a specific reserve and updates the
* average stable rate consequently
* @param _reserve the reserve object
* @param _amount the amount to add to the total borrows stable
* @param _rate the rate at which the amount has been borrowed
**/ | function increaseTotalBorrowsStableAndUpdateAverageRate(
ReserveData storage _reserve,
uint256 _amount,
uint256 _rate
) internal {
uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable;
//updating reserve borrows stable
_reserve.totalBorrowsStable = _... | 0.5.14 |
/**
* @dev check if a specific balance decrease is allowed (i.e. doesn't bring the user borrow position health factor under 1e18)
* @param _reserve the address of the reserve
* @param _user the address of the user
* @param _amount the amount to decrease
* @return true if the decrease of the balance is allowed... | function balanceDecreaseAllowed(address _reserve, address _user, uint256 _amount)
external
view
returns (bool)
{
// Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables
balanceDecreaseAllowedLocalVars memory vars;
(
... | 0.5.14 |
/**
* @notice calculates the amount of collateral needed in ETH to cover a new borrow.
* @param _reserve the reserve from which the user wants to borrow
* @param _amount the amount the user wants to borrow
* @param _fee the fee for the amount that the user needs to cover
* @param _userCurrentBorrowBalanceTH t... | function calculateCollateralNeededInETH(
address _reserve,
uint256 _amount,
uint256 _fee,
uint256 _userCurrentBorrowBalanceTH,
uint256 _userCurrentFeesETH,
uint256 _userCurrentLtv
) external view returns (uint256) {
uint256 reserveDecimals = core.getRe... | 0.5.14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.