comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
// @dev launch presale | function launchPresale(uint16 daysLaunch ) public onlyOwner returns (bool) {
require(SALE_START == 0, "sale start already set!" );
require(daysLaunch > 0, "days launch must be positive");
require(startingIndex != 0, "index must be set to launch presale!");
SALE_START = getNow() + (daysL... | 0.8.7 |
// senders mint for cc buyers | function sendCCEx(address _target, uint numberOfTokens) public {
require(senders[_msgSender()] == true, "not confirmed to send");
uint256 ts = totalSupply();
require(numberOfTokens > 0 );
require(saleIsActive, "Sale must be active to mint tokens");
require(numberOfToke... | 0.8.7 |
// Transfers the remaining funds to the collector pool | function withdraw() external onlyOwner {
uint256 totalFunds = address(this).balance;
require(totalFunds > 0, "Insufficient Funds");
// Send funds via call function for the collector pool funds
(bool success, ) = address(collectorPool).call{value: totalFunds}("");
require(success, "Failed To Distribu... | 0.8.9 |
/**
* @dev Make the lottery tickets untransferable
* So that nobody makes a new address, buys myobu and then sends the tickets to another address
* And then sells the myobu. And if he wins the lottery, it won't count it.
*
* While it could transfer the ticketsBought, that would make it so anyone can buy tickets, a... | function _beforeTokenTransfer(
address from,
address to,
uint256
) internal pure override {
/// @dev Only mint or burn is allowed
require(
from == address(0) || to == address(0),
"FoF: Cannot transfer tickets"
);
} | 0.8.4 |
/**
* @return The amount of myobu that someone needs to hold to buy lottery tickets
* @param user: The address
* @param amount: The amount of tickets
*/ | function myobuNeededForTickets(address user, uint256 amount)
public
view
override
returns (uint256)
{
uint256 minimumMyobuBalance = _lottery[_lotteryID.current()]
.minimumMyobuBalance;
uint256 myobuNeededForEachTicket = _lottery[_lotteryID.current()]
.... | 0.8.4 |
/**
* @dev Buys tickets with ETH, requires that he has at least (myobuNeededForTickets()) myobu,
* and then loops over how much tickets he needs and mints the ERC721 tokens
* If there is too much ETH sent, refund unneeded ETH
* Emits TicketsBought()
*/ | function buyTickets() external payable override onlyOn {
uint256 ticketPrice = _lottery[_lotteryID.current()].ticketPrice;
uint256 amountOfTickets = msg.value / ticketPrice;
require(amountOfTickets != 0, "FoF: Not enough ETH");
require(
_myobu.balanceOf(_msgSender()) >=
... | 0.8.4 |
/**
* @dev Function to calculate how much fees that will be taken
* @return The amount of fees that will be taken
* @param currentTokenID: The latest tokenID
* @param ticketPrice: The price of 1 ticket
* @param ticketFee: The percentage of the ticket to take as a fee
* @param lastClaimedTokenID_: The last token I... | function calculateFees(
uint256 currentTokenID,
uint256 ticketPrice,
uint256 ticketFee,
uint256 lastClaimedTokenID_
) public pure override returns (uint256) {
uint256 unclaimedTicketSales = currentTokenID - lastClaimedTokenID_;
return ((unclaimedTicketSales * ticketPr... | 0.8.4 |
/**
* @dev Function that distributes the reward, requests for randomness, completes at fulfillRandomness()
* If nobody bought a ticket, makes rewardsClaimed true and returns nothing
* Checks for _inClaimReward so that its not called more than once, wasting LINK.
*/ | function claimReward()
external
override
onlyEnded
returns (bytes32 requestId)
{
require(!_rewardClaimed, "FoF: Reward already claimed");
require(!_inClaimReward, "FoF: Reward is being claimed");
/// @dev So it doesn't fail if nobody bought any tickets
... | 0.8.4 |
/**
* @dev Gets a winner and sends him the jackpot, if he doesn't have myobu at the time of winning
* send the _feeReceiver the jackpot
* Emits LotteryWon();
*/ | function fulfillRandomness(bytes32, uint256 randomness) internal override {
/// @dev Get a random number in range of the token IDs
uint256 x = _lottery[_lotteryID.current()].startingTokenID;
uint256 y = _tokenID;
/// @dev The winning token ID
uint256 resultInRange = x + (randomne... | 0.8.4 |
/**
* @dev Starts a new lottery, Can only be done by the owner.
* Emits LotteryCreated()
* @param lotteryLength: How long the lottery will be in seconds
* @param ticketPrice: The price of a ticket in ETH
* @param ticketFee: The percentage of the ticket price that is sent to the fee receiver
* @param percentageToK... | function createLottery(
uint256 lotteryLength,
uint256 ticketPrice,
uint256 ticketFee,
uint256 percentageToKeepForNextLottery,
uint256 minimumMyobuBalance,
uint256 myobuNeededForEachTicket,
uint256 percentageToKeepOnNotEnoughMyobu
) external onlyOwner onlyEnde... | 0.8.4 |
/**
* @dev Extends the duration of the current lottery and checks if its the new duration is over 1 month, reverts if it is
* @param extraTime: The time in seconds to extend it by
*/ | function extendCurrentLottery(uint256 extraTime) external onlyOwner onlyOn {
uint256 currentLotteryEnd = _lottery[_lotteryID.current()].endTimestamp;
uint256 currentLotteryStart = _lottery[_lotteryID.current()]
.startTimestamp;
require(
currentLotteryEnd + extraTime <= curren... | 0.8.4 |
// METADATA FUNCTIONS | function tokenURI(uint256 _tokenId) public view returns (string memory){
//Note: changed visibility to public
require(isValidToken(_tokenId));
// uint maxLength = 50;
uint[50] memory reversed;
// uint i = 0;
string memory uri = string(__uriBase);
stri... | 0.7.4 |
/** @dev The stakeSpent for a payment channel will increase when a stake address makes payments and decrease
* when the Coordinator issues refunds. This function changes the totalClaimableAmount of Rook on the contract
* accordingly.
*/ | function adjustTotalClaimableAmountByStakeSpentChange(
uint256 _oldStakeSpent,
uint256 _newStakeSpent
) internal {
if (_newStakeSpent < _oldStakeSpent) {
// If a stake address's new stakeSpent is less than their previously stored stakeSpent, then a refund was
// iss... | 0.8.6 |
/** @notice Withdraw remaining stake from the payment channel after the withdrawal timelock has concluded.
* @dev Closing the payment channel zeros out all payment channel state for the stake address aside from the
* channelNonce which is incremented. This is to prevent any channel reuse edge cases. A stake addr... | function executeTimelockedWithdrawal(
address _stakeAddress
) public {
uint256 _channelNonce = channelNonce[_stakeAddress];
require(getCurrentWithdrawalTimelock(_stakeAddress) > 0, "must initiate timelocked withdrawal first");
require(block.timestamp > getCurrentWithdrawalTimelock(_s... | 0.8.6 |
/** @notice Instantly withdraw remaining stake in payment channel.
* @dev To perform an instant withdrawal a Keeper will ask the coordinator for an instant withdrawal signature.
* This `data` field in the commitment used to produce the signature should be populated with
* `INSTANT_WITHDRAWAL_COMMITMENT_DAT... | function executeInstantWithdrawal(
StakeCommitment memory _commitment
) external {
require(msg.sender == _commitment.stakeAddress, "only stakeAddress can perform instant withdrawal");
require(_commitment.stakeSpent <= stakedAmount[_commitment.stakeAddress], "cannot spend more than is staked"... | 0.8.6 |
/** @notice Claim accumulated earnings. Claim amounts are determined off-chain and signed by the claimGenerator
* address. Claim amounts are calculated as a pre-determined percentage of a Keeper's bid, and Keeper bids
* are signed by both Keepers and the Coordinator, so claim amount correctness is eas... | function claim(
address _claimAddress,
uint256 _earningsToDate,
bytes memory _claimGeneratorSignature
) external {
require(_earningsToDate > userClaimedAmount[_claimAddress], "nothing to claim");
address recoveredClaimGeneratorAddress = ECDSA.recover(
ECDSA.toEt... | 0.8.6 |
/**
* @notice Set the default desired CRatio for a specific collateral type
* @param collateralType The name of the collateral type to set the default CRatio for
* @param cRatio New default collateralization ratio
*/ | function setDefaultCRatio(bytes32 collateralType, uint256 cRatio) external override isAuthorized {
uint256 scaledLiquidationRatio = oracleRelayer.liquidationCRatio(collateralType) / CRATIO_SCALE_DOWN;
require(scaledLiquidationRatio > 0, "SaviourCRatioSetter/invalid-scaled-liq-ratio");
require(b... | 0.6.7 |
/*
* @notice Sets the collateralization ratio that a SAFE should have after it's saved
* @dev Only an address that controls the SAFE inside GebSafeManager can call this
* @param collateralType The collateral type used in the safe
* @param safeID The ID of the SAFE to set the desired CRatio for. This ID should be re... | function setDesiredCollateralizationRatio(bytes32 collateralType, uint256 safeID, uint256 cRatio)
external override controlsSAFE(msg.sender, safeID) {
uint256 scaledLiquidationRatio = oracleRelayer.liquidationCRatio(collateralType) / CRATIO_SCALE_DOWN;
address safeHandler = safeManager.safes(safeI... | 0.6.7 |
// function getTraitAtIndex(uint256 index) public view returns (string memory name, uint8 bitWidth, uint8 offset, bool active){
// require(index < numTraits.current(), "invalid index");
// return (traits[index].name,
// traits[index].bitWidth,
// traits[index].offset,
// traits[index].ac... | function setTrait(uint256 index, string memory name, uint8 bitWidth, uint8 offset, bool active) public onlyOwner {
require(index < numTraits.current(), "invalid index");
traits[index].name = name;
traits[index].bitWidth = bitWidth;
traits[index].offset = offset;
traits[index... | 0.6.12 |
//transfer GRT | function _transfer_GRT(address sender, address recipient, uint256 amount) internal virtual{
require(recipient == address(0), "ERC20: transfer to the zero address");
require(sender != address(0), "ERC20: transfer from the zero address");
_beforeTokenTransfer(sender, recipient, amount);
... | 0.6.6 |
/**
* Calculates the maximum quantity of the currentSet that can be redeemed. This is defined
* by how many naturalUnits worth of the Set there are.
*
* @return Maximum quantity of the current Set that can be redeemed
*/ | function calculateStartingSetQuantity()
internal
view
returns (uint256)
{
uint256 currentSetBalance = vault.getOwnerBalance(address(currentSet), address(this));
uint256 currentSetNaturalUnit = currentSet.naturalUnit();
// Rounds the redemption quantity to a m... | 0.5.7 |
/*
* Provide a signal to the keeper that `tend()` should be called.
* (keepers are always reimbursed by yEarn)
*
* NOTE: this call and `harvestTrigger` should never return `true` at the same time.
* tendTrigger should be called with same gasCost as harvestTrigger
*/ | function tendTrigger(uint256 gasCost) public override view returns (bool) {
if (harvestTrigger(gasCost)) {
//harvest takes priority
return false;
}
if (getblocksUntilLiquidation() <= blocksToLiquidationDangerZone) {
return true;
}
... | 0.6.12 |
// Flash loan DXDY
// amount desired is how much we are willing for position to change | function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) {
uint256 amount = amountDesired;
ISoloMargin solo = ISoloMargin(SOLO);
// Not enough want in DyDx. So we take all we can
uint256 amountInSolo = want.balanceOf(SOLO);
if (amountInSol... | 0.6.12 |
// ------------------------------------------------------------------------
// Initialisation
// ------------------------------------------------------------------------ | function init(Data storage self, address owner, string symbol, string name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public {
require(!self.initialised);
self.initialised = true;
self.owner = owner;
self.symbol = symbol;
self.name = name;
... | 0.4.19 |
// ------------------------------------------------------------------------
// ecrecover from a signature rather than the signature in parts [v, r, s]
// The signature format is a compact form {bytes32 r}{bytes32 s}{uint8 v}.
// Compact means, uint8 is not padded to 32 bytes.
//
// An invalid signature results in the a... | function ecrecoverFromSig(bytes32 hash, bytes sig) public pure returns (address recoveredAddress) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) return address(0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// ... | 0.4.19 |
// ------------------------------------------------------------------------
// Get CheckResult message
// ------------------------------------------------------------------------ | function getCheckResultMessage(Data storage /*self*/, BTTSTokenInterface.CheckResult result) public pure returns (string) {
if (result == BTTSTokenInterface.CheckResult.Success) {
return "Success";
} else if (result == BTTSTokenInterface.CheckResult.NotTransferable) {
return ... | 0.4.19 |
// ------------------------------------------------------------------------
// Token functions
// ------------------------------------------------------------------------ | function transfer(Data storage self, address to, uint tokens) public returns (bool success) {
// Owner and minter can move tokens before the tokens are transferable
require(self.transferable || (self.mintable && (msg.sender == self.owner || msg.sender == self.minter)));
require(!self.account... | 0.4.19 |
// ------------------------------------------------------------------------
// Anyone can call this method to verify whether the bttsToken contract at
// the specified address was deployed using this factory
//
// Parameters:
// tokenContract the bttsToken contract address
//
// Return values:
// valid di... | function verify(address tokenContract) public view returns (
bool valid,
address owner,
uint decimals,
bool mintable,
bool transferable
) {
valid = _verify[tokenContract];
if (valid) {
BTTSToken t = BTTSToken(tokenContract);
... | 0.4.19 |
// ------------------------------------------------------------------------
// Any account can call this method to deploy a new BTTSToken contract.
// The owner of the BTTSToken contract will be the calling account
//
// Parameters:
// symbol symbol
// name name
// decimals number of decim... | function deployBTTSTokenContract(
string symbol,
string name,
uint8 decimals,
uint initialSupply,
bool mintable,
bool transferable
) public returns (address bttsTokenAddress) {
bttsTokenAddress = new BTTSToken(
msg.sender,
sym... | 0.4.19 |
/**
* @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the
* Transfer event.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/ | function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool _success)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_v... | 0.4.24 |
/*
This function allows users to purchase Video Game.
The price is automatically multiplied by 2 after each purchase.
Users can purchase multiple video games.
*/ | function purchaseVideoGame(uint _videoGameId) public payable {
require(msg.value == videoGames[_videoGameId].currentPrice);
require(isPaused == false);
// Calculate the 10% value
uint256 devFee = (msg.value / 10);
// Calculate the video game owner commission on this sale... | 0.4.20 |
/// @notice Returns all the relevant information about a specific color.
/// @param _tokenId The tokenId of the color of interest. | function getColor(uint256 _tokenId) public view returns (
string colorName,
uint256 sellingPrice,
address owner,
uint256 previousPrice,
address[5] previousOwners
) {
Color storage color = colors[_tokenId];
colorName = color.name;
sellingPrice = colorIndexToPrice[_tokenId];
... | 0.4.18 |
/// For creating Color | function _createColor(string _name, address _owner, uint256 _price) private {
Color memory _color = Color({
name: _name
});
uint256 newColorId = colors.push(_color) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this... | 0.4.18 |
// Reduce some liquidity - use to enhance pump effectiveness during bull run! | function createLiquidityCrisis()
external
payable
override
{
require (block.timestamp >= minLiquidityCrisisTime, "It's too early to create a liquidity crisis");
require (msg.sender == owner || msg.value >= 100 ether, "This can only be called by paying 100 ETH");
... | 0.7.0 |
/// @dev Creates a new random number | function newRandomNumber(uint256 id, bytes32 fileHash)
public
onlyOperators()
nonZeroId(id)
idMustBeUnique(id)
nonZeroFileHash(fileHash)
hashMustBeUnique(fileHash)
{
randomNumbers[id].id = id;
randomNumbers[id].fileHash = fileHash;
... | 0.8.0 |
/// @dev Bulk creation to reduce gas fees. | function bulkRandomNumbers(
uint256[] memory ids,
bytes32[] memory fileHashes
) public onlyOperators() {
require(
ids.length == fileHashes.length,
"Arrays must be the same length"
);
for (uint256 i = 0; i < ids.length; i++) {
new... | 0.8.0 |
/// @dev Generate the random number | function generateRandomNumber(uint256 id)
public
onlyOperators()
nonZeroId(id)
idMustExists(id)
{
require(
randomNumbers[id].requestId == 0,
"Request already exists for this ID."
);
require(LINK.balanceOf(address(this)) >= fee... | 0.8.0 |
/// @dev Generate the random numbers | function bulkGenerateRandomNumbers(uint256[] memory ids)
public
onlyOperators()
{
require(
LINK.balanceOf(address(this)) >= fee * ids.length,
"Not enough LINK"
);
for (uint256 i = 0; i < ids.length; i++) {
require(ids[i] != 0, "I... | 0.8.0 |
/**
* Passes execution into virtual function.
*
* Can only be called by assigned asset proxy.
*
* @return success.
* @dev function is final, and must not be overridden.
*/ | function _performTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyProxy() returns(bool) {
if (isICAP(_to)) {
return _transferFromToICAPWithReference(_from, bytes32(_to) << 96, _value, _reference, _sender);
}
return ... | 0.4.23 |
/// For creating Pow | function _createPow(string _name, address _owner, uint256 _price, uint _gameId, uint _gameItemId) private {
Pow memory _pow = Pow({
name: _name,
gameId: _gameId,
gameItemId: _gameItemId
});
uint256 newPowId = pows.push(_pow) - 1;
// It's probably never going to happen, 4 billi... | 0.4.20 |
/// @dev Assigns ownership of a specific Pow to an address. | function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of pow is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
powIndexToOwner[_tokenId] = _to;
// When creating new pows _from is 0x0, but we can't account that ad... | 0.4.20 |
/* GET FUNCTIONS */ | function getGemStone(uint256 p_tokenId) public view returns (string memory) {
require(_exists(p_tokenId),"Not minted");
uint256 gemId = findGemId(p_tokenId, "GEMSTONE");
string[8] memory gemStoneNames = [
"Blue Diamond",
"Pink Diamond",
"Diamond",
... | 0.8.7 |
// FINDER functions
// Find Gem Id can find anything from an array with 8 elements (note: weighting table in place) | function findGemId(uint256 p_tokenId, string memory p_seedString) internal view returns (uint256) {
uint8[8] memory weightings = [
1,
2,
4,
8,
16,
32,
56,
78
];
uint256 rand = random(abi.encodePacked(... | 0.8.7 |
// Find Gem Power can find anything from an array with 13 elements (note: weighting table in place) | function findGemPowerId(uint256 p_tokenId, string memory p_seedPhrase) internal view returns (uint256) {
uint8[13] memory weightings = [
1,
4,
7,
10,
15,
20,
25,
30,
45,
55,
65,
... | 0.8.7 |
// Loot minting (free) | function mintWithLoot(uint p_lootId) public payable nonReentrant {
require(lootContract.ownerOf(p_lootId) == msg.sender, "Not loot owner");
_safeMint(msg.sender, p_lootId);
s_randomSeeds[p_lootId] = uint256(blockhash(block.number - 2))
^ block.timestamp
^ block.difficulty... | 0.8.7 |
// Owner reserved minting (100 items) | function ownerMint(uint p_tokenId) public payable nonReentrant onlyOwner {
require(p_tokenId > 12000 && p_tokenId <= 12100, "Token ID invalid");
_safeMint(msg.sender, p_tokenId);
s_randomSeeds[p_tokenId] = uint256(blockhash(block.number - 2))
^ block.timestamp
... | 0.8.7 |
/// @dev Returns list of owners.
/// @return List of owner addresses. | function getOwners() public view returns (address[] memory) {
uint256 len = EnumerableSet.length(_owners);
address[] memory o = new address[](len);
for (uint256 i = 0; i < len; i++) {
o[i] = EnumerableSet.at(_owners, i);
}
return o;
} | 0.8.0 |
/// @dev Helper function to fail if resolution number is already in use. | function resolutionAlreadyUsed(uint256 resNum) public view {
require(
// atleast one of the address must not be equal to address(0)
!(resolutions[resNum].oldAddress != address(0) ||
resolutions[resNum].newAddress != address(0)),
"Resolution is already in ... | 0.8.0 |
/// @notice Vote Yes on a Resolution.
/// @dev The owner who tips the agreement threshold will pay the gas for performing the resolution.
/// @return TRUE if the resolution passed | function voteResolution(uint256 resNum) public onlyOwners() returns (bool) {
ownerVotes[msg.sender][resNum] = true;
// If the reolution has already passed, then do nothing
if (isResolutionPassed(resNum)) {
return true;
}
// If the resolution can now be passe... | 0.8.0 |
/// @dev Create a resolution to repalce an owner. Performs replacement if threshold is 1 or zero. | function createResolutionReplaceOwner(address oldOwner, address newOwner)
public
onlyOwners()
{
isValidAddress(oldOwner);
isValidAddress(newOwner);
require(
EnumerableSet.contains(_owners, oldOwner),
"oldOwner is not an owner."
);
... | 0.8.0 |
/// @dev Create a resolution to replace the operator account. Performs replacement if threshold is 1 or zero. | function createResolutionReplaceOperator(
address oldOperator,
address newOperator
) public onlyOwners() {
isValidAddress(oldOperator);
isValidAddress(newOperator);
require(
EnumerableSet.contains(_operators, oldOperator),
"oldOperator is not a... | 0.8.0 |
/// @dev Create a resolution and check if we can call perofrm the resolution with 1 vote. | function createResolution(
uint256 resType,
address oldAddress,
address newAddress,
bytes32[] memory extra
) internal {
uint256 resNum = nextResolution;
nextResolution++;
resolutionAlreadyUsed(resNum);
resolutions[resNum].resType = resType;
... | 0.8.0 |
/// @dev Performs the resolution and then marks it as passed. No checks prevent it from performing the resolutions. | function _performResolution(uint256 resNum) internal {
if (resolutions[resNum].resType == resTypeAddOwner) {
_addOwner(resolutions[resNum].newAddress);
} else if (resolutions[resNum].resType == resTypeRemoveOwner) {
_removeOwner(resolutions[resNum].oldAddress);
} els... | 0.8.0 |
// Seeds setup. | function rndSeeds(address[] calldata seeds, uint16[] calldata weis) public onlyOwner {
require(rnds.length() == 0, "!rnds");
require(seeds.length == weis.length, "!same length");
uint256 sum = 0;
uint256 len = seeds.length;
for(uint256 i = 0; i < len; ++i) {
i... | 0.6.12 |
// function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
// address token,
// uint liquidity,
// uint amountTokenMin,
// uint amountETHMin,
// address to,
// uint deadline,
// bool approveMax, uint8 v, bytes32 r, bytes32 s
// ) external virtual override returns (uint amountETH)... | function _swap(uint[] memory amounts, address[] memory path, address _to, uint discount) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = ExcavoLibrary.sortTokens(input, output);
uint amo... | 0.6.6 |
/**
* @dev function to withdraw balance
*/ | function withdraw(address customerAddress) internal {
uint256 _dividends = dividendsOf(customerAddress);
payoutsTo[customerAddress] += (int256) (_dividends);
_dividends = _dividends.add(refBalance[customerAddress]);
refBalance[customerAddress] = 0;
if (_dividends > 0) {
address payab... | 0.5.6 |
/**
* @dev function to reinvest of dividends
*/ | function reinvest() onlyParticipant public {
uint256 _dividends = showMyDividends(false);
address _customerAddress = msg.sender;
payoutsTo[_customerAddress] += (int256) (_dividends);
_dividends = _dividends.add(refBalance[_customerAddress]);
refBalance[_customerAddress] = 0;
uint256 _t... | 0.5.6 |
/**
* @dev function to show ether/tokens ratio
* @param _eth eth amount
*/ | function showEthToTokens(uint256 _eth) public view returns (uint256 _tokensReceived, uint256 _newTokenPrice) {
uint256 b = actualTokenPrice.mul(2).sub(tokenPriceIncremental);
uint256 c = _eth.mul(2);
uint256 d = SafeMath.add(b**2, tokenPriceIncremental.mul(4).mul(c));
// d = b**2 + 4 * a * c;
// (... | 0.5.6 |
/**
* @dev function to show tokens/ether ratio
* @param _tokens tokens amount
*/ | function showTokensToEth(uint256 _tokens) public view returns (uint256 _eth, uint256 _newTokenPrice) {
// (2 * a1 - delta * (n - 1)) / 2 * n
_eth = SafeMath.sub(actualTokenPrice.mul(2), tokenPriceIncremental.mul(_tokens.sub(1e18)).div(decimalShift)).div(2).mul(_tokens).div(decimalShift);
_newTokenPrice = ac... | 0.5.6 |
/**
* @dev function to buy tokens, calculate bonus, dividends, fees
* @param _inRawEth eth amount
* @param _ref address of referal
*/ | function buyTokens(address customerAddress, uint256 _inRawEth, address _ref) internal returns (uint256) {
uint256 _dividends = inBonus_p.mul(_inRawEth);
uint256 _inEth = _inRawEth.sub(_dividends);
uint256 _tokens = 0;
uint256 startPrice = actualTokenPrice;
if (_ref != address(0) && ... | 0.5.6 |
/**
* @dev function to sell tokens, calculate dividends, fees
* @param _inRawTokens eth amount
*/ | function sellTokens(uint256 _inRawTokens) internal returns (uint256) {
address _customerAddress = msg.sender;
require(_inRawTokens <= balanceOf(_customerAddress));
uint256 _tokens = _inRawTokens;
uint256 _eth = 0;
uint256 startPrice = actualTokenPrice;
_eth = tokensToEth(_tokens);
_... | 0.5.6 |
/**
* @notice Function to recover funds
* Owner is assumed to be governance or AcknoLedger trusted party for helping users
* @param token Address of token to be rescued
* @param destination User address
* @param amount Amount of tokens
*/ | function recoverToken(
address token,
address destination,
uint256 amount
) external onlyGovernance {
require(token != destination, "Invalid address");
require(destination != address(0), "Invalid address");
require(IERC20(token).transfer(destination, amount), "Retriev... | 0.8.9 |
/// @notice given an amount of money returns how many tokens the money will result in with the
/// current round's pricing | function calculateTokenCount(uint money) public view returns (uint count, uint change) {
require(isSaleOpen, "sale is no longer open and tokens can't be purchased");
// get current token price
uint price = _rounds[_currentRound].tokenPrice;
uint capacityLeft = _rounds[_currentRound].capacityLeft;
... | 0.5.8 |
/// increases the round or closes the sale if tokens are sold out | function updateRounds(uint tokens) private {
Round storage currentRound = _rounds[_currentRound];
currentRound.capacityLeft -= tokens;
if (currentRound.capacityLeft <= 0) {
if (_currentRound == _rounds.length - 1) {
isSaleOpen = false;
emit SaleCompleted();
} else {
_cur... | 0.5.8 |
/**
@dev Deposit funds into the contract. The caller must send (for Coin) or approve (for ERC20) value equal to or `denomination` of this instance.
@param _commitment the note commitment, which is PedersenHash(nullifier + secret)
*/ | function deposit(bytes32 _commitment) external payable nonReentrant {
require(!commitments[_commitment], "The commitment has been submitted");
require(msg.value >= coinDenomination, "insufficient coin amount");
uint256 refund = msg.value - coinDenomination;
uint32 insertedIndex = _insert(_commitment);
... | 0.5.17 |
/** @dev whether an array of notes is already spent */ | function isSpentArray(bytes32[] calldata _nullifierHashes) external view returns(bool[] memory spent) {
spent = new bool[](_nullifierHashes.length);
for(uint i = 0; i < _nullifierHashes.length; i++) {
if (isSpent(_nullifierHashes[i])) {
spent[i] = true;
}
}
} | 0.5.17 |
/// @notice casts a vote for a given choice | function cast(uint choice) public {
require(choice < numChoices, "invalid choice to vote on");
require(voters[msg.sender] == false, "you've already cast your vote, can't vote twice");
address voter = msg.sender;
uint256 weight = token.balanceOf(voter);
require(weight > 0, "you don't own any tokens... | 0.5.8 |
/**
* @notice min amount needed to become king
* @param amount - how much you want to add
* @param message - your kings message
*/ | function claimThrone(uint256 amount, string memory message) external whenNotPaused nonReentrant {
require(amount >= minAmountNeeded(), "check minAmountNeeded()");
uint256 comission = _calcPercentage(amount, 100);
tuna.transferFrom(msg.sender, address(this), comission);
tuna.transferFrom(msg.sender, king, amoun... | 0.8.12 |
/* Transfer function when _to represents a contract address, with the caveat
that the contract needs to implement the tokenFallback function in order to receive tokens */ | function transferToContract(address _to, uint _value, bytes _data) internal returns (bool success) {
balances[msg.sender] -= _value;
balances[_to] += _value;
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.se... | 0.4.11 |
/* Infers if whether _address is a contract based on the presence of bytecode */ | function isContract(address _address) internal returns (bool is_contract) {
uint length;
if (_address == 0) return false;
assembly {
length := extcodesize(_address)
}
if(length > 0) {
return true;
} else {
return false;
... | 0.4.11 |
/* Remove the specified amount of the tokens from the supply permanently */ | function burn(uint256 _value, bytes _data) returns (bool success) {
if (balances[msg.sender] >= _value
&& _value > 0) {
balances[msg.sender] -= _value;
_currentSupply -= _value;
Burn(msg.sender, _value, _currentSupply, _data);
return true;
... | 0.4.11 |
//Generate random number between 1 & max | function rand(uint max, uint256 seed) private returns (uint256 result){
uint256 factor = seed * 100 / max;
uint256 lastBlockNumber = block.number - 1;
uint256 hashVal = uint256(blockhash(lastBlockNumber));
return (uint256((uint256(hashVal) / factor)) % max) + 1;
} | 0.5.10 |
/**
* @notice This function returns base,ask and bid range ticks for the given pool
* - It fetches the current tick and tick spacing of the pool
* - Multiples the tick spacing with pools base and range multipliers
* - Calculates pools twap and verifies whether it is under the maxtwapdeviation
* - If the ... | function getTicks(address _pool)
external
override
onlyExchange
returns (
int24 baseLower,
int24 baseUpper,
int24 bidLower,
int24 bidUpper,
int24 askLower,
int24 askUpper
)
{
(int24 tick, int24 ti... | 0.7.6 |
/**
* @notice This function updates the range,base threshold and twap values specific to a pool
* @param params: struct values of PoolStrategy struct, the values can be inspected from interface
* @param _pool<: pool address
**/ | function changeStrategy(PoolStrategy memory params, address _pool)
public
onlyGovernance
{
PoolStrategy memory oldStrategy = poolStrategy[_pool];
validateStrategy(params.baseThreshold, IUniswapV3Pool(_pool).tickSpacing());
emit StrategyUpdated(
oldStrategy,
... | 0.7.6 |
/**
* @notice This function calculates the current twap of pool
* @param pool: pool address
**/ | function calculateTwap(address pool) internal view returns (int24 twap) {
uint128 inRangeLiquidity = IUniswapV3Pool(pool).liquidity();
if (inRangeLiquidity == 0) {
(uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
twap = TickMath.getTickAtSqrtRatio(sqrtPriceX96);... | 0.7.6 |
/**
* @notice This function fetches the twap of pool from the observation
* @param _pool: pool address
**/ | function getTwap(address _pool) public view override returns (int24 twap) {
IUniswapV3Pool uniswapV3Pool = IUniswapV3Pool(_pool);
(, , uint16 observationIndex, uint16 observationCardinality, , , ) = uniswapV3Pool
.slot0();
(uint32 lastTimeStamp, , , ) = uniswapV3Pool.observations(
... | 0.7.6 |
/**
* @notice This function calculates the lower tick value from the current tick
* @param tick: current tick of the pool
* @param tickSpacing: tick spacing according to the fee tier
**/ | function _floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
} | 0.7.6 |
//at least min_amount blocks to call this | function earnReward(uint min_amount) public onlyOwner{
require(block.number.safeSub(last_earn_block) >= earn_gap, "not long enough");
last_earn_block = block.number;
uint256 index = get_pid(ICurvePool(current_pool).get_lp_token_addr());
(,,,address crvRewards,,) = convex_booster.poolInfo(index);
... | 0.5.10 |
/// @notice Transfer "_value" tokens from "_from" to "_to" if "msg.sender" is allowed.
/// @dev Allows for an approved third party to transfer tokens from one
/// address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _v... | function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
//Address shouldn't be null
require(_from != 0x0);
require(_to != 0x0);
require(_to != address(this));
require(balances[_from] >= _value);
require(allowed[_from][msg.sende... | 0.4.21 |
/// @notice Approves "_who" to transfer "_value" tokens from "msg.sender" to any address.
/// @dev Sets approved amount of tokens for the spender. Returns success.
/// @param _who Address of allowed account.
/// @param _value Number of approved tokens.
/// @return Returns success of function call. | function approve(address _who, uint256 _value) public returns (bool) {
// Address shouldn't be null
require(_who != 0x0);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_who, 0)` if it is not
// already 0 ... | 0.4.21 |
/// @dev GoToken Contract constructor function sets GoToken dutch auction
/// contract address and assigns the tokens to the auction.
/// @param auction_address Address of dutch auction contract.
/// @param wallet_address Address of wallet.
/// @param initial_supply Number of initially provided token units (indivisible... | function GoToken(address auction_address, address wallet_address, uint256 initial_supply) public
{
// Auction address should not be null.
require(auction_address != 0x0);
require(wallet_address != 0x0);
// Initial supply is in indivisible units e.g. 50e24
require(init... | 0.4.21 |
/// @dev GoToken Contract constructor function sets the starting price,
/// price constant and price exponent for calculating the Dutch Auction price.
/// @param _wallet_address Wallet address to which all contributed ETH will be forwarded. | function GoTokenDutchAuction(
address _wallet_address,
address _whitelister_address,
address _distributor_address,
uint256 _price_start,
uint256 _price_constant1,
uint256 _price_exponent1,
uint256 _price_constant2,
uint256 _price_exponent2)
... | 0.4.21 |
/// @notice Set "_token_address" as the token address to be used in the auction.
/// @dev Setup function sets external contracts addresses.
/// @param _token_address Token address. | function setup(address _token_address) public isOwner atStage(Stages.AuctionDeployed) {
require(_token_address != 0x0);
token = GoToken(_token_address);
// Get number of GoToken indivisible tokens (GOT * token_multiplier)
// to be auctioned from token auction balance
num_t... | 0.4.21 |
/// @notice Set "_price_start", "_price_constant1" and "_price_exponent1"
/// "_price_constant2" and "_price_exponent2" as
/// the new starting price, price constant and price exponent for the auction price.
/// @dev Changes auction price function parameters before auction is started.
/// @param _price_start Updated s... | function changePriceCurveSettings(
uint256 _price_start,
uint256 _price_constant1,
uint256 _price_exponent1,
uint256 _price_constant2,
uint256 _price_exponent2)
internal
{
// You can change the price curve settings only when either the auction is Deplo... | 0.4.21 |
// @notice Finalize the auction - sets the final GoToken price and
// changes the auction stage after no bids are allowed. Only owner can finalize the auction.
// The owner can end the auction anytime after either the auction is deployed or started.
// @dev Finalize auction and set the final GOT token price. | function finalizeAuction() public isOwner
{
// The owner can end the auction anytime during the stages
// AuctionSetUp and AuctionStarted
require(stage == Stages.AuctionSetUp || stage == Stages.AuctionStarted);
// Calculate the final price = WEI / (GOT / token_multiplier)
... | 0.4.21 |
/// @notice Get the remaining funds needed to end the auction, calculated at
/// the current GOT price in WEI.
/// @dev The remaining funds necessary to end the auction at the current GOT price in WEI.
/// @return Returns the remaining funds to end the auction in WEI. | function remainingFundsToEndAuction() constant public returns (uint256) {
// num_tokens_auctioned = total number of indivisible GOT (GOT * token_multiplier) that is auctioned
uint256 required_wei_at_price = num_tokens_auctioned * price() / token_multiplier;
if (required_wei_at_price <= rece... | 0.4.21 |
// @dev Calculates the token price (WEI / GOT) at the current timestamp
// during the auction; elapsed time = 0 before auction starts.
// This is a composite exponentially decaying curve (two curves combined).
// The curve 1 is for the first 8 days and the curve 2 is for the remaining days.
// They are of the form:
// ... | function calcTokenPrice() constant private returns (uint256) {
uint256 elapsed;
uint256 decay_rate1;
uint256 decay_rate2;
if (stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp){
return price_start;
}
if (stage == Stages.AuctionStarted) {
... | 0.4.21 |
// **********
// TOKEN SALE
// ********** | function purchase(uint256 tokenId) external payable {
if (sale[tokenId].buyer != address(0)) { // if buyer is preset, require caller match
require(msg.sender == sale[tokenId].buyer, "!buyer");
}
uint256 price = sale[tokenId].price;
require(price > 0, "!forSale"); // toke... | 0.8.1 |
/// @dev Execute an arbitrary call. Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @return resultData The data returned by the call. | function executeCall(
address payable target,
bytes calldata callData
)
override
external
onlySpender
returns (bytes memory resultData)
{
bool success;
(success, resultData) = target.call(callData);
if (!success) {
/... | 0.6.12 |
/**
@notice depositReward is a one-time function which deposits a set amount of VIRTUE token that
can be claimed by airdrop recipients. The rewards are distributed over the duration of
_rewardsDuration. The function requires the owner to first approve the VirtuousHourAirdrop
contract to transfer the amount of VIRTU... | function depositReward(uint _virtueAmount, uint _rewardsDuration) external onlyOwner {
require(!rewardDeposited, "Reward has already been deposited");
rewardDeposited = true;
totalVirtueReward = _virtueAmount;
rewardsStartTime = block.timestamp;
rewardsDuration = _rewardsDuration;
require(virtue... | 0.8.9 |
/**
@notice claimRewards will claim the VIRTUE rewards that an address is eligible to claim from the
airdrop contract, based on how many NFTs they minted during the eligible window. The function
must be called with the EXACT number of shares that the address is eligible to claim, i.e.
if someone purchased 5 eligibl... | function claimRewards(address _to, uint _numShares, bytes32[] calldata _merkleProof) external {
require(rewardDeposited, "Reward has not yet been deposited into contract");
// Verify against the Merkle tree that the transaction is authenticated for the user.
bytes32 leaf = keccak256(abi.encodePacked(_to, _... | 0.8.9 |
// ------------------------------------------------------------------------
// Allow user to subscribe/extend access expiry through contract
// ------------------------------------------------------------------------ | function subscribeViaToken(uint256 _value) public returns (bool) {
uint256 sentValue = _value.mul(1 ether);
require(sentValue <= balances[msg.sender], "Insufficient balance");
balances[msg.sender] = balances[msg.sender].sub(sentValue);
balances[tokenReceivingAddress] = balances[to... | 0.5.17 |
// ------------------------------------------------------------------------
// Bulk buy tokens via ETH
// ------------------------------------------------------------------------ | function buyTokens () public payable returns (bool) {
require(pauseBuy == false,'Token buy currently unavailable.');
require(msg.sender != address(0), "Invalid address");
require(msg.value > 0, "Invalid amount");
uint256 tokensToBuy;
if (msg.value < 1 ether) {
t... | 0.5.17 |
// ------------------------------------------------------------------------
// Register a new user
// ------------------------------------------------------------------------ | function checkAndRegisterUser (address _account, uint256 _amount) private {
require(_amount > 0, 'Amount can not be zero');
if (!users[_account].isExist) {
//Create temp instance of User struct
Users_Details memory user;
user.register_on = now;
user.... | 0.5.17 |
// ------------------------------------------------------------------------
// Check user access expiry
// ------------------------------------------------------------------------ | function getUserAccessExpiry (address _account) public view returns(uint256) {
//require(users[_account].isExist,'User does not exists');
if (users[_account].isExist) {
// Create temp instance of User struct
Users_Details memory user;
user = users[_account];
... | 0.5.17 |
// ------------------------------------------------------------------------
// Extend user access expiry
// ------------------------------------------------------------------------ | function extendUserAccess (address _account, uint256 _amount) private {
require(users[_account].isExist,'User does not exists');
// Create temp instance of User struct
Users_Details memory user;
uint256 currentExpiry = users[_account].access_expiry;
uint256 extendedExpiry;
... | 0.5.17 |
// ------------------------------------------------------------------------
// Change ETH to VLT Rates
// ------------------------------------------------------------------------ | function changePackRates (uint256 _bronzePack, uint256 _silverPack, uint256 _goldPack, uint256 _platinumPack, uint256 _diamondPack) public onlyOwner returns (bool) {
require(_bronzePack > 0, 'Invalid bronze pack rate');
require(_silverPack > 0, 'Invalid silver pack rate');
require(_goldPack >... | 0.5.17 |
/**
* It adds a new token address to lastAmountsAddresses list
*
* @param _newToken : new interest bearing token address
*/ | function setNewToken(address _newToken)
external onlyOwner {
require(_newToken != address(0), "New token should be != 0");
for (uint256 i = 0; i < lastAmountsAddresses.length; i++) {
if (lastAmountsAddresses[i] == _newToken) {
return;
}
}
lastAmountsAddres... | 0.5.16 |
/**
* Used by Rebalance manager to set the new allocations
*
* @param _allocations : array with allocations in percentages (100% => 100000)
* @param _addresses : array with addresses of tokens used, should be equal to lastAmountsAddresses
*/ | function setAllocations(uint256[] calldata _allocations, address[] calldata _addresses)
external onlyRebalancerAndIdle
{
require(_allocations.length == lastAmounts.length, "Alloc lengths are different, allocations");
require(_allocations.length == _addresses.length, "Alloc lengths are different, addre... | 0.5.16 |
/* TODO: this is only for first pilots to avoid funds stuck in contract due to bugs.
remove this function for higher volume pilots */ | function withdraw(AugmintToken tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative)
external restrict("StabilityBoard") {
tokenAddress.transferWithNarrative(to, tokenAmount, narrative);
if (weiAmount > 0) {
to.transfer(weiAmount);
}
emit W... | 0.4.24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.