comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
// From compound's _moveDelegates
// Keep track of votes. "Delegates" is a misnomer here | function trackVotes(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
... | 0.6.11 |
/**
* repays bond token, any user can call it
*/ | function withdraw(uint256 tokenId) external {
// check if token exists
require(
IBondToken(_bond).hasToken(tokenId),
"bond token id does not exist");
address user = _msgSender();
// get token properties
( uint256 value, /* uint256 interest */, uint256 ma... | 0.6.3 |
/* Private allocation functions */ | function _calculatePoolMax() private {
uint256[] memory poolMax = new uint256[](combinedPoolAllocation.length);
for (uint256 i = 0; i < combinedPoolAllocation.length; i++) {
uint256 max = 0;
for (uint256 j = 0; j < combinedPoolAllocation[i].length; j++) {
max += c... | 0.6.12 |
/* PUBLIC ADMIN ONLY */ | function withdraw() public payable override nonReentrant {
require(
hasRole(OWNER_ROLE, _msgSender()),
"must have owner role to withdraw"
);
uint256 remainder = (address(this).balance);
uint256 division = remainder.div(100);
for (uint8 i = 0; i < splitAddr... | 0.6.12 |
/**
* @notice Cannot be used for already spawned positions
* @notice Token using as main collateral must be whitelisted
* @notice Depositing tokens must be pre-approved to vault address
* @notice position actually considered as spawned only when usdpAmount > 0
* @dev Spawns new positions
* @param asset The ... | function spawn(address asset, uint mainAmount, uint usdpAmount) public nonReentrant {
require(usdpAmount != 0, "Unit Protocol: ZERO_BORROWING");
// check whether the position is spawned
require(vault.getTotalDebt(asset, msg.sender) == 0, "Unit Protocol: SPAWNED_POSITION");
// ora... | 0.7.6 |
/**
* @notice Cannot be used for already spawned positions
* @notice WETH must be whitelisted as collateral
* @notice position actually considered as spawned only when usdpAmount > 0
* @dev Spawns new positions using ETH
* @param usdpAmount The amount of USDP token to borrow
**/ | function spawn_Eth(uint usdpAmount) public payable nonReentrant {
require(usdpAmount != 0, "Unit Protocol: ZERO_BORROWING");
// check whether the position is spawned
require(vault.getTotalDebt(vault.weth(), msg.sender) == 0, "Unit Protocol: SPAWNED_POSITION");
// oracle availabil... | 0.7.6 |
/**
* @notice Position should be spawned (USDP borrowed from position) to call this method
* @notice Depositing tokens must be pre-approved to vault address
* @notice Token using as main collateral must be whitelisted
* @dev Deposits collaterals and borrows USDP to spawned positions simultaneously
* @param as... | function depositAndBorrow(
address asset,
uint mainAmount,
uint usdpAmount
)
public
spawned(asset, msg.sender)
nonReentrant
{
require(usdpAmount != 0, "Unit Protocol: ZERO_BORROWING");
_depositAndBorrow(asset, msg.sender, mainAmount, usdpAmount);
... | 0.7.6 |
/**
* @notice Tx sender must have a sufficient USDP balance to pay the debt
* @dev Withdraws collateral and repays specified amount of debt simultaneously
* @param asset The address of token using as main collateral
* @param mainAmount The amount of main collateral token to withdraw
* @param usdpAmount The am... | function withdrawAndRepay(
address asset,
uint mainAmount,
uint usdpAmount
)
public
spawned(asset, msg.sender)
nonReentrant
{
// check usefulness of tx
require(mainAmount != 0, "Unit Protocol: USELESS_TX");
uint debt = vault.debts(asset, m... | 0.7.6 |
/**
* @notice Tx sender must have a sufficient USDP balance to pay the debt
* @dev Withdraws collateral and repays specified amount of debt simultaneously converting WETH to ETH
* @param ethAmount The amount of ETH to withdraw
* @param usdpAmount The amount of USDP token to repay
**/ | function withdrawAndRepay_Eth(
uint ethAmount,
uint usdpAmount
)
public
spawned(vault.weth(), msg.sender)
nonReentrant
{
// check usefulness of tx
require(ethAmount != 0, "Unit Protocol: USELESS_TX");
uint debt = vault.debts(vault.weth(), msg.sende... | 0.7.6 |
// ensures that borrowed value is in desired range | function _ensureCollateralization(
address asset,
address user,
uint mainUsdValue_q112
)
internal
view
{
// USD limit of the position
uint usdLimit = mainUsdValue_q112 * vaultManagerParameters.initialCollateralRatio(asset) / Q112 / 100;
// reve... | 0.7.6 |
/// WALK THE PLANK /// | function walkPlank() external whenNotPaused nonReentrant {
require(tx.origin == msg.sender, "Only EOA");
require(_pendingPlankCommitId[msg.sender] == 0, "Already have pending mints");
uint16 totalPirats = uint16(potm.getTotalPirats());
uint16 totalPending = pendingMintAmt + pendingPl... | 0.8.7 |
/// For creating Rich Token | function _createRich(string _name, address _owner, uint256 _price) private {
Rich memory _richtoken = Rich({
name: _name
});
uint256 newRichId = richtokens.push(_richtoken) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never ... | 0.4.18 |
/**
* @dev Updates parameters of the position to the current ones
* @param asset The address of the main collateral token
* @param user The owner of a position
**/ | function update(address asset, address user) public hasVaultAccess notLiquidating(asset, user) {
// calculate fee using stored stability fee
uint debtWithFee = getTotalDebt(asset, user);
tokenDebts[asset] = tokenDebts[asset].sub(debts[asset][user]).add(debtWithFee);
debts[asset][us... | 0.7.6 |
/**
* @dev Increases position's debt and mints USDP token
* @param asset The address of the main collateral token
* @param user The address of a position's owner
* @param amount The amount of USDP to borrow
**/ | function borrow(
address asset,
address user,
uint amount
)
external
hasVaultAccess
notLiquidating(asset, user)
returns(uint)
{
require(vaultParameters.isOracleTypeEnabled(oracleType[asset][user], asset), "Unit Protocol: WRONG_ORACLE_TYPE");
upd... | 0.7.6 |
/**
* @dev Deletes position and transfers collateral to liquidation system
* @param asset The address of the main collateral token
* @param positionOwner The address of a position's owner
* @param initialPrice The starting price of collateral in USDP
**/ | function triggerLiquidation(
address asset,
address positionOwner,
uint initialPrice
)
external
hasVaultAccess
notLiquidating(asset, positionOwner)
{
// reverts if oracle type is disabled
require(vaultParameters.isOracleTypeEnabled(oracleType[asset][... | 0.7.6 |
// Functions
// Transaction overview:
// 1. User approves transfer of token to AtomicSwap contract (triggered by the frontend)
// 2. User calls AtomicSwap.swapExactTokensAndMint() (triggered by the frontend)
// 2.1 AtomicSwap transfers token from user to itself (internal tx)
// 2.2 AtomicSwap approves IUniswapV2R... | function swapExactTokensAndMint(
uint256 tokenAmountIn,
uint256 collateralAmountOut,
address[] calldata tokenSwapPath,
ISynthereumPoolOnChainPriceFeed synthereumPool,
ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams
)
public
returns (
uint256 collateralOut,
IERC20 s... | 0.6.12 |
// Transaction overview:
// 1. User approves transfer of token to AtomicSwap contract (triggered by the frontend)
// 2. User calls AtomicSwap.swapTokensForExactAndMint() (triggered by the frontend)
// 2.1 AtomicSwap transfers token from user to itself (internal tx)
// 2.2 AtomicSwap approves IUniswapV2Router02 (i... | function swapTokensForExactAndMint(
uint256 tokenAmountIn,
uint256 collateralAmountOut,
address[] calldata tokenSwapPath,
ISynthereumPoolOnChainPriceFeed synthereumPool,
ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams
)
public
returns (
uint256 collateralOut,
IERC2... | 0.6.12 |
// Transaction overview:
// 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend)
// 2. User calls `AtomicSwap.redeemAndSwapExactTokens()` (triggered by the frontend)
// 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx)
// 2.2 `AtomicSwaps` approves transfer of sy... | function redeemAndSwapExactTokens(
uint256 amountTokenOut,
address[] calldata tokenSwapPath,
ISynthereumPoolOnChainPriceFeed synthereumPool,
ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams,
address recipient
)
public
returns (
uint256 collateralRedeemed,
IERC20... | 0.6.12 |
// Transaction overview:
// 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend)
// 2. User calls `AtomicSwap.redeemAndSwapTokensForExact()` (triggered by the frontend)
// 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx)
// 2.2 `AtomicSwaps` approves transfer of... | function redeemAndSwapTokensForExact(
uint256 amountTokenOut,
address[] calldata tokenSwapPath,
ISynthereumPoolOnChainPriceFeed synthereumPool,
ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams,
address recipient
)
public
returns (
uint256 collateralRedeemed,
IER... | 0.6.12 |
// ------------------------------------------------------------------------
// 100000 FWD Tokens per 1 ETH
// ------------------------------------------------------------------------ | function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 10000000000;
} else {
tokens = msg.value * 100000;
}
balances[msg.sender] = safeAdd(balances[msg.sender], to... | 0.4.26 |
// Transaction overview:
// 1. User calls AtomicSwap.swapExactETHAndMint() sending Ether (triggered by the frontend)
// 1.1 AtomicSwap calls IUniswapV2Router02.swapExactETHForTokens() to exchange ETH for collateral (internal tx)
// 1.2 AtomicSwap approves SynthereumPool (internal tx)
// 1.3 AtomicSwap calls Sy... | function swapExactETHAndMint(
uint256 collateralAmountOut,
address[] calldata tokenSwapPath,
ISynthereumPoolOnChainPriceFeed synthereumPool,
ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams
)
public
payable
returns (
uint256 collateralOut,
IERC20 synthToken,
u... | 0.6.12 |
// Transaction overview:
// 1. User calls AtomicSwap.swapETHForExactAndMint() sending Ether (triggered by the frontend)
// 1.1 AtomicSwap checks the return amounts from the IUniswapV2Router02.swapETHForExactTokens()
// 1.2 AtomicSwap saves the leftover ETH that won't be used in a variable
// 1.3 AtomicSwap cal... | function swapETHForExactAndMint(
uint256 collateralAmountOut,
address[] calldata tokenSwapPath,
ISynthereumPoolOnChainPriceFeed synthereumPool,
ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams
)
public
payable
returns (
uint256 collateralOut,
IERC20 synthToken,
... | 0.6.12 |
// Transaction overview:
// 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend)
// 2. User calls `AtomicSwap.redeemAndSwapExactTokensForETH()` (triggered by the frontend)
// 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx)
// 2.2 `AtomicSwaps` approves transfer... | function redeemAndSwapExactTokensForETH(
uint256 amountTokenOut,
address[] calldata tokenSwapPath,
ISynthereumPoolOnChainPriceFeed synthereumPool,
ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams,
address recipient
)
public
returns (
uint256 collateralRedeemed,
... | 0.6.12 |
// Transaction overview:
// 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend)
// 2. User calls `AtomicSwap.redeemAndSwapTokensForExactETH()` (triggered by the frontend)
// 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx)
// 2.2 `AtomicSwaps` approves transfer... | function redeemAndSwapTokensForExactETH(
uint256 amountTokenOut,
address[] calldata tokenSwapPath,
ISynthereumPoolOnChainPriceFeed synthereumPool,
ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams,
address recipient
)
public
returns (
uint256 collateralRedeemed,
... | 0.6.12 |
// Checks if a pool is registered with the SynthereumRegistry | function checkPoolRegistration(ISynthereumPoolOnChainPriceFeed synthereumPool)
internal
view
returns (IERC20 collateralInstance)
{
ISynthereumRegistry poolRegistry =
ISynthereumRegistry(
synthereumFinder.getImplementationAddress(
SynthereumInterfaces.PoolRegistry
)
... | 0.6.12 |
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _f... | function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
... | 0.8.7 |
// Sends all avaibile balances and creates LP tokens
// Possible ways this could break addressed
// 1) Multiple calls and resetting amounts - addressed with boolean
// 2) Failed WETH wrapping/unwrapping addressed with checks
// 3) Failure to create LP tokens, addressed with checks
// 4) Unacceptable division errors . A... | function addLiquidityToUniswapPxWETHPair() public {
require(liquidityGenerationOngoing() == false, "Liquidity generation onging");
require(LPGenerationCompleted == false, "Liquidity generation already finished");
totalETHContributed = address(this).balance;
IUniswapV2Pair pair = IUni... | 0.6.12 |
// Possible ways this could break addressed
// 1) No ageement to terms - added require
// 2) Adding liquidity after generaion is over - added require
// 3) Overflow from uint - impossible there isnt that much ETH aviable
// 4) Depositing 0 - not an issue it will just add 0 to tally | function addLiquidity(bool IreadParticipationAgreementInReadSectionAndIagreeFalseOrTrue) public payable {
require(liquidityGenerationOngoing(), "Liquidity Generation Event over");
require(IreadParticipationAgreementInReadSectionAndIagreeFalseOrTrue, "No agreement provided");
ethContributed[ms... | 0.6.12 |
// Possible ways this could break addressed
// 1) Accessing before event is over and resetting eth contributed -- added require
// 2) No uniswap pair - impossible at this moment because of the LPGenerationCompleted bool
// 3) LP per unit is 0 - impossible checked at generation function | function claimLPTokens() public {
require(LPGenerationCompleted, "Event not over yet");
require(ethContributed[msg.sender] > 0 , "Nothing to claim, move along");
IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair);
uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperE... | 0.6.12 |
// CHECK WHICH SERIES 2 ID CAN BE CLAIMED WITH SERIES 0 OR SERIES 1 TOKENS | function series2_token(CollectionToClaim _collection, uint256[] memory tokenIds) public view returns(uint256[] memory) {
require(mintStartIndexDrawn);
uint256[] memory ids = new uint256[](tokenIds.length);
if (_collection == CollectionToClaim.Series0) {
for(uint i = 0;... | 0.8.7 |
// CHECK IF SERIES 2 TOKEN IS CLAIMED | function check_claim(CollectionToClaim _collection, uint256[] memory tokenIds) public view returns(bool[] memory) {
uint256[] memory ids = series2_token(_collection, tokenIds);
bool[] memory isit = new bool[](tokenIds.length);
for(uint i = 0; i<tokenIds.length;i++) {
isit[i] = _e... | 0.8.7 |
// MINT THEM | function mint_series2(CollectionToClaim _collection, uint256[] memory tokenIds) public {
require(claimRunning && mintStartIndexDrawn);
require(tokenIds.length > 0 && tokenIds.length <= 15);
if (_collection == CollectionToClaim.Series0) {
for(uint i = 0; i<tokenIds.leng... | 0.8.7 |
/**
* @notice Determine winner by tallying votes
*/ | function _determineWinner(uint256 counter) internal view returns (uint256) {
uint256 winner = currentAxonsNumbersForVotes[counter][0];
uint256 highestVoteCount = 0;
for (uint i=0; i<10; i++) {
uint256 currentAxonNumber = currentAxonsNumbersForVotes[counter][i];
uin... | 0.8.10 |
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/ | function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
} | 0.4.24 |
/**
* @dev Adds two signed integers, reverts on overflow.
*/ | function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
} | 0.4.24 |
// Minting reserved tokens to the treasury wallet | function mintReserved(uint256 _mintAmount) external onlyOwner {
require(_mintAmount > 0, "amount to mint should be a positive number");
require(
reservedMinted + _mintAmount <= WT_MAX_RESERVED_COUNT,
"cannot mint the amount requested"
);
uint256 supply = currentI... | 0.8.4 |
// ------------------------------------------
// ASSETS ACCESS MANAGEMENT | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return notRevealedUr... | 0.8.4 |
/// Convert from a pixel's x, y coordinates to its section index
/// This is a helper function | function getSectionIndexFromRaw(
uint _x,
uint _y
) returns (uint) {
if (_x >= mapWidth) throw;
if (_y >= mapHeight) throw;
// Convert raw x, y to section identifer x y
_x = _x / 10;
_y = _y / 10;
//Get section_identifier from coords
... | 0.4.11 |
/// Get Section index based on its upper left x,y coordinates or "identifier"
/// coordinates
/// This is a helper function | function getSectionIndexFromIdentifier (
uint _x_section_identifier,
uint _y_section_identifier
) returns (uint) {
if (_x_section_identifier >= (mapWidth / 10)) throw;
if (_y_section_identifier >= (mapHeight / 10)) throw;
uint index = _x_section_identifier + (_y_section... | 0.4.11 |
/// Returns whether a section is available for purchase as a market sale | function sectionForSale(
uint _section_index
) returns (bool) {
if (_section_index >= sections.length) throw;
Section s = sections[_section_index];
// Has the user set the section as for_sale
if(s.for_sale)
{
// Has the owner set a "sell only to" a... | 0.4.11 |
/// Set an inidividual section as for sale at the provided price in wei.
/// The section will be available for purchase by any address. | function setSectionForSale(
uint _section_index,
uint256 _price
) {
if (_section_index >= sections.length) throw;
Section section = sections[_section_index];
if(section.owner != msg.sender) throw;
section.price = _price;
section.for_sale = true;
... | 0.4.11 |
/**
* @notice Constructor for contract. Sets token and beneficiary addresses.
* @param _token token address - supposed to be DGTX address
* @param _beneficiary recipient of received ethers
*/ | function Auction(address _token, address _beneficiary, uint _startTime, uint _maxBidInCentsPerAddress)
public
payable
Ownable()
{
require(_token != address(0));
require(_beneficiary != address(0));
require(_startTime > now);
require(_maxBid... | 0.4.19 |
/**
* @notice Fallback function.
* During the auction receives and remembers participants bids.
* After the sale is finished, withdraws tokens to participants.
* It is not allowed to bid from contract (e.g., multisig).
*/ | function () public payable {
if (msg.sender == owner) {
return;
}
require(now >= startTime);
require(!isContract(msg.sender));
if (!hasEnded()) {
require(msg.value >= TRANSACTION_MIN_IN_ETH);
bid(msg.sender, msg.value);
} els... | 0.4.19 |
/**
* @notice Get current price: dgtx to cents.
* 25 cents in the beginning and linearly decreases by 1 cent every hour until it reaches 1 cent.
* @return current token to cents price
*/ | function getPrice() public view returns (uint) {
if (now < startTime) {
return START_PRICE_IN_CENTS;
}
uint passedHours = (now - startTime) / 1 hours;
return (passedHours >= 24) ? MIN_PRICE_IN_CENTS : (25 - passedHours);
} | 0.4.19 |
/**
* @notice Function to receive transaction from oracle with new ETH rate.
* @dev Calls updateEthToCentsRate in one hour (starts update cycle)
* @param result string with new rate
*/ | function __callback(bytes32, string result) public {
require(msg.sender == oraclize_cbAddress());
uint newEthToCents = parseInt(result, 2); // convert string to cents
if (newEthToCents > 0) {
ethToCents = newEthToCents;
EthToCentsUpdated(ethToCents);
}
... | 0.4.19 |
/**
* @notice Function to transfer tokens to participants in the range [_from, _to).
* @param _from starting index in the range of participants to withdraw to
* @param _to index after the last participant to withdraw to
*/ | function distributeTokensRange(uint _from, uint _to) public {
require(hasEnded());
require(_from < _to && _to <= participants.length);
address recipient;
for (uint i = _from; i < _to; ++i) {
recipient = participants[i];
if (!withdrawn[recipient]) {
... | 0.4.19 |
/**
* @dev Function which records bids.
* @param _bidder is the address that bids
* @param _valueETH is value of THE bid in ether
*/ | function bid(address _bidder, uint _valueETH) internal {
uint price = getPrice();
uint bidInCents = _valueETH * ethToCents / 1 ether;
uint centsToAccept = bidInCents;
uint ethToAccept = _valueETH;
// Refund any ether above address bid limit
if (centsReceived[_bi... | 0.4.19 |
/**
* @dev Internal function to withdraw tokens by final price.
* @param _recipient participant to withdraw
*/ | function withdrawTokens(address _recipient) internal {
uint256 tokens = 0;
if (totalCentsCollected < totalTokens * MIN_PRICE_IN_CENTS / TOKEN_DECIMALS_MULTIPLIER) {
tokens = centsReceived[_recipient] * TOKEN_DECIMALS_MULTIPLIER / MIN_PRICE_IN_CENTS;
} else {
tokens =... | 0.4.19 |
/// Set a section region for sale at the provided price in wei.
/// The sections in the region will be available for purchase by any address. | function setRegionForSale(
uint _start_section_index,
uint _end_section_index,
uint _price
) {
if(_start_section_index > _end_section_index) throw;
if(_end_section_index > 9999) throw;
uint x_pos = _start_section_index % 100;
uint base_y_pos = (_start_... | 0.4.11 |
/// Set a section region starting in the top left at the supplied start section
/// index to and including the supplied bottom right end section index
/// for sale at the provided price in wei, to the provided address.
/// The sections in the region will be available for purchase only by the
/// provided address. | function setRegionForSaleToAddress(
uint _start_section_index,
uint _end_section_index,
uint _price,
address _only_sell_to
) {
if(_start_section_index > _end_section_index) throw;
if(_end_section_index > 9999) throw;
uint x_pos = _start_section_index %... | 0.4.11 |
/// Update a region of sections' cloud image_id and md5 to be redrawn on the
/// map starting at the top left start section index to and including the
/// bottom right section index. Fires a NewImage event with the top left
/// section index. If any sections not owned by the sender are in the region
/// they are ignore... | function setRegionImageDataCloud(
uint _start_section_index,
uint _end_section_index,
uint _image_id,
string _md5
) {
if (_end_section_index < _start_section_index) throw;
var (start_x, start_y) = getIdentifierFromSectionIndex(_start_section_index);
va... | 0.4.11 |
/// Set a single section as for sale at the provided price in wei only
/// to the supplied address. | function setSectionForSaleToAddress(
uint _section_index,
uint256 _price,
address _to
) {
if (_section_index >= sections.length) throw;
Section section = sections[_section_index];
if(section.owner != msg.sender) throw;
section.price = _price;
... | 0.4.11 |
/// Delist a region of sections for sale. Making the sections no longer
/// no longer available on the market. | function unsetRegionForSale(
uint _start_section_index,
uint _end_section_index
) {
if(_start_section_index > _end_section_index) throw;
if(_end_section_index > 9999) throw;
uint x_pos = _start_section_index % 100;
uint base_y_pos = (_start_section_index - (_st... | 0.4.11 |
/// Depreciated. Store the raw image data in the contract. | function setImageData(
uint _section_index
// bytes32 _row_zero,
// bytes32 _row_one,
// bytes32 _row_two,
// bytes32 _row_three,
// bytes32 _row_four,
// bytes32 _row_five,
// bytes32 _row_six,
// bytes32 _row_seven,
// bytes32 _... | 0.4.11 |
/// Set a section's image data to be redrawn on the map. Fires a NewImage
/// event. | function setImageDataCloud(
uint _section_index,
uint _image_id,
string _md5
) {
if (_section_index >= sections.length) throw;
Section section = sections[_section_index];
if(section.owner != msg.sender) throw;
section.image_id = _image_id;
sec... | 0.4.11 |
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/ | function buyTokens(address beneficiary) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaise... | 0.4.24 |
/** this can only be done once, so this oracle is solely for working with
* three AssetSwap contracts
* assetswap 0 is the ETH, at 2.5 leverage
* assetswap 1 is the SPX, at 10x leverage
* assetswap 2 is the BTC, at 2.5 leverage
*
*/ | function addAssetSwaps(address newAS0, address newAS1, address newAS2)
external
onlyAdmin
{
require(assetSwaps[0] == address(0));
assetSwaps[0] = newAS0;
assetSwaps[1] = newAS1;
assetSwaps[2] = newAS2;
readers[newAS0] = true;
readers[newAS1] =... | 0.5.15 |
/** Quickly fix an erroneous price, or correct the fact that 50% movements are
* not allowed in the standard price input
* this must be called within 60 minutes of the initial price update occurence
*/ | function editPrice(uint _ethprice, uint _spxprice, uint _btcprice)
external
onlyAdmin
{
require(now < lastUpdateTime + 60 minutes);
prices[0][currentDay] = _ethprice;
prices[1][currentDay] = _spxprice;
prices[2][currentDay] = _btcprice;
emit PriceUpdat... | 0.5.15 |
/**
* @return startDay relevant for trades done now
* pulls the day relevant for new AssetSwap subcontracts
* startDay 2 means the 2 slot (ie, the third) of prices will be the initial
* price for the subcontract. As 5 is the top slot, and rolls into slot 0
* the next week, the next pricing day is 1 when the c... | function getStartDay()
public
view
returns (uint8 _startDay)
{
if (nextUpdateSettle) {
_startDay = 5;
} else if (currentDay == 5) {
_startDay = 1;
} else {
_startDay = currentDay + 1;
}
} | 0.5.15 |
/// Transfer a region of sections and IPO tokens to the supplied address. | function transferRegion(
uint _start_section_index,
uint _end_section_index,
address _to
) {
if(_start_section_index > _end_section_index) throw;
if(_end_section_index > 9999) throw;
uint x_pos = _start_section_index % 100;
uint base_y_pos = (_start_se... | 0.4.11 |
// this function will only return the no of dai can pay till now | function getCurrentInstallment(address _addr) public view returns(uint256) {
require(registeredusers[_addr],'you are not registered');
if(block.timestamp > users[_addr].time){
return users[_addr].daiamount;
}
uint256 timeleft = users[_addr].time.su... | 0.6.12 |
/* only owner address can do manual refund
* used only if bet placed + oraclize failed to __callback
* filter LogBet by address and/or playerBetId:
* LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId... | function ownerRefundPlayer(bytes32 originalPlayerBetId, address sendTo, uint originalPlayerProfit, uint originalPlayerBetValue) public
onlyOwner
{
/* safely reduce pendingPayouts by playerProfit[rngId] */
maxPendingPayouts = safeSub(maxPendingPayouts, originalPlayerProfit);
/... | 0.4.10 |
/**************************************************** Public Interface for Stakers **************************************************************/ | function createNewStake(uint256 _amount, uint8 _lockupPeriod, bool _compound) public {
require(!paused, "New stakes are paused");
require(_isValidLockupPeriod(_lockupPeriod), "The lockup period is invalid");
require(_amount >= 5000000000000000000000, "You must stake at least 5000 LIT");
... | 0.5.12 |
// Will be called monthly, at the end of each month | function _accreditRewards() public onlyOwner {
uint256 totalToAccredit = getTotalRewardsToBeAccredited();
require(IERC20(litionToken).transferFrom(msg.sender, address(this), totalToAccredit), "Couldn't take the LIT from the sender");
for (uint256 i = 0; i < stakers.length; i++) {
... | 0.5.12 |
// Will be called every day to distribute the accumulated new MiningReward events coming from LitionRegistry | function _updateRewardsToBeAccredited(uint256 _fromMiningRewardBlock, uint256 _toMiningRewardBlock, uint256 _amount) public onlyOwner {
require(_fromMiningRewardBlock < _toMiningRewardBlock, "Invalid params");
require(_fromMiningRewardBlock > lastMiningRewardBlock, "Rewards already distributed");
... | 0.5.12 |
/**************************************************** Internal Admin - Lockups **************************************************************/ | function calculateFinishTimestamp(uint256 _timestamp, uint8 _lockupPeriod) public pure returns (uint256) {
uint16 year = Date.getYear(_timestamp);
uint8 month = Date.getMonth(_timestamp);
month += _lockupPeriod;
if (month > 12) {
year += 1;
month = month % 1... | 0.5.12 |
/**************************************************** Internal Admin - Validations **************************************************************/ | function _isValidLockupPeriod(uint8 n) internal pure returns (bool) {
if (n == 1) {
return true;
}
else if (n == 3) {
return true;
}
else if (n == 6) {
return true;
}
else if (n == 12) {
return true;
... | 0.5.12 |
// get back the BET before claimingPhase | function getRefund(uint _gameID) external {
require(now < games[_gameID].claimingPhaseStart - 1 days);
require(games[_gameID].tickets[msg.sender]>0);
games[_gameID].tickets[msg.sender] -= 1;
games[_gameID].numTickets -= 1;
uint refund = games[_gameID].ticketPrice * REFUND_PE... | 0.4.24 |
/// @dev Buy tokens function
/// @param beneficiary Address which will receive the tokens | function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(helper.isWhitelisted(beneficiary));
uint256 weiAmount = msg.value;
require(weiAmount > 0);
uint256 tokenAmount = 0;
if (isPresale()) {
/// Minimum contribution of 1 ether during pres... | 0.4.19 |
/// @dev Internal function used for calculating ICO discount percentage depending on levels | function getIcoDiscountPercentage() internal constant returns (uint8) {
if (tokensSoldIco <= icoDiscountLevel1) {
return icoDiscountPercentageLevel1;
} else if (tokensSoldIco <= icoDiscountLevel1.add(icoDiscountLevel2)) {
return icoDiscountPercentageLevel2;
} else {
return icoDiscou... | 0.4.19 |
/// @dev Internal function used to calculate amount of tokens based on discount percentage | function getTokenAmount(uint256 weiAmount, uint8 discountPercentage) internal constant returns (uint256) {
/// Less than 100 to avoid division with zero
require(discountPercentage >= 0 && discountPercentage < 100);
uint256 baseTokenAmount = weiAmount.mul(rate);
uint256 tokenAmount = baseTokenAmount... | 0.4.19 |
/// @dev Change discount percentages for different phases
/// @param _icoDiscountPercentageLevel1 Discount percentage of phase 1
/// @param _icoDiscountPercentageLevel2 Discount percentage of phase 2
/// @param _icoDiscountPercentageLevel3 Discount percentage of phase 3 | function changeIcoDiscountPercentages(uint8 _icoDiscountPercentageLevel1, uint8 _icoDiscountPercentageLevel2, uint8 _icoDiscountPercentageLevel3) public onlyOwner {
require(_icoDiscountPercentageLevel1 >= 0 && _icoDiscountPercentageLevel1 < 100);
require(_icoDiscountPercentageLevel2 >= 0 && _icoDiscountPercen... | 0.4.19 |
/**
Configure redemption amounts for each group. ONE token of _groupIdin results
in _amountOut number of _groupIdOut tokens
@param _groupIdIn The group ID of the token being redeemed
@param _groupIdIn The group ID of the token being received
@param _data The redemption config data input.
*/ | function setRedemptionConfig(uint256 _groupIdIn, uint256 _groupIdOut, address _tokenOut, RedemptionConfig calldata _data) external onlyOwner {
redemptionConfigs[_groupIdIn][_tokenOut] = RedemptionConfig({
groupIdOut: _groupIdOut,
amountOut: _data.amountOut,
burnOnRedemption: _data.burnOnRedemp... | 0.7.6 |
//Note: returns a boolean indicating whether transfer was successful | function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0)); //not sending to burn address
require(_value <= balances[msg.sender]); // If the sender has sufficient funds to send
require(_value>0);// and the amount is not zero or negative
... | 0.4.23 |
// low level token purchase function
//implements the logic for the token buying | function buyTokens(address beneficiary) public payable {
//tokens cannot be burned by sending to 0x0 address
require(beneficiary != address(0));
//token must adhere to the valid restrictions of the validPurchase() function, ie within time period and buying tokens within max/min limits
... | 0.4.23 |
// Function to have a way to add business logic to your crowdsale when buying | function getTokenAmount(uint256 weiAmount) internal returns(uint256) {
//Logic for pricing based on the Tiers of the crowdsale
// These bonus amounts and the number of tiers itself can be changed
/*This means that:
- If you purchase within the tier 1 ICO (earliest tier)
... | 0.4.23 |
/**
* @notice mint brand new RogueRhino nfts
* @param _numRhinos is the number of rhinos to mint
*/ | function mintRhino(uint256 _numRhinos) public payable saleIsLive {
require(tx.origin == msg.sender, "Humans only");
require(_numRhinos > 0, "0 mint");
require(_numRhinos < MINT_MAX, "20 max");
require(msg.value == (_numRhinos * mintPrice), "Wrong ETH");
_mintRhinos(msg.sender, _numRhinos);
} | 0.8.4 |
/**
* @notice mint rhinos from the two allowlists.
* Raging Rhinos got rugged. If you held Raging (rugged) Rhinos
* at the snapshot (Jan 25th 2022) you got on the Rogue allowlist.
* @dev you do not have to mint all your quota at once but
* you must pass the same sig and claimQuota each time yo... | function rogueListMint(
uint256 _numToMint,
bytes calldata _sig,
uint256 _claimQuota,
uint256 _listId
)
public
payable
presaleIsLive
{
//which allowlist is msg.sender in?
if (_listId == 1) { //rogue allowlist
require(msg.value == 0, "Wrong ETH");
} else if (_listId == 2) { //publi... | 0.8.4 |
/**
* @notice list all the rhinos in a wallet
* @dev useful for staking in future utility
* @dev don't call from a contract or you'll
* ruin yourself with gas
*/ | function walletOfOwner(address _addr)
public
virtual
view
returns (uint256[] memory)
{
uint256 ownerBal = balanceOf(_addr);
if (ownerBal == 0) {
return new uint256[](0);
} else {
uint256[] memory tokenList = new uint256[](ownerBal);
... | 0.8.4 |
///withdraw to trusted wallets | function withdraw() public {
//team shares assigned in constructor are access keys
require(teamShares[msg.sender] > 0, "Team only");
uint256 bal = address(this).balance;
for (uint256 mem = 0; mem < teamAddrs.length; mem++) {
address adi = teamAddrs[mem];
payable(adi).send(teamShares[adi] * bal / 1... | 0.8.4 |
/**
* @notice mint function called by multiple other functions
* @param _to recipient address
* @param _num number of rhinos to mint
*/ | function _mintRhinos(address _to, uint256 _num) internal {
uint256 _totalSupply = totalSupply; //temp var for gas efficiency
require(_totalSupply + _num < MAX_RHINOS, "Too few Rhinos left!");
for (uint256 r = 0; r < _num; r++) {
unchecked { //overflow checked above
_totalSupply++;
}
_safeMin... | 0.8.4 |
/**
* @notice was the correct hash signed by the msgSigner?
* @param _sig the signed hash to inspect
* @dev _sig should be a signed hash of the sender,
* this contract, their quota and the whitelist id.
* The signer is recovered and compared to msgSigner for validity.
*/ | function legitSigner(bytes memory _sig, uint256 _numToHash, uint256 _wlId)
private
view
returns (bool)
{
//hash the sender, this address, and a number
//this should be the same hash as signed in _sig
bytes32 checkHash = keccak256(abi.encodePacked(
msg.sender,
address(this),
_numToHash,
... | 0.8.4 |
/*
* Set the reward peroid. If only possible to set the reward period after last rewards have been
* expired.
*
* @param _periodStart timestamp of reward starting time
* @param _rewardsDuration the duration of rewards in seconds
*/ | function setPeriod(uint64 _periodStart, uint64 _rewardsDuration) public onlyOwner {
require(_periodStart >= block.timestamp, "OpenDAOStaking: _periodStart shouldn't be in the past");
require(_rewardsDuration > 0, "OpenDAOStaking: Invalid rewards duration");
Config memory cfg = config;
r... | 0.8.9 |
/*
* Returns the frozen rewards
*
* @returns amount of frozen rewards
*/ | function frozenRewards() public view returns(uint256) {
Config memory cfg = config;
uint256 time = block.timestamp;
uint256 remainingTime;
uint256 duration = uint256(cfg.periodFinish) - uint256(cfg.periodStart);
if (time <= cfg.periodStart) {
remainingTime = duratio... | 0.8.9 |
/*
* Staking specific amount of SOS token and get corresponding amount of veSOS
* as the user's share in the pool
*
* @param _sosAmount
*/ | function enter(uint256 _sosAmount) external {
require(_sosAmount > 0, "OpenDAOStaking: Should at least stake something");
uint256 totalSOS = getSOSPool();
uint256 totalShares = totalSupply();
sos.safeTransferFrom(msg.sender, address(this), _sosAmount);
if (totalShares == 0 || ... | 0.8.9 |
/*
* Redeem specific amount of veSOS to SOS tokens according to the user's share in the pool.
* veSOS will be burnt.
*
* @param _share
*/ | function leave(uint256 _share) external {
require(_share > 0, "OpenDAOStaking: Should at least unstake something");
uint256 totalSOS = getSOSPool();
uint256 totalShares = totalSupply();
_burn(msg.sender, _share);
uint256 _sosAmount = _share * totalSOS / totalShares;
so... | 0.8.9 |
/**
* @dev Public Mint
*/ | function mintPublic() public payable nonReentrant
{
require(tx.origin == msg.sender, "Bad.");
require(publicMintState, "Public mint is currently paused.");
uint256 currentSupply = totalSupply();
require(currentSupply < MAX_SUPPLY, "Maximum amount of NFTs have been minted.");
... | 0.8.11 |
/**
* @dev Whitelist Mint
*/ | function mintWhitelist(uint256 _amount) public nonReentrant
{
require(tx.origin == msg.sender, "Bad.");
require(whitelistMintState, "Whitelist mint is currently paused.");
uint256 currentSupply = totalSupply();
require(_amount <= whitelist[msg.sender], "You can't mint that many... | 0.8.11 |
/**
* @dev Requests updating rate from oraclize.
*/ | function updateRate() external onlyBank returns (bool) {
if (getPrice() > this.balance) {
OraclizeError("Not enough ether");
return false;
}
bytes32 queryId = oraclize_query(oracleConfig.datasource, oracleConfig.arguments, gasLimit, priceLimit);
if... | 0.4.23 |
/**
* @dev Oraclize default callback with the proof set.
* @param myid The callback ID.
* @param result The callback data.
* @param proof The oraclize proof bytes.
*/ | function __callback(bytes32 myid, string result, bytes proof) public {
require(validIds[myid] && msg.sender == oraclize_cbAddress());
rate = Helpers.parseIntRound(result, 3); // save it in storage as 1/1000 of $
delete validIds[myid];
callbackTime = now;
waitQuery = false;... | 0.4.23 |
// ######################
// ##### ONLY OWNER #####
// ###################### | function addLiquidity() external onlyOwner() {
require(!m_TradingOpened,"trading is already open");
m_Whitelist[_msgSender()] = true;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
m_UniswapV2Router = _uniswapV2Router;
m... | 0.8.4 |
/**
* @dev Set the limit of a class.
* @param _id The id of the class.
* @param _limit The limit of the class.
*/ | function setLimit(uint256 _id, uint256 _limit) external onlyOwner {
Info storage info = table[_id];
Action action = getAction(info.limit, _limit);
if (action == Action.Insert) {
info.index = array.length;
info.limit = _limit;
array.push(_id);
}
... | 0.4.25 |
/**
* @dev Get the required action.
* @param _prev The old limit.
* @param _next The new limit.
* @return The required action.
*/ | function getAction(uint256 _prev, uint256 _next) private pure returns (Action) {
if (_prev == 0 && _next != 0)
return Action.Insert;
if (_prev != 0 && _next == 0)
return Action.Remove;
if (_prev != _next)
return Action.Update;
return Action.None... | 0.4.25 |
/**
* @dev Transfer tokens in batches (of adresses)
* @param _vaddr address The address which you want to send tokens from
* @param _vamounts address The address which you want to transfer to
*/ | function batchAssignTokens(address[] _vaddr, uint[] _vamounts, uint[] _vDefrostClass ) onlyOwner {
require ( batchAssignStopped == false );
require ( _vaddr.length == _vamounts.length && _vaddr.length == _vDefrostClass.length);
//Looping into input arrays to assign target amount to each given address
... | 0.4.23 |
/*
* An accurate estimate for the total amount of assets (principle + return)
* that this strategy is currently managing, denominated in terms of want tokens.
*/ | function estimatedTotalAssets() public override view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 _claimableComp = predictCompAccrued();
uint256 currentComp = IERC20(comp).balanceOf(address(this));
// Use touch price. it doesnt matter if... | 0.6.12 |
//predicts our profit at next report | function expectedReturn() public view returns (uint256) {
uint256 estimateAssets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
if (debt > estimateAssets) {
return 0;
} else {
return estimateAssets - debt;
}
... | 0.6.12 |
//WARNING. manipulatable and simple routing. Only use for safe functions | function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) {
if (_amount == 0) {
return 0;
}
address[] memory path;
if(start == weth){
path = new address[](2);
path[0] = weth;
path[1] = end;
... | 0.6.12 |
//Calculate how many blocks until we are in liquidation based on current interest rates
//WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look
//equation. Compound doesn't include compounding for most blocks
//((deposits*colateralThreshold - borrows) / (borrows*borrowra... | function getblocksUntilLiquidation() public view returns (uint256) {
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 borrrowRate = cToken.borrowRatePerBlock();
uint256 supplyRate = c... | 0.6.12 |
// This function makes a prediction on how much comp is accrued
// It is not 100% accurate as it uses current balances in Compound to predict into the past | function predictCompAccrued() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
if (deposits == 0) {
return 0; // should be impossible to have 0 balance and positive comp accrued
}
//comp speed is amount to borrow or deposit (s... | 0.6.12 |
//sell comp function | function _disposeOfComp() internal {
uint256 _comp = IERC20(comp).balanceOf(address(this));
if (_comp > minCompToSell) {
address[] memory path = new address[](3);
path[0] = comp;
path[1] = weth;
path[2] = address(want);
IUni(uniswapR... | 0.6.12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.