comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
@notice wrap sSQUID
@param _amount uint
@return uint
*/ | function wrapFromsSQUID( uint _amount ) external returns ( uint ) {
IERC20( sSQUID ).transferFrom( msg.sender, address(this), _amount );
uint value = wSQUIDValue( _amount );
_mint( msg.sender, value );
return value;
} | 0.7.5 |
/*
* Message Jakub "I heard you like chicken" on Discord
*/ | function stepThroughThePortal(uint256[] memory claimIds) external nonReentrant() {
require(_claimPeriodIsOpen, "Claim period is not open");
for (uint256 i = 0; i < claimIds.length; i++) {
uint256 tokenId = claimIds[i];
require(ITopDogBeachClub(_tdbcAddress).ownerOf(... | 0.8.0 |
/*
* Called once by the dev team to mint unclaimed cats after the claim period ends. Used for giveaways, marketing, etc.
*/ | function reserve(uint256[] memory tokenIds) external onlyOwner {
require(block.timestamp > 1633903200, "Not yet");
require(!_claimPeriodIsOpen, "Claim is still open..?");
require(_canReserve, "Already called");
require(tokenIds.length <= DEV_CATS, "Too many cats");
for (ui... | 0.8.0 |
/**
* @notice Returns a list of all tokenIds assigned to an address - used by the TDBC website
* Taken from https://ethereum.stackexchange.com/questions/54959/list-erc721-tokens-owned-by-a-user-on-a-web-page
* @param user get tokens of a given user
*/ | function tokensOfOwner(address user) external view returns (uint256[] memory ownerTokens) {
uint256 tokenCount = balanceOf(user);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory output = new uint256[](tokenCount);
for (uint2... | 0.8.0 |
//advertising address | function() external payable {
ads.transfer(msg.value/20); //Send 5% for advertising
//if investor already returned his deposit then his rate become 4%
if(balance[msg.sender]>=overallPayment[msg.sender])
rate[msg.sender]=80;
else
rate[msg.sender]=40... | 0.4.25 |
// GLADIATOR BATTLES | function createGladiatorBattle(
uint256 _dragonId,
uint8[2] _tactics,
bool _isGold,
uint256 _bet,
uint16 _counter
) external payable onlyHuman whenNotPaused {
address(gladiatorBattle).transfer(msg.value);
uint256 _id = gladiatorBattle.create(msg.sender... | 0.4.25 |
/*
@dev Function to set the basis point rate .
@param newBasisPoints uint which is <= 9.
*/ | function setParams(uint newBasisPoints,uint newMaxFee,uint newMinFee) public onlyOwner {
// Ensure transparency by hardcoding limit beyond which fees can never be added
require(newBasisPoints <= 9);
require(newMaxFee <= 100);
require(newMinFee <= 5);
basisPointsRate = newBas... | 0.4.25 |
/**
* @dev Calculate investment details
*/ | function calculateInvestment(address investor, uint value) public view
returns (uint investment, uint tokensToSend, uint refundValue) {
uint remainingInvestment = availableInvestment(investor);
if (value <= remainingInvestment) {
refundValue = 0;
} else {
refundValue = value.sub(remaining... | 0.6.12 |
/**
* @dev Invest into presale
*
* `investor` is sending ether and receiving tokens on `wallet` address and partial or full refund back on `invesor` address.
*/ | function invest(address wallet) public payable whenRunning nonReentrant {
address investor = _msgSender();
require(isInvestor(investor), "Investor is not whitelisted");
require(address(wallet) != address(0), "No wallet to transfer tokens to");
require(msg.value > 0, "There's no value in transaction");
... | 0.6.12 |
/**
* @dev Update presale details
*/ | function updateDetails(
uint _startBlock,
uint _endBlock,
uint _endRefundBlock,
uint _supply,
uint _rate,
uint _maxInvestment
) public onlyOwner {
require(_endBlock > block.number, "End block must be greater than the current one");
require(_endBlock > _startBlock, "Start block should b... | 0.6.12 |
// the current Form owner may always wield the metadata | function setMetaDesc(uint256 tokenId, string memory metadataDescription) public {
require(_msgSender() == super.ownerOf(tokenId), "It is another's impression to make");
require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked("Metadata description may only contain ", toStri... | 0.8.4 |
// a subsequently immutable Form | function mintForm(string[17] memory line, string memory metadataDescription) public nonReentrant onlyOwner {
require(bytes(line[0]).length <= maxLineLen && bytes(line[1]).length <= maxLineLen && bytes(line[2]).length <= maxLineLen && bytes(line[3]).length <= maxLineLen &&
bytes(line[4]).length <= max... | 0.8.4 |
/** one may paint a blank Canvas
* with immutable ink
* for history and the evolution of the collective consciousness */ | function paintCanvas(uint256 tokenId, string[17] memory line, string memory metadataDescription) public nonReentrant {
require(bytes(line[0]).length <= maxLineLen && bytes(line[1]).length <= maxLineLen && bytes(line[2]).length <= maxLineLen && bytes(line[3]).length <= maxLineLen &&
bytes(line[4]).len... | 0.8.4 |
// Function for buying shares | function buyShares(uint256 numberOfSharesToBuy) public whenNotPaused() returns (bool) {
// Check that buying is enabled
require(buyEnabled, "Buying is currenty disabled");
require(numberOfSharesToBuy >= minVolume, "Volume too low");
// Fetch the total price
address buyer... | 0.5.0 |
// Price getters | function getCumulatedPrice(uint256 amount, uint256 supply) public view returns (uint256){
uint256 cumulatedPrice = 0;
if (supply <= initialNumberOfShares) {
uint256 first = initialNumberOfShares.add(1).sub(supply);
uint256 last = first.add(amount).sub(1);
cumulat... | 0.5.0 |
// Crowdsale {constructor}
// @notice fired when contract is crated. Initilizes all constnat and initial values. | function Crowdsale(WhiteList _whiteListAddress) public {
multisig = 0x49447Ea549CCfFDEF2E9a9290709d6114346df88;
team = 0x49447Ea549CCfFDEF2E9a9290709d6114346df88;
startBlock = 0; // Should wait for the call of the function start
endBlock = 0;... | 0.4.17 |
// @notice set the step of the campaign
// @param _step {Step} | function setStep(Step _step) public onlyOwner() {
currentStep = _step;
if (currentStep == Step.FundingPreSale) { // for presale
minInvestETH = 1 ether/5;
}else if (currentStep == Step.FundingPublicSale) { // for public sale ... | 0.4.17 |
// @notice Due to changing average of block time
// this function will allow on adjusting duration of campaign closer to the end | function adjustDuration(uint _block) external onlyOwner() {
require(_block < 389376); // 4.16*60*24*65 days = 389376
require(_block > block.number.sub(startBlock)); // ensure that endBlock is not set in the past
endBlock = startBlock.add(_block);
} | 0.4.17 |
// @notice determine if purchase is valid and return proper number of tokens
// @return tokensToSend {uint} proper number of tokens based on the timline | function determinePurchase() internal view returns (uint) {
require(msg.value >= minInvestETH); // ensure that min contributions amount is met
uint tokenAmount = msg.value.mul(1e18) / tokenPriceWei; // calculate amount of tokens
uint tokensToSend;
... | 0.4.17 |
// @notice This function will return number of tokens based on time intervals in the campaign
// @param _tokenAmount {uint} amount of tokens to allocate for the contribution | function calculateNoOfTokensToSend(uint _tokenAmount) internal view returns (uint) {
if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 14) / 100) // less equal then/equal 14 days
return _tokenAmount + (_tokenAmount * 40) / 100; // 40% bonus
else i... | 0.4.17 |
// @notice called to send tokens to contributors after ICO and lockup period.
// @param _backer {address} address of beneficiary
// @return true if successful | function claimTokensForUser(address _backer) internal returns(bool) {
require(currentStep == Step.Claiming);
Backer storage backer = backers[_backer];
require(!backer.refunded); // if refunded, don't allow for another refund
require(!bac... | 0.4.17 |
// @notice it will allow contributors to get refund in case campaign failed | function refund() external stopInEmergency returns (bool) {
require(currentStep == Step.Refunding);
require(this.balance > 0); // contract will hold 0 ether at the end of campaign.
// contract needs to be funde... | 0.4.17 |
/// Create a new Lotto | function LottoCount() public
{
worldOwner = msg.sender;
ticketPrice = 0.0101 * 10**18;
maxTickets = 10;
_direction = 0;
lottoIndex = 1;
lastTicketTime = 0;
numtickets = 0;
totalBounty = 0;
} | 0.4.19 |
// Deposits ore to be burned | function burnOre(uint256 _amount) external nonReentrant {
require(_openForBurning, "Not Open For Burning");
require(_amount > 0, "Invalid Ore Amount");
require(ore.balanceOf(msg.sender) >= _amount, "Insufficient Ore");
ore.burn(msg.sender, _amount);
_burntOreByAddress[msg.sender][_currentLaunch] +... | 0.8.9 |
// Calculates and returns the total amount of claimable funds for the specified account and period | function totalClaimableByAccount(
address _account,
uint256 _fromLaunch,
uint256 _toLaunch
) public view returns (
uint256,
uint256[] memory
) {
require(_fromLaunch > 0 && _toLaunch <= _currentLaunch && _fromLaunch <= _toLaunch, "Invalid Launch Period");
// Calculate the total claimable... | 0.8.9 |
// Can be called by collectors for claiming funds from the ore burning mechanism | function claim(uint256 _fromLaunch, uint256 _toLaunch) external nonReentrant {
uint256 totalClaimable;
uint256[] memory maxPerLaunch;
(totalClaimable, maxPerLaunch) = totalClaimableByAccount(msg.sender, _fromLaunch, _toLaunch);
// Check the claimable amount and update the total claimed so far for the a... | 0.8.9 |
// Handles funds received for the pool | receive() external payable {
// Make sure enough funds are sent, and the source is whitelisted
require(msg.value > 0, "Insufficient Funds");
require(fundAddresses[msg.sender], "Invalid Fund Address");
// Update the total received funds for the currently open launch
_totalFundsByLaunch[_currentLaunc... | 0.8.9 |
/* function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _af... | function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) ... | 0.4.24 |
// An internal convenience function that checks to see if we are currently
// in the Window defined by the WindowParameters struct passed as an
// argument. | function _isInWindow(WindowParameters memory localParams) internal view returns (bool) {
// We are never "in a window" if the contract is paused
if (block.number < localParams.pauseEndedBlock) {
return false;
}
// If we are before the first window of this type, we are ... | 0.5.12 |
/// @notice A getter function for determining whether we are currently in a
/// fightWindow for a given tournament
/// @param _basicTournamentAddress The address of the tournament in
/// question
/// @return Whether or not we are in a fightWindow for this tournament | function _isInFightWindowForTournament(address _basicTournamentAddress) internal view returns (bool){
uint256 tournamentStartBlock;
uint256 pauseEndedBlock;
uint256 admissionDuration;
uint256 duelTimeoutDuration;
uint256 ascensionWindowDuration;
uint256 fightWindowD... | 0.5.12 |
/// @notice A seller/maker calls this function to update the pricePerPower
/// of an order that they already have stored in this contract. This saves
/// some gas for the seller by allowing them to just update the
/// pricePerPower parameter of their order.
/// @param _wizardId The tokenId for the seller's wizard. ... | function updateSellOrder(uint256 _wizardId, uint256 _newPricePerPower, address _basicTournamentAddress) external whenNotPaused nonReentrant {
require(WizardGuild(wizardGuildAddress).ownerOf(_wizardId) == msg.sender, 'only the owner of the wizard can update a sell order');
require(WizardGuild(wizardGui... | 0.5.12 |
/// @notice A seller/maker calls this function to cancel an existing order
/// that they have posted to this contract.
/// @dev Unlike the other Order functions, this function can be called even
/// if the contract is paused, so that users can clear out their orderbook
/// if they would like.
/// @param _wizardId T... | function cancelSellOrder(uint256 _wizardId, address _basicTournamentAddress) external nonReentrant {
require(WizardGuild(wizardGuildAddress).ownerOf(_wizardId) == msg.sender, 'only the owner of the wizard can cancel a sell order');
// Wait until after emitting event to delete order so that event dat... | 0.5.12 |
/// @notice A convenience function providing the caller with the current
/// amount needed (in wei) to fulfill this order.
/// @param _wizardId The id of the wizard NFT whose order we would like to
/// see the details of.
/// @param _basicTournamentAddress The address of the tournament that this
/// order pertains t... | function getCurrentPriceForOrder(uint256 _wizardId, address _basicTournamentAddress) external view returns (uint256){
Order memory order = orderForWizardIdAndTournamentAddress[_basicTournamentAddress][_wizardId];
uint256 power;
( , power, , , , , , , ) = BasicTournament(_basicTournamentAddres... | 0.5.12 |
/// @notice A convenience function checking whether the order is currently
/// valid. Note that an order can become invalid for a period of time, but
/// then become valid again (for example, during the time that a wizard
/// is dueling).
/// @param _wizardId The id of the wizard NFT whose order we would like to
///... | function getIsOrderCurrentlyValid(uint256 _wizardId, address _basicTournamentAddress) external view returns (bool){
Order memory order = orderForWizardIdAndTournamentAddress[_basicTournamentAddress][_wizardId];
if(order.makerAddress == address(0)){
// Order is not valid if order does not ... | 0.5.12 |
/// @notice Manual payout for site users
/// @param _user Ethereum address of the user
/// @param _amount The mount of CMA tokens in wei to send | function singlePayout(address _user, uint256 _amount)
public
onlyAdmin
returns (bool paid)
{
require(!tokenTransfersFrozen);
require(_amount > 0);
require(transferCheck(owner, _user, _amount));
if (!userRegistered[_user]) {
registerUser(_u... | 0.4.18 |
/// @dev low-level minting function not accessible externally | function tokenMint(address _invoker, uint256 _amount)
private
returns (bool raised)
{
require(balances[owner].add(_amount) > balances[owner]);
require(balances[owner].add(_amount) > 0);
require(totalSupply.add(_amount) > 0);
require(totalSupply.add(_amount) > ... | 0.4.18 |
/// @notice Used to burn tokens
/// @param _amount The amount of CMA tokens in wei to burn | function tokenBurn(uint256 _amount)
public
onlyAdmin
returns (bool burned)
{
require(_amount > 0);
require(_amount < totalSupply);
require(balances[owner] > _amount);
require(balances[owner].sub(_amount) >= 0);
require(totalSupply.sub(_amount)... | 0.4.18 |
/// @notice Used to transfer funds on behalf of one person
/// @param _owner Person you are allowed to spend funds on behalf of
/// @param _receiver Person to receive the funds
/// @param _amount Amoun of CMA tokens in wei to send | function transferFrom(address _owner, address _receiver, uint256 _amount)
public
returns (bool _transferredFrom)
{
require(!tokenTransfersFrozen);
require(allowance[_owner][msg.sender].sub(_amount) >= 0);
require(transferCheck(_owner, _receiver, _amount));
bala... | 0.4.18 |
/**
* @inheritdoc iOVM_StateCommitmentChain
*/ | function appendStateBatch(
bytes32[] memory _batch,
uint256 _shouldStartAtElement
)
override
public
{
// Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the
// publication of batches by some other user.
require(
... | 0.7.6 |
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Timestamp of the last batch submitted by the sequencer.
*/ | function _getBatchExtraData()
internal
view
returns (
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
// solhint-disable max-line-length
uint40 totalElements;
uint40 lastSequencerTimestamp;
assembl... | 0.7.6 |
/**
* Removes a batch and all subsequent batches from the chain.
* @param _batchHeader Header of the batch to remove.
*/ | function _deleteBatch(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
{
require(
_batchHeader.batchIndex < batches().length(),
"Invalid batch index."
);
require(
_isValidBatchHeader(_batchHeader),
"Invalid bat... | 0.7.6 |
/**
* Transfer functions
*/ | function transfer(address _to, uint256 _value) public {
require(_to != address(this));
require(_to != address(0), "Cannot use zero address");
require(_value > 0, "Cannot use zero value");
require (balanceOf[msg.sender] >= _value, "Balance not enough"); // Check if the sende... | 0.7.1 |
/**
* Requirements:
* `rewardAmount` rewards to be added to the staking contract
* @dev to add rewards to the staking contract
* once the allowance is given to this contract for 'rewardAmount' by the user
*/ | function addReward(uint256 rewardAmount, address tokenAddress)
external
_validTokenAddress(tokenAddress)
_hasAllowance(msg.sender, rewardAmount, tokenAddress)
returns (bool)
{
require(rewardAmount > 0, "Reward must be positive");
address from = msg.sender;
... | 0.5.16 |
/**
* Requirements:
* `amount` Amount to be staked
* `tokenAddress` Token address to stake
/**
* @dev to stake 'amount' value of tokens
* once the user has given allowance to the staking contract
*/ | function stake(uint256 amount, address tokenAddress)
public
_validTokenAddress(tokenAddress)
_hasAllowance(msg.sender, amount, tokenAddress)
returns (bool)
{
require(amount > 0, "Can't stake 0 amount");
require(
amount <= userCap[tokenAddress],
... | 0.5.16 |
/**
* @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply
* and the maximum number of the tokens that a single account can mint are limited.
* @dev only owner can call this mint function
* @param recipient address of account to receive the tokens
* @param ... | function mint(
address recipient,
uint256 amount,
bytes32[] calldata merkleProof
) external onlyOwner {
require(amount != 0, "amount == 0");
// If the pool is in the guarded launch phase, the following checks are done to restrict deposits.
// 1. Check if the given ... | 0.6.12 |
/**
* @dev mints to multiple addresses arbitrary units of tokens of ONE token id per address
* @notice example: mint 3 units of tokenId 1 to alice and 4 units of tokenId 2 to bob
* @param accounts list of beneficiary addresses
* @param tokenIds list of token ids (aka tiers)
*... | function mintToMultiple(
address[] calldata accounts,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) public onlyOwner isSameLength(accounts, tokenIds, amounts) {
bytes memory data;
for (uint256 i = 0; i < accounts.length; i++) {
require(
... | 0.8.4 |
/**
* @dev burns from multiple addresses arbitrary units of tokens of ONE token id per address
* example: burn 3 units of tokenId 1 from alice and 4 units of tokenId 2 froms bob
* @param accounts list of token holder addresses
* @param tokenIds list of token ids (aka t... | function burnFromMultiple(
address[] calldata accounts,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) public onlyOwner isSameLength(accounts, tokenIds, amounts) {
for (uint256 i = 0; i < accounts.length; i++) {
require(
tokenTiers[tokenIds[i]].... | 0.8.4 |
/**
* @dev transfers tokens from one address to another allowing custom data parameter
* @notice this is the standard transfer interface for ERC1155 tokens which contracts expect
* @param from address from which token will be transferred
* @param to recipient of addr... | function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public override {
require(
owner() == _msgSender() ||
from == _msgSender() ||
isApprovedForAll(from, _msgSender()),
... | 0.8.4 |
/**
* @dev creates a new token tier
* @param tokenId identifier for the new token tier
* @param uriId identifier that is appended to the baseUri together forming the uri where the metadata lives
* @param transferable determines if tokens from specific tier should be transferable or no... | function createTokenTier(
uint256 tokenId,
string memory uriId,
bool transferable,
address boxToken
) public onlyOwner isValidString(uriId) {
require(
_isEmptyString(tokenTiers[tokenId].uriId),
"Tier already exists for tokenId"
);
toke... | 0.8.4 |
/**
* @dev update uri identifiers for multiple token ids (tiers)
* @param tokenIds tokenIds for which the uri should be updated (must be in same order as uriIds)
* @param uriIds identifiers that are appended to the baseUri together forming the uri where the metadata lives (must be in same... | function updateMultipleUriIdentifiers(
uint256[] calldata tokenIds,
string[] calldata uriIds
) public onlyOwner {
require(tokenIds.length == uriIds.length, "Input array mismatch");
for (uint8 i = 0; i < tokenIds.length; i++) {
_updateUriIdentifier(tokenIds[i], uriIds[i])... | 0.8.4 |
/**
* @notice Initializes this Swap contract with the given parameters.
* This will also clone a LPToken contract that represents users'
* LP positions. The owner of LPToken will be this contract - which means
* only this contract is allowed to mint/burn tokens.
*
* @param _pooledTokens an array of ERC20s this po... | function initialize(
IERC20[] memory _pooledTokens,
uint8[] memory decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 _a,
uint256 _fee,
uint256 _adminFee,
uint256 _withdrawFee,
address lpTokenTargetAddress
) public virtua... | 0.6.12 |
/**
* @notice Borrow the specified token from this pool for this transaction only. This function will call
* `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token
* and the associated fee by the end of the callback transaction. If the conditions are not met, this... | function flashLoan(
address receiver,
IERC20 token,
uint256 amount,
bytes memory params
) external nonReentrant {
uint8 tokenIndex = getTokenIndex(address(token));
uint256 availableLiquidityBefore = token.balanceOf(address(this));
uint256 protocolBalanceBefore... | 0.6.12 |
/**
* @notice Updates the flash loan fee parameters. This function can only be called by the owner.
* @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans
* @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee
*/ | function setFlashLoanFees(
uint256 newFlashLoanFeeBPS,
uint256 newProtocolFeeShareBPS
) external onlyOwner {
require(
newFlashLoanFeeBPS > 0 &&
newFlashLoanFeeBPS <= MAX_BPS &&
newProtocolFeeShareBPS <= MAX_BPS,
"fees are not in valid r... | 0.6.12 |
/**
* @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node
* stored in this contract. Pools should use this function to check if the given address qualifies for depositing.
* If the given account has already been verified with the correct merkleProof, this ... | function verifyAddress(address account, bytes32[] calldata merkleProof)
external
override
returns (bool)
{
if (merkleProof.length != 0) {
// Verify the account exists in the merkle tree via the MerkleProof library
bytes32 node = keccak256(abi.encodePacked(acco... | 0.6.12 |
/**
* @notice Return A in its raw precision
* @dev See the StableSwap paper for details
* @param self Swap struct to read from
* @return A parameter in its raw precision form
*/ | function _getAPrecise(SwapUtilsV1.Swap storage self)
internal
view
returns (uint256)
{
uint256 t1 = self.futureATime; // time when ramp is finished
uint256 a1 = self.futureA; // final A value when ramp is finished
if (block.timestamp < t1) {
uint256 t0 = ... | 0.6.12 |
/**
* @notice Start ramping up or down A parameter towards given futureA_ and futureTime_
* Checks if the change is too rapid, and commits the new A value only when it falls under
* the limit range.
* @param self Swap struct to update
* @param futureA_ the new A to ramp towards
* @param futureTime_ timestamp when... | function rampA(
SwapUtilsV1.Swap storage self,
uint256 futureA_,
uint256 futureTime_
) external {
require(
block.timestamp >= self.initialATime.add(1 days),
"Wait 1 day before starting ramp"
);
require(
futureTime_ >= block.timestam... | 0.6.12 |
/**
* @notice Stops ramping A immediately. Once this function is called, rampA()
* cannot be called for another 24 hours
* @param self Swap struct to update
*/ | function stopRampA(SwapUtilsV1.Swap storage self) external {
require(self.futureATime > block.timestamp, "Ramp is already stopped");
uint256 currentA = _getAPrecise(self);
self.initialA = currentA;
self.futureA = currentA;
self.initialATime = block.timestamp;
self.future... | 0.6.12 |
/**
* @dev Transfer tokens to multiple addresses
* @param _addresses The addresses that will receieve tokens
* @param _amounts The quantity of tokens that will be transferred
* @return True if the tokens are transferred correctly
*/ | function transferForMultiAddresses(address[] _addresses, uint256[] _amounts) canTransfer public returns (bool) {
for (uint256 i = 0; i < _addresses.length; i++) {
require(_addresses[i] != address(0));
require(_amounts[i] <= balances[msg.sender]);
require(_amounts[i] > 0);
// SafeMath.... | 0.4.18 |
/**
* @notice Migrates saddle LP tokens from a pool to another
* @param oldPoolAddress pool address to migrate from
* @param amount amount of LP tokens to migrate
* @param minAmount of new LP tokens to receive
*/ | function migrate(
address oldPoolAddress,
uint256 amount,
uint256 minAmount
) external returns (uint256) {
// Check
MigrationData memory mData = migrationMap[oldPoolAddress];
require(
address(mData.oldPoolLPTokenAddress) != address(0),
"migrati... | 0.6.12 |
// in case DegenSwap launches new router V2 | function changeRouter(address _newRouter, uint256 _fees) public onlyOwner() {
degenSwapRouter = IDEGENSwapRouter(_newRouter);
WETH = degenSwapRouter.WETH();
// Create a uniswap pair for this new token
degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory())
.createPair(... | 0.8.9 |
//Owner of all the tokens
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token | function CryptFillToken(
) {
balances[msg.sender] = 30000000 * 1000000000000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 30000000 * 1000000000000000000; // Update total supply (100000 for example)
name = "Crypt... | 0.4.24 |
/// @notice Will allow multiple minting within a single call to save gas.
/// @param _to_list A list of addresses to mint for.
/// @param _values The list of values for each respective `_to` address. | function airdropMinting(address[] _to_list, uint[] _values) public {
require(msg.sender == owner); // assuming you have a contract owner
require(_to_list.length == _values.length);
for (uint i = 0; i < _to_list.length; i++) {
mintToken(_to_list[i], _values[i]);
}
} | 0.4.24 |
/**
* @dev Withdraw asset.
* @param _assetAddress Asset to be withdrawn.
*/ | function withdraw(address _assetAddress) public onlyOwner {
uint assetBalance;
if (_assetAddress == ETHER) {
address self = address(this); // workaround for a possible solidity bug
assetBalance = self.balance;
msg.sender.transfer(assetBalance);
} else {
... | 0.6.12 |
// Buy Index and return to user (no flash loans) - Same as flashSellIndex but send user the token | function obtainIndexTokens(address _index, uint256 amountIndexToBuy, address pairAddress) public payable {
(uint256 totalEthNeeded, uint256[] memory tokenAmounts, address[] memory tokens) = calculatePositionsNeededToBuyIndex(_index, amountIndexToBuy);
require(msg.value >= totalEthNeeded, "did not send enough ... | 0.6.12 |
// Loan WETH and trade for individual parts, then redeem and sell Index (will trigger executeOperation); | function flashSellIndex(address _index, uint256 amountIndexToSell, address pairAddress) internal {
// Second calculate amount of ETH needed to get individual tokens
(uint256 totalEthNeeded, uint256[] memory tokenAmounts, address[] memory tokens) = calculatePositionsNeededToBuyIndex(_index, amountIndexToSell);... | 0.6.12 |
// Loan Index and Sell for Individual Parts | function flashBuyIndex(address _index, uint256 amountIndexToBuy, address pairAddress) internal returns (address t0, address t1, uint256 a0, uint256 a1) {
bytes memory data = abi.encode(_index, amountIndexToBuy, pairAddress);
address token0 = IUniswapV2Pair(pairAddress).token0();
address token1 = ... | 0.6.12 |
// computes the direction and magnitude of the profit-maximizing trade
// https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSwapToPrice.sol | function computeProfitMaximizingTrade(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) private pure returns (bool aToB, uint256 amountIn) {
aToB = reserveA.mul(truePriceTokenB) / reserveB < truePriceTokenA;
uint256 invariant = reserveA.mul(reserv... | 0.6.12 |
/**
* distribute token for team, marketing, foundation, ...
*/ | function _genesisDistributeAndLock() internal {
address seedAddress = 0x43AedAdE0066A57247D8D8D45424E2AcaA9aEB70;
address privateSaleAddress = 0xb0438dcd547653E5B651d09e279A10F5a5C0dad6;
address presaleAddress = 0x2285dF9ffeb3Bd2d12147438C3b7D8a680Be8B49;
address publicsaleAddress = ... | 0.8.7 |
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy | function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (addr... | 0.6.12 |
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount | function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.... | 0.6.12 |
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order | function takeOrder(
ExchangeData memory _exData,
uint256 _ethAmount,
ActionType _type
) private returns (bool success, uint256, uint256) {
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.c... | 0.6.12 |
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount | function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");
uint ethValue = 0;
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exD... | 0.6.12 |
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _srcAmount amount we are selling | function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return address(this).balance;
// if msg value is larger than srcAmount, that means that msg value is... | 0.6.12 |
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The a... | function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
r... | 0.6.12 |
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio | function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed)... | 0.6.12 |
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio | function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
CompoundSubscriptions.CompoundHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
retur... | 0.6.12 |
/* For The Minter to give CWC to a client */ | function minterGivesCWC(address _to, uint _value) public {
require(isMinter[msg.sender]); //minters are the sales items: UET, DET, ...
require(!isMinter[_to] && _to != owner); //to a client
balances[_to] = balances[_to].add(_value);
MinterGaveCWC(msg.sender, _to, _value);
} | 0.4.19 |
/* ERC223 transfer CWCs with data */ | function transfer(address _to, uint _value, bytes _data) public {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
if(!isMinter[_to] && _to != owner) { //They will never get anyth... | 0.4.19 |
/* ERC223 transfer CWCs w/o data for ERC20 compatibility */ | function transfer(address _to, uint _value) public {
uint codeLength;
bytes memory empty;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
if(!isMinter[_to] && _to != owner) { //They will never g... | 0.4.19 |
//================================ CWC Return Transaction ==================================// | function CWCreturnTransaction(address from, uint amount) private {
require(verifiedUsersOnlyMode==false || verifiedUsers[from]==true);
require(!pauseCWC);
require(amount>minCWCsPerReturnMoreThan && amount<maxCWCsPerReturnLessThan);
if (oraclize_getPrice("URL") > this.balanc... | 0.4.19 |
// _migrateCashLP migrates MICv1 LP tokens into MICv2 LP and returns the amount of converted MICv1. | function _migrateCashLP()
internal
onlyOneBlock
returns (uint256)
{
require(block.timestamp <= endTime, 'CashLpMigrator: redemption period ended');
uint256 amount = IERC20(lp_old).balanceOf(msg.sender);
require(amount > 0, 'CashLpMigrator: cannot exchange zero ... | 0.6.12 |
//Converts V1 Cash/stable LP to V2 Cash/stable LP and stakes the V2 LP tokens on behalf of the user | function migrateLockedCashLP()
external
onlyOneBlock
{
//Only need to check price if I'm locking
uint256 cashPrice = getOraclePrice();
require(cashPrice <= 1000000, 'Cash v1 price must be <= $1');
uint256 convertedOldCashAmount = _migrateCashLP();
... | 0.6.12 |
/**
* @notice Send this earning to drip contract.
*/ | function _forwardEarning() internal override {
address _dripContract = IVesperPool(pool).poolRewards();
uint256 _earned = IERC20(dripToken).balanceOf(address(this));
// Fetches which rewardToken collects the drip
address _growPool = IEarnDrip(_dripContract).growToken();
// Checks... | 0.8.3 |
/**
* Mints monster
*/ | function mintmonster( string calldata message) public {
require(saleIsActive, "Sale must be active to mint monster");
require((totalSupply()+1) <= MAX_monster, "Purchase would exceed max supply of monster");
require(saletoken.allowance(msg.sender, address(this)) >= monsterPrice, "This contrac... | 0.7.0 |
// Calculates the Bonus Award based upon the purchase amount and the purchase period
// function calculateBonus(uint256 individuallyContributedEtherInWei) private returns(uint256 bonus_applied) | function startPreICO() public onlyOwner atStage(Stages.NOTSTARTED)
{
stage = Stages.PREICO;
paused = false;
Price_Per_Token = 10;
BONUS = 30;
balances[address(this)] = (TotalpresaleSupply).mul(TOKEN_DECIMALS);
StartdatePresale = now;
EnddatePresale = now + PresaleDays;
emit Transfer(0, address... | 0.4.24 |
/**
* @notice Calculate the dy, the amount of selected token that user receives and
* the fee of withdrawing in one token
* @param account the address that is withdrawing
* @param tokenAmount the amount to withdraw in the pool's precision
* @param tokenIndex which token will be withdrawn
* @param self Swap struct... | function calculateWithdrawOneToken(
Swap storage self,
address account,
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256) {
(uint256 availableTokenAmount, ) = _calculateWithdrawOneToken(
self,
account,
tokenAmount,
... | 0.6.12 |
/**
* @notice Calculate the price of a token in the pool with given
* precision-adjusted balances and a particular D.
*
* @dev This is accomplished via solving the invariant iteratively.
* See the StableSwap paper and Curve.fi implementation for further details.
*
* x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * ... | function getYD(
uint256 a,
uint8 tokenIndex,
uint256[] memory xp,
uint256 d
) internal pure returns (uint256) {
uint256 numTokens = xp.length;
require(tokenIndex < numTokens, "Token not found");
uint256 c = d;
uint256 s;
uint256 nA = a.mul(num... | 0.6.12 |
/**
* @notice Given a set of balances and precision multipliers, return the
* precision-adjusted balances.
*
* @param balances an array of token balances, in their native precisions.
* These should generally correspond with pooled tokens.
*
* @param precisionMultipliers an array of multipliers, corresponding to
... | function _xp(
uint256[] memory balances,
uint256[] memory precisionMultipliers
) internal pure returns (uint256[] memory) {
uint256 numTokens = balances.length;
require(
numTokens == precisionMultipliers.length,
"Balances must match multipliers"
);
... | 0.6.12 |
/**
* @notice Get the virtual price, to help calculate profit
* @param self Swap struct to read from
* @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS
*/ | function getVirtualPrice(Swap storage self)
external
view
returns (uint256)
{
uint256 d = getD(_xp(self), _getAPrecise(self));
LPToken lpToken = self.lpToken;
uint256 supply = lpToken.totalSupply();
if (supply > 0) {
return d.mul(10**uint256(POOL_P... | 0.6.12 |
/**
* @notice Internally calculates a swap between two tokens.
*
* @dev The caller is expected to transfer the actual amounts (dx and dy)
* using the token contracts.
*
* @param self Swap struct to read from
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number... | function _calculateSwap(
Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256[] memory balances
) internal view returns (uint256 dy, uint256 dyFee) {
uint256[] memory multipliers = self.tokenPrecisionMultipliers;
uint256[] memory xp... | 0.6.12 |
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param self Swap st... | function calculateTokenAmount(
Swap storage self,
address account,
uint256[] calldata amounts,
bool deposit
) external view returns (uint256) {
uint256 a = _getAPrecise(self);
uint256[] memory balances = self.balances;
uint256[] memory multipliers = self.token... | 0.6.12 |
/**
* @notice swap two tokens in the pool
* @param self Swap struct to read from and write to
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell
* @param minDy the min amount the user would like to ... | function swap(
Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy
) external returns (uint256) {
{
IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom];
require(
dx <= tokenFrom.balanceOf(msg.... | 0.6.12 |
/**
* @notice Update the withdraw fee for `user`. If the user is currently
* not providing liquidity in the pool, sets to default value. If not, recalculate
* the starting withdraw fee based on the last deposit's time & amount relative
* to the new deposit.
*
* @param self Swap struct to read from and write to
*... | function updateUserWithdrawFee(
Swap storage self,
address user,
uint256 toMint
) public {
// If token is transferred to address 0 (or burned), don't update the fee.
if (user == address(0)) {
return;
}
if (self.defaultWithdrawFee == 0) {
... | 0.6.12 |
/**
* @notice Burn LP tokens to remove liquidity from the pool.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param self Swap struct to read from and write to
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable f... | function removeLiquidity(
Swap storage self,
uint256 amount,
uint256[] calldata minAmounts
) external returns (uint256[] memory) {
LPToken lpToken = self.lpToken;
IERC20[] memory pooledTokens = self.pooledTokens;
require(amount <= lpToken.balanceOf(msg.sender), ">LP.b... | 0.6.12 |
/**
* @notice Remove liquidity from the pool all in one token.
* @param self Swap struct to read from and write to
* @param tokenAmount the amount of the lp tokens to burn
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @return a... | function removeLiquidityOneToken(
Swap storage self,
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount
) external returns (uint256) {
LPToken lpToken = self.lpToken;
IERC20[] memory pooledTokens = self.pooledTokens;
require(tokenAmount <= lpToken.balan... | 0.6.12 |
/**
* @notice withdraw all admin fees to a given address
* @param self Swap struct to withdraw fees from
* @param to Address to send the fees to
*/ | function withdrawAdminFees(Swap storage self, address to) external {
IERC20[] memory pooledTokens = self.pooledTokens;
for (uint256 i = 0; i < pooledTokens.length; i++) {
IERC20 token = pooledTokens[i];
uint256 balance = token.balanceOf(address(this)).sub(
self.ba... | 0.6.12 |
/**
* @dev Change the name of the asteroid
*/ | function setName(uint _asteroidId, string memory _newName) external whenNotPaused {
require(_msgSender() == token.ownerOf(_asteroidId), "ERC721: caller is not the owner");
require(validateName(_newName) == true, "Invalid name");
require(isNameUsed(_newName) == false, "Name already in use");
// If alrea... | 0.7.6 |
/**
* @dev Check if the name string is valid
* Between 1 and 32 characters (Alphanumeric and spaces without leading or trailing space)
*/ | function validateName(string memory str) public pure returns (bool){
bytes memory b = bytes(str);
if(b.length < 1) return false;
if(b.length > 32) return false; // Cannot be longer than 25 characters
if(b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trail... | 0.7.6 |
//@dev Prior approval by the "addressHoldingNFTs" of this deployed contract
// to the Timeless contract is required for all IDs that should be allowed to be exchanged | function exchangeTimeless(uint256 tokenId) external payable {
require(tokenIdToAddress[tokenId] == msg.sender, "You are not allowed to buy one!");
require(claimed[tokenId] == false, "TokenID already claimed!");
require(msg.value == 0.222 ether, "Please send exactly 0.222 ETH");
IERC721(... | 0.8.10 |
/**
* @notice create and deploy multiple vest contracts.
* @notice can be called by onlyOwner.
* @param startTime vesting startTime in EPOCH.
* @param endTime vesting endTime in EPOCH.
* @param cliff duration when claim starts.
* @param unlockDuration every liner unlocking schedule in seconds.
* @param al... | function createVest(
uint256 startTime,
uint256 endTime,
uint256 cliff,
uint256 unlockDuration,
bool allowReleaseAll
) external onlyOwner returns (address vestAddress) {
vestAddress = address(
new UnifarmVesting(
_msgSender(),
... | 0.8.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.