comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* Create tokens.
*
* @param _value number of tokens to be created.
*/ | function createTokens (uint256 _value)
public virtual returns (bool) {
require (msg.sender == owner);
if (_value > 0) {
if (_value <= MAX_TOKENS_COUNT - tokensCount) {
accounts [msg.sender] = accounts [msg.sender] + _value;
tokensCount = tokensCount + _value;
Transfer ... | 0.8.0 |
/**
* Burn tokens.
*
* @param _value number of tokens to burn
*/ | function burnTokens (uint256 _value)
public virtual returns (bool) {
require (msg.sender == owner);
if (_value > 0) {
if (_value <= accounts [msg.sender]) {
accounts [msg.sender] = accounts [msg.sender] - _value;
tokensCount = tokensCount - _value;
Transfer (msg.sender... | 0.8.0 |
/**
* Transfer tokens from an different address to another address.
* Need to have been granted an allowance to do this before triggering.
*/ | function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances... | 0.4.11 |
/**
* Approve the indicated address to spend the specified amount of tokens on the sender's behalf
*/ | function approve(address _spender, uint _value) {
// Ensure allowance is zero if attempting to set to a non-zero number
// This helps manage an edge-case race condition better: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) th... | 0.4.11 |
/// @notice Allow registered voter to vote 'for' proposal
/// @param _id Proposal id | function voteFor(uint256 _id) public {
require(proposals[_id].start < block.number, "<start");
require(proposals[_id].end > block.number, ">end");
uint256 _against = proposals[_id].againstVotes[_msgSender()];
if (_against > 0) {
proposals[_id].totalAgainstVotes = propo... | 0.6.3 |
/* Use admin powers to send from a users account */ | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
require (_to != 0x0); // Prevent transfer to 0x0 address
require (balances[msg.sender] > _value); // Check if the sender has enough
require (balances[_to] ... | 0.4.20 |
/* Function to authenticate user
Restricted to whitelisted partners */ | function authenticate(uint _value, uint _challenge, uint _partnerId) public {
require(whitelist[_partnerId][msg.sender]); // Make sure the sender is whitelisted
require(balances[msg.sender] > _value); // Check if the sender has enough
require(hydroPartnerMap[_partnerId][ms... | 0.4.20 |
/* Function called by Hydro API to check if the partner has validated
* The partners value and data must match and it must be less than a day since the last authentication
*/ | function validateAuthentication(address _sender, uint _challenge, uint _partnerId) public constant returns (bool _isValid) {
if (partnerMap[_partnerId][_sender].value == hydroPartnerMap[_partnerId][_sender].value
&& block.timestamp < hydroPartnerMap[_partnerId][_sender].timestamp
&& partnerMa... | 0.4.20 |
/**
* @dev get all GreedyCoins of msg.sender
*/ | function getMyTokens() external view returns ( uint256[] arr_token_id, uint256[] arr_last_deal_time, uint256[] buying_price_arr, uint256[] price_arr ){
TokenGDC memory token;
uint256 count = stOwnerTokenCount[msg.sender];
arr_last_deal_time = new uint256[](count);
buying_price_arr = new uint256[... | 0.4.24 |
// buy (only accept normal address) | function buy(uint256 next_price, bool is_recommend, uint256 recommend_token_id) external payable mustCommonAddress {
require (next_price >= PRICE_MIN && next_price <= PRICE_LIMIT);
_checkRecommend(is_recommend,recommend_token_id);
if (stTokens.length < ISSUE_MAX ){
_buyAndCreateToken(next_pric... | 0.4.24 |
// get the cheapest GreedyCoin | function _getCurrentTradableToken() private view returns(uint256 token_id) {
uint256 token_count = stTokens.length;
uint256 min_price = stTokens[0].price;
token_id = 0;
for ( uint i = 0; i < token_count; i++ ){
// token = stTokens[i];
uint256 price = stTokens[i].price;
if (price... | 0.4.24 |
// create GreedyCoin | function _buyAndCreateToken(uint256 next_price, bool is_recommend, uint256 recommend_token_id ) private {
require( msg.value >= START_PRICE );
// create
uint256 now_time = now;
uint256 token_id = stTokens.length;
TokenGDC memory token;
token = TokenGDC({
token_hash: keccak256(ab... | 0.4.24 |
// buy GreedyCoin from each other,after all GreedyCoins has been created | function _buyFromMarket(uint256 next_price, bool is_recommend, uint256 recommend_token_id ) private {
uint256 current_tradable_token_id = _getCurrentTradableToken();
TokenGDC storage token = stTokens[current_tradable_token_id];
uint256 current_token_price = token.price;
bytes32 current_token_h... | 0.4.24 |
// 10% change of getting all blance of fees | function _gambling(uint256 current_fund, bytes32 current_token_hash, uint256 last_deal_time) private {
// random 0 - 99
uint256 random_number = _createRandomNumber(current_token_hash,last_deal_time);
if ( random_number < 10 ) {
// contract address
address contract_address = (address)(... | 0.4.24 |
//mint KandiKids | function mintKandiKids(uint256 _count) external payable {
if (msg.sender != owner()) {
require(saleOpen, "Sale is not open yet");
require(
_count > 0 && _count <= 10,
"Min 1 & Max 10 Kandi Kids can be minted per transaction"
);
... | 0.8.7 |
/*
* This is how you get one, or more...
*/ | function acquire(uint256 amount) public payable nonReentrant {
require(amount > 0, "minimum 1 token");
require(amount <= totalTokenToMint - tokenIndex, "greater than max supply");
require(isSaleActive, "sale is not active");
require(amount <= 20, "max 20 tokens at once");
require(getPricePerToken() * amount =... | 0.8.6 |
//in case tokens are not sold, admin can mint them for giveaways, airdrops etc | function adminMint(uint256 amount) public onlyOwner {
require(amount > 0, "minimum 1 token");
require(amount <= totalTokenToMint - tokenIndex, "amount is greater than the token available");
for (uint256 i = 0; i < amount; i++) {
_mintToken(_msgSender());
}
} | 0.8.6 |
/*
* Helper function
*/ | function tokensOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tok... | 0.8.6 |
/**
* @dev Unlock vested tokens and transfer them to their holder.
*/ | function unlockVestedTokens() external {
Grant storage grant_ = grants[msg.sender];
// Require that the grant is not empty.
require(grant_.value != 0);
// Get the total amount of vested tokens, according to grant.
uint256 vested = calculateVestedTokens(grant_, bl... | 0.4.24 |
/**
* @dev Grant tokens to a specified address. Please note, that the trustee must have enough ungranted tokens
* to accomodate the new grant. Otherwise, the call with fail.
* @param _to address The holder address.
* @param _value uint256 The amount of tokens to be granted.
* @param _start uint256 The beginni... | function granting(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end,
uint256 _installmentLength, bool _revocable)
external onlyOwner
{
require(_to != address(0));
// Don't allow holder to be this contract.
require(_to != address(this));
... | 0.4.24 |
/**
* @dev Calculate amount of vested tokens at a specifc time.
* @param _grant Grant The vesting grant.
* @param _time uint256 The time to be checked
* @return a uint256 Representing the amount of vested tokens of a specific grant.
*/ | function calculateVestedTokens(Grant _grant, uint256 _time) private pure returns (uint256) {
// If we're before the cliff, then nothing is vested.
if (_time < _grant.cliff) {
return 0;
}
// If we're after the end of the vesting period - everything is vested;
... | 0.4.24 |
// claim txs will revert if any tokenids are not claimable | function claim(
uint256[] memory tokenIds,
uint256[] memory amounts,
uint256 nonce,
uint256 timestamp,
bytes memory signature
) external payable override nonReentrant {
address sender = _msgSender();
address recovered = ECDSA.recover(
ECDSA.toEthSi... | 0.8.7 |
/**
* @dev Set an updateManager for an account
* @param _owner - address of the account to set the updateManager
* @param _operator - address of the account to be set as the updateManager
* @param _approved - bool whether the address will be approved or not
*/ | function setUpdateManager(address _owner, address _operator, bool _approved) external {
require(_operator != msg.sender, "The operator should be different from owner");
require(
_owner == msg.sender ||
_isApprovedForAll(_owner, msg.sender),
"Unauthorized user"
);
updateManager... | 0.4.24 |
/**
* @dev Register an account balance
* @notice Register land Balance
*/ | function registerBalance() external {
require(!registeredBalance[msg.sender], "Register Balance::The user is already registered");
// Get balance of the sender
uint256 currentBalance = landBalance.balanceOf(msg.sender);
if (currentBalance > 0) {
require(
landBalance.destroyTokens(m... | 0.4.24 |
/**
* @dev Unregister an account balance
* @notice Unregister land Balance
*/ | function unregisterBalance() external {
require(registeredBalance[msg.sender], "Unregister Balance::The user not registered");
// Set balance as unregistered
registeredBalance[msg.sender] = false;
// Get balance
uint256 currentBalance = landBalance.balanceOf(msg.sender);
// Destroy T... | 0.4.24 |
/**
* @dev Public mints a new token
* @param hash The hash of the token
* @param signature The signature of the token
*/ | function mint(bytes32 hash, bytes memory signature) external payable onlySender nonReentrant {
require(!publicMintPaused, "Mint is paused");
require(
hash ==
keccak256(
abi.encode(msg.sender, balanceOf(msg.sender), address(this))
),
... | 0.8.7 |
/**
* @dev get the minting amount for the given value
* @param value The value of the transaction
*/ | function _getMintAmount(uint256 value) internal view returns (uint256) {
uint256 remainder = value % mintPrice;
require(remainder == 0, "Send a divisible amount of eth");
uint256 amount = value / mintPrice;
require(amount > 0, "Amount to mint is 0");
require(
(totalS... | 0.8.7 |
// Forward ERC20 methods to upgraded contract if this one is deprecated | function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
require(!isBlackListed[_from]);
require(!isBlackListed[_to]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).tran... | 0.5.0 |
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/ | function release() public {
uint256 nowTime = block.timestamp;
uint256 passTime = nowTime - openingTime;
uint256 weeksnow = passTime/2419200;
require(unfreezed[weeksnow] != 1, "This week we have unfreeze part of the token");
uint256 amount = getPartReleaseAmount();
... | 0.4.23 |
/**
*@dev getMonthRelease is the function to get todays month realse
*
*/ | function getPartReleaseAmount() public view returns(uint256){
uint stage = getStage();
for( uint i = 0; i <= stage; i++ ) {
uint256 stageAmount = totalFreeze/2;
}
uint256 amount = stageAmount*2419200/126230400;
return amount;
} | 0.4.23 |
/**
*@dev getStage is the function to get which stage the lock is on, four year will change the stage
*@return uint256
*/ | function getStage() public view returns(uint256) {
uint256 nowTime = block.timestamp;
uint256 passTime = nowTime - openingTime;
uint256 stage = passTime/126230400; //stage is the lock is on, a day is 86400 seconds
return stage;
} | 0.4.23 |
/**
* @dev Mint `count` tokens if requirements are satisfied.
*
*/ | function mintTokens(uint256 count)
public
payable
nonReentrant{
require(_isPublicMintEnabled, "Mint disabled");
require(count > 0 && count <= 100, "You can drop minimum 1, maximum 100 NFTs");
require(count.add(_tokenIds.current()) < _maxSupply, "Exceeds max supply");
require(owner() == msg.... | 0.8.7 |
/**
* @dev Mint a token to each Address of `recipients`.
* Can only be called if requirements are satisfied.
*/ | function mintTokens(address[] calldata recipients)
public
payable
nonReentrant{
require(recipients.length>0,"Missing recipient addresses");
require(owner() == msg.sender || _isPublicMintEnabled, "Mint disabled");
require(recipients.length > 0 && recipients.length <= 100, "You can drop minimum 1,... | 0.8.7 |
// Source: https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory. | function external_call(address destination, uint value, uint dataOffset, uint dataLength, bytes memory data) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
... | 0.5.17 |
/// @dev Return the amount of token out as liquidation reward for liquidating token in.
/// @param tokenIn Input ERC20 token
/// @param tokenOut Output ERC1155 token
/// @param tokenOutId Output ERC1155 token id
/// @param amountIn Input ERC20 token amount | function convertForLiquidation(
address tokenIn,
address tokenOut,
uint tokenOutId,
uint amountIn
) external view returns (uint) {
require(whitelistERC1155[tokenOut], 'bad token');
address tokenOutUnderlying = IERC20Wrapper(tokenOut).getUnderlyingToken(tokenOutId);
uint rateUnderly... | 0.6.12 |
/// @dev Return the value of the given input as ETH for collateral purpose.
/// @param token ERC1155 token address to get collateral value
/// @param id ERC1155 token id to get collateral value
/// @param amount Token amount to get collateral value
/// @param owner Token owner address | function asETHCollateral(
address token,
uint id,
uint amount,
address owner
) external view returns (uint) {
require(whitelistERC1155[token], 'bad token');
address tokenUnderlying = IERC20Wrapper(token).getUnderlyingToken(id);
uint rateUnderlying = IERC20Wrapper(token).getUnderlyi... | 0.6.12 |
/// @dev Return the value of the given input as ETH for borrow purpose.
/// @param token ERC20 token address to get borrow value
/// @param amount ERC20 token amount to get borrow value
/// @param owner Token owner address | function asETHBorrow(
address token,
uint amount,
address owner
) external view returns (uint) {
uint tier = alphaTier.getAlphaTier(owner);
uint borrFactor = tierTokenFactors[token][tier].borrowFactor;
require(liqIncentives[token] != 0, 'bad underlying borrow');
require(borrFactor ... | 0.6.12 |
/**
* Change voting rules
*
* Make so that proposals need to be discussed for at least `minutesForDebate/60` hours
* and all voters combined must own more than `minimumPercentToPassAVote` multiplied by total supply tokens of `tokenAddress` to be executed
*
* @param _tokenAddress token address
* @param _mi... | function changeVotingRules(Token _tokenAddress, address _chairmanAddress, uint _minimumTokensToVote, uint _minimumPercentToPassAVote, uint _minutesForDebate) onlyOwner public {
require(_chairmanAddress != address(0));
require(_minimumPercentToPassAVote <= 51);
tokenAddress = Token(_tokenAddre... | 0.5.11 |
/**
* Add Proposal
*
* Propose to execute transaction
*
* @param destination is a transaction destination address
* @param weiAmount amount of wei
* @param transactionDescription Description of transaction
* @param transactionBytecode bytecode of transaction
*/ | function newProposal(
address destination,
uint weiAmount,
string memory transactionDescription,
bytes memory transactionBytecode
)
onlyTokenholders public
returns (uint proposalID)
{
proposalID = proposals.length++;
Proposal storage p = ... | 0.5.11 |
/**
* Sign a proposal
*
* Vote `supportsProposal? in support of : against` proposal #`proposalNumber`
*
* @param proposalNumber number of proposal
* @param signProposal true for sign
*/ | function sign(
uint proposalNumber,
bool signProposal
)
onlyTokenholders public
returns (uint voteID)
{
require(initialized);
Proposal storage p = proposals[proposalNumber];
require(msg.sender == chairmanAddress);
require(signProposal == ... | 0.5.11 |
/**
* Log a vote for a proposal
*
* Vote `supportsProposal? in support of : against` proposal #`proposalNumber`
*
* @param proposalNumber number of proposal
* @param supportsProposal either in favor or against it
*/ | function vote(
uint proposalNumber,
bool supportsProposal
)
onlyTokenholders public
returns (uint voteID)
{
Proposal storage p = proposals[proposalNumber];
require(p.voted[msg.sender] != true);
voteID = p.votes.length++;
p.votes[voteID]... | 0.5.11 |
// -------------------------------------------------
// Transfers amount to address
// ------------------------------------------------- | function transfer(address _to, uint256 _amount) public notBeforeCrowdfundEnds returns (bool success) {
require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfered
addToBalance(_to, _amount);
decrementBalance(msg.sender, _amount);
Transfer(msg.sender,... | 0.4.18 |
// -------------------------------------------------
// Finalizes crowdfund. If there are leftover RED, let them overflow to foundation
// ------------------------------------------------- | function finalizeCrowdfund() external onlyCrowdfund {
require(stage == icoStages.PublicSale);
uint256 amount = balanceOf(crowdfundAddress);
if (amount > 0) {
accounts[crowdfundAddress] = 0;
addToBalance(foundationAddress, amount);
Transfer(crowdfundAddre... | 0.4.18 |
// -------------------------------------------------
// Function to unlock 20% RED to private angels investors
// ------------------------------------------------- | function partialUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner notBeforeCrowdfundEnds returns (bool success) {
require(unlock20Done == false);
uint256 amount;
address holder;
for (uint256 i = 0; i < _batchOfAddresses.length; i++) {
holder = _batchOf... | 0.4.18 |
// -------------------------------------------------
// Function to unlock all remaining RED to private angels investors (after 3 months)
// ------------------------------------------------- | function fullUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner checkAngelsLockingPeriod returns (bool success) {
uint256 amount;
address holder;
for (uint256 i = 0; i < _batchOfAddresses.length; i++) {
holder = _batchOfAddresses[i];
amount = angels... | 0.4.18 |
// -------------------------------------------------
// Contract's constructor
// ------------------------------------------------- | function REDCrowdfund(address _tokenAddress) public {
wallet = 0xc65f0d8a880f3145157117Af73fe2e6e8E60eF3c; // ICO wallet address
startsAt = 1515398400; // Jan 8th 2018, 16:00, GMT+8
endsAt = 1517385600; // Jan 31th 2018, 16:00, ... | 0.4.18 |
// -------------------------------------------------
// Function to buy RED. One can also buy RED by calling this function directly and send
// it to another destination.
// ------------------------------------------------- | function buyTokens(address _to) public crowdfundIsActive onlyWhiteList nonZeroAddress(_to) nonZeroValue payable {
uint256 weiAmount = msg.value;
uint256 tokens;
uint price = 2500;
if (RED.isEarlyBirdsStage()) {price = 2750;} // 10% discount for early birds
tokens = w... | 0.4.18 |
/// ============ Functions ============
/// @notice Allows claiming tokens if address is part of merkle tree
/// @param to address of claimee
/// @param amount of tokens owed to claimee
/// @param proof merkle proof to prove address and amount are in tree | function claim(address to, uint256 amount, bytes32[] calldata proof) external {
// Throw if address has already claimed tokens
if (hasClaimed[to]) revert AlreadyClaimed();
// Verify merkle proof, or revert if not in tree
bytes32 leaf = keccak256(abi.encodePacked(to, amount));
bool isValidLeaf = Mer... | 0.8.7 |
// @notice Contributors can retrieve their funds here if crowdsale has paased deadline
// @param (address) _assetAddress = The address of the asset which didn't reach it's crowdfunding goals | function refund(address _assetAddress)
public
whenNotPaused
validAsset(_assetAddress)
afterDeadline(_assetAddress)
notFinalized(_assetAddress)
returns (bool) {
require(database.uintStorage(keccak256(abi.encodePacked("crowdsale.deadline", _assetAddress))) != 0);
database.deleteUint(keccak256(... | 0.4.24 |
//if true, degen can't call their debt | function isDebtorHealthy() public view returns (bool) {
int256 months = monthsAhead();
bool moreThanMonthBehind = months <= -1;
if (months == 0) {
//accounts for being at least 1 day overdue
int256 arrears =
int256(expectedPayments()) -
... | 0.8.0 |
//positive number means Justin has more than met his requirement. Negative means he's in arrears | function expectedAccumulated() public view returns (uint256, uint256) {
uint256 expected = expectedPayments();
if (expected > agreementState.accumulatedRepayments) {
//Justin is behind
return (expected, agreementState.accumulatedRepayments);
} else {
... | 0.8.0 |
//in the event of a critical bug, shutdown contract and withdraw EYE. | function voteForEmergencyShutdown(bool vote) public {
if (msg.sender == users.Justin) {
emergencyShutdownMultisig[EMERGENCY_SHUTDOWN_JUSTIN_INDEX] = vote;
} else if (msg.sender == users.DGVC) {
emergencyShutdownMultisig[EMERGENCY_SHUTDOWN_DEGEN_INDEX] = vote;
}
... | 0.8.0 |
/// @dev Constructor
/// @param _token SilentNotary token contract address
/// @param _teamWallet Wallet address to withdraw unfrozen tokens
/// @param _freezePeriods Ordered array of freeze periods
/// @param _freezePortions Ordered array of balance portions to freeze, in percents | function SilentNotaryTokenStorage (address _token, address _teamWallet, uint[] _freezePeriods, uint[] _freezePortions) public {
require(_token > 0);
require(_teamWallet > 0);
require(_freezePeriods.length > 0);
require(_freezePeriods.length == _freezePortions.length);
token = ERC20(_token);
... | 0.4.18 |
/// @dev Unfreeze currently available amount of tokens | function unfreeze() public onlyOwner {
require(amountFixed);
uint unfrozenTokens = 0;
for (uint i = 0; i < frozenPortions.length; i++) {
var portion = frozenPortions[i];
if (portion.isUnfrozen)
continue;
if (portion.unfreezeTime < now) {
unfrozenTokens = safeAdd(u... | 0.4.18 |
/// @dev Fix current token amount (calculate absolute values of every portion) | function fixAmount() public onlyOwner {
require(!amountFixed);
amountFixed = true;
uint currentBalance = token.balanceOf(this);
for (uint i = 0; i < frozenPortions.length; i++) {
var portion = frozenPortions[i];
portion.portionAmount = safeDiv(safeMul(currentBalance, portion.portionP... | 0.4.18 |
/// @dev Deposit BBO. | function depositBBO() payable {
require(depositStartTime > 0);
require(msg.value == 0);
require(now >= depositStartTime && now <= depositStopTime);
ERC20 bboToken = ERC20(bboTokenAddress);
uint bboAmount = bboToken
.balanceOf(msg.sender)
.... | 0.4.24 |
/// @dev Withdrawal BBO. | function withdrawBBO() payable {
require(depositStartTime > 0);
require(bboDeposited > 0);
Record storage record = records[msg.sender];
require(now >= record.timestamp + WITHDRAWAL_DELAY);
require(record.bboAmount > 0);
uint bboWithdrawalBase = record.bboAmount;... | 0.4.24 |
//////////
/// @notice Get the list of whitelisted addresses
/// @return The list of whitelisted addresses | function getWhitelisted() external view returns(address[] memory) {
uint256 length = _whitelisted.length();
address[] memory result = new address[](length);
for (uint256 i=0; i < length; i++) {
result[i] = _whitelisted.at(i);
}
return result;
} | 0.7.6 |
/// @notice Get fee (In basis points) to pay by a given user, for a given fee type
/// @param _user The address for which to calculate the fee
/// @param _hasReferrer Whether the address has a referrer or not
/// @param _feeType The type of fee
/// @return The protocol fee to pay by _user (In basis points) | function getFee(address _user, bool _hasReferrer, FeeType _feeType) public view returns(uint256) {
if (_whitelisted.contains(_user)) return 0;
uint256 fee = _getBaseFee(_feeType);
// If premiaFeeDiscount contract is set, we calculate discount
if (address(premiaFeeDiscount) != add... | 0.7.6 |
/// @notice Calculate protocol fee and referrer fee to pay, from a total fee (in wei), after applying all discounts
/// @param _user The address for which to calculate the fee
/// @param _hasReferrer Whether the address has a referrer or not
/// @param _baseFee The total fee to pay (without including any discount)
/// ... | function getFeeAmountsWithDiscount(address _user, bool _hasReferrer, uint256 _baseFee) public view returns(uint256 _fee, uint256 _feeReferrer) {
if (_whitelisted.contains(_user)) return (0,0);
uint256 feeReferrer = 0;
uint256 feeDiscount = 0;
// If premiaFeeDiscount contract is s... | 0.7.6 |
//////////////
/// @notice Get the base protocol fee, for a given fee type
/// @param _feeType The type of fee
/// @return The base protocol fee for _feeType (In basis points) | function _getBaseFee(FeeType _feeType) internal view returns(uint256) {
if (_feeType == FeeType.Write) {
return writeFee;
} else if (_feeType == FeeType.Exercise) {
return exerciseFee;
} else if (_feeType == FeeType.Maker) {
return makerFee;
} e... | 0.7.6 |
//Storage of addresses is broken into smaller contracts. | function importAddresses(address[] parentsArray,address[] childrenArray) {
if (numImports<maxImports) {
numImports++;
addressesImported(msg.sender,childrenArray.length,numImports); //Details of import
balanceOf[0x000000000000000000000000000000000000dEaD]=numImports*initialSupplyPerChildAddress; //Easy way fo... | 0.4.13 |
/***************************************
ADMIN
****************************************/ | function notifyRewardAmount(uint256 _reward)
external
onlyRewardsDistributor
updateReward(address(0))
{
uint256 currentTime = block.timestamp;
// If previous period over, reset rewardRate
if (currentTime >= periodFinish) {
rewardRate = _reward.div(... | 0.5.16 |
// validates a proof-of-work for a given NFT, with a supplied nonce
// at a given difficulty level | function work(
uint256 id, uint256 nonce, uint8 difficulty
) public view returns (bool) {
bytes32 candidate = _firstn(
keccak256(abi.encodePacked(address(this), id, nonce)),
difficulty
);
bytes32 target = _firstn(
bytes32(uint256(address(th... | 0.6.12 |
/**
* @dev Returns a token IDs array owned by `owner`.
*/ | function tokensByOwner(address owner) external view returns (uint256[] memory) {
if (balanceOf(owner) == 0) {
return new uint256[](0);
}
uint256 tokensOwned = 0;
uint256 idIndex = 0;
for(uint i = 1; i <= currentSupply; i++) {
if (ownerOf(i) == owner) {
tokensOwne... | 0.8.0 |
// UniV2 / SLP Info | function uniV2LPBasicInfo(address pair_address) public view returns (UniV2LPBasicInfo memory) {
// Instantiate the pair
IUniswapV2Pair the_pair = IUniswapV2Pair(pair_address);
// Get the reserves
(uint256 reserve0, uint256 reserve1, ) = (the_pair.getReserves());
// Get t... | 0.8.10 |
// ( 4 * 5 * (86400000) ) / 1 days; | function update(address from, address to) external onlyAllowed {
if (from != address(0)) {
rewards[from] += getPending(from);
lastClaimDatetime[from] = block.timestamp;
}
if (to != address(0)) {
rewards[to] += getPending(to);
lastClaimDatetime[to] ... | 0.8.2 |
// View function to see pending ERC20s for a user. | function pending(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accERC20PerShare = pool.accERC20PerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
... | 0.6.12 |
// Deposit LP tokens to Farm for ERC20 allocation. | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user... | 0.6.12 |
// Withdraw LP tokens from Farm. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: can't withdraw more than deposit");
updatePool(_pid);
uint256 pendingAmount = user... | 0.6.12 |
// This is the constructor and automatically runs when the smart contract is uploaded | function FMT() { // Set the constructor to the same name as the contract name
name = "FINGER MOBILE TOKEN"; // set the token name here
symbol = "FMT"; // set the Symbol here
decimals = 8; // set the number of decimals
devAddress=0x6eC2f42d083F29e2cd19eC0e4d99A22B4a8A31cf; // Add the address that you... | 0.4.26 |
/**
* @dev Transfer tokens direct to recipient without allocation.
* _recipient can only get one transaction and _tokens can't be above maxDirect value
*
*/ | function transferDirect(address _recipient,uint256 _tokens) public{
//Check if contract has tokens
require(token.balanceOf(this)>=_tokens);
//Check max value
require(_tokens < maxDirect );
//Check if _recipient already have got tokens
require(!recipients[_recipient]);
recip... | 0.4.24 |
/**
* Requests randomness from a user-provided seed
*/ | function getRandomNumber(uint256 userProvidedSeed) public onlyDistributer returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
require(!progress, "now getting an random number.");
winner = 0;
progress = tr... | 0.8.1 |
// Function to distribute punk. | function setPunkWinner() external onlyOwner {
require(_prevRandomCallCount != _randomCallCount, "Please generate random number.");
require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');
require(_punkWinner == 6500, 'You already picked punk winner');
_p... | 0.8.1 |
// Function to distribute legendary monster. | function setLegendaryMonsterWinner() external onlyOwner {
require(_prevRandomCallCount != _randomCallCount, "Please generate random number.");
require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');
_prevRandomCallCount = _randomCallCount;
uint2... | 0.8.1 |
// Function to distribute eth. | function setETHWinner() external onlyOwner {
require(_prevRandomCallCount != _randomCallCount, "Please generate random number.");
require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');
_prevRandomCallCount = _randomCallCount;
uint256 _tempWinne... | 0.8.1 |
// Function to distribute zed. | function setZedWinner() external onlyOwner {
require(_prevRandomCallCount != _randomCallCount, "Please generate random number.");
require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');
_prevRandomCallCount = _randomCallCount;
uint256 _tempWinne... | 0.8.1 |
// ======== Claim / Minting ========= | function mintCommunity(uint amount) external nonReentrant {
require(saleIsActive, "Sale must be active to claim!");
require(block.timestamp >= communitySaleStart && block.timestamp < publicSaleStart, "Community sale not active!");
require(amount > 0, "Enter valid amount to claim");
r... | 0.8.6 |
// ======== Snapshot / Whitelisting | function snapshot(address[] memory _addresses, uint[] memory _godsToClaim) external onlyOwner {
require(_addresses.length == _godsToClaim.length, "Invalid snapshot data");
for (uint i = 0; i < _addresses.length; i++) {
addressToClaimableGods[_addresses[i]] = _godsToClaim[i];
}
... | 0.8.6 |
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/ | function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender a... | 0.8.0 |
/**
* @dev Allow AMFEIX to transfer AMF to claiming users
*
* @param tokenAmount Amount of tokens to be sent
* @param userAddress BTC address on which users willing to receive payment
* @param btcTxId ID of the AMF buying transaction on Bitcoin network
*/ | function payAMF(uint256 tokenAmount, address userAddress, string memory btcTxId) public virtual returns (bool) {
require(_msgSender() == _tokenPool, "Only AMFEIX can use this method");
_transfer(_msgSender(), userAddress, tokenAmount);
emit AmfPaid(userAddress, btcTxId, tokenAmount);
... | 0.8.0 |
/**
* @dev Get the royalty fee percentage for a specific ERC1155 contract.
* @param _tokenId uint256 token ID.
* @return uint8 wei royalty fee.
*/ | function getTokenRoyaltyPercentage(
uint256 _tokenId
) public view override returns (uint8) {
if (tokenRoyaltyPercentage[_tokenId] > 0) {
return tokenRoyaltyPercentage[_tokenId];
}
address creator =
iERC1155TokenCreator.tokenCreator(_tokenId);
if (creatorR... | 0.6.12 |
/**
* @dev Sets the royalty percentage set for an Nafter token
* Requirements:
* - `_percentage` must be <= 100.
* - only the owner of this contract or the creator can call this method.
* @param _tokenId uint256 token ID.
* @param _percentage uint8 wei royalty fee.
*/ | function setPercentageForTokenRoyalty(
uint256 _tokenId,
uint8 _percentage
) external override returns (uint8) {
require(
msg.sender == iERC1155TokenCreator.tokenCreator(_tokenId) ||
msg.sender == owner() ||
msg.sender == nafter,
"setPercentage... | 0.6.12 |
/**
* @dev restore data from old contract, only call by owner
* @param _oldAddress address of old contract.
* @param _oldNafterAddress get the token ids from the old nafter contract.
* @param _startIndex start index of array
* @param _endIndex end index of array
*/ | function restore(address _oldAddress, address _oldNafterAddress, uint256 _startIndex, uint256 _endIndex) external onlyOwner {
NafterRoyaltyRegistry oldContract = NafterRoyaltyRegistry(_oldAddress);
INafter oldNafterContract = INafter(_oldNafterAddress);
uint256 length = oldNafterContract.getTok... | 0.6.12 |
/**
* Lazily mint some reserved tokens
*/ | function mintReserved(uint numberOfTokens) public onlyOwner {
require(
_reservedTokenIdCounter.current().add(numberOfTokens) <= RESERVED_TOTAL,
"Minting would exceed max reserved supply"
);
for (uint i = 0; i < numberOfTokens; i++) {
_safeMintGeneric(msg.sende... | 0.8.4 |
/**
* @dev Throttle minting to once a block and reset the reclamation threshold
* whenever a new token is minted or transferred.
*/ | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
// If minting: ensure it's the only one from this tx origin in the block.
if (from == addre... | 0.8.7 |
/**
* @dev Wrap an original or extra discreet NFT when transferred to this
* contract via `safeTransferFrom` during the migration period.
*/ | function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external override returns (bytes4) {
require(
block.number < migrationEnds,
"discreet: token migration is complete."
);
requir... | 0.8.7 |
/**
* @dev Mint a given discreet NFT if it is currently available.
*/ | function mint(uint256 tokenId) external override {
require(
tokenId < 0x510,
"discreet: cannot mint out-of-range token"
);
if (tokenId < 0x360) {
require(
block.number >= migrationEnds,
"discreet: cannot mint tokens fr... | 0.8.7 |
/**
* @dev Mint a given NFT if it is currently available to a given address.
*/ | function mint(address to, uint256 tokenId) external override {
require(
tokenId < 0x510,
"discreet: cannot mint out-of-range token"
);
if (tokenId < 0x360) {
require(
block.number >= migrationEnds,
"discreet: cannot mi... | 0.8.7 |
/**
* @dev Burn a given discreet NFT if it is owned, approved or reclaimable.
* Tokens become reclaimable after ~4 million blocks without a transfer.
*/ | function burn(uint256 tokenId) external override {
require(
tokenId < 0x510,
"discreet: cannot burn out-of-range token"
);
// Only enforce check if tokenId has not reached reclaimable threshold.
if (!isReclaimable(tokenId)) {
require(
... | 0.8.7 |
/**
* @dev Derive and return a tokenURI json payload formatted as a
* data URI.
*/ | function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "discreet #',
_toString(tokenId),
... | 0.8.7 |
// @notice sets current round goal amount
// @dev the current deposit must be less than or equal to goal
// @dev only issuance manager role can call this function
// @param _newGoal the new goal amount to set the current round to | function setCurrentRoundGoal(uint256 _newGoal)
external
nonReentrant
onlyRole(ISSUANCE_MANAGER)
onlyStage(Stages.Started, currentRoundId)
{
uint256 totalDeposit = roundData[currentRoundId].totalDeposit;
require(
totalDeposit <= _newGoal,
"issua... | 0.8.0 |
// @notice purchase a ticket of an amount in denominated asset into current round
// @dev user should only have one ticket per round
// @dev the contract must not be paused
// @dev only once round has started and goal has not been met | function purchaseTicket(uint256 _amount)
external
nonReentrant
whenNotPaused
onlyStage(Stages.Started, currentRoundId)
{
require(_amount > 0, "issuance: amount can't be zero");
denomAsset.safeTransferFrom(msg.sender, address(this), _amount);
uint256 _totalDepo... | 0.8.0 |
// @notice use the round's deposited assets to issue new vault tokens
// @dev only callable from issuance manager
// @dev can only issue for current round and after the goal is met | function issue()
external
nonReentrant
onlyRole(ISSUANCE_MANAGER)
onlyStage(Stages.GoalMet, currentRoundId)
{
// approve vault and deposit
uint256 amount = roundData[currentRoundId].totalDeposit;
denomAsset.safeApprove(vault, amount);
uint256 mintedVau... | 0.8.0 |
// @notice redeem the round ticket for vault tokens
// @param _roundId the identifier of the round
// @dev the round must have ended and vault tokens are issued | function redeemTicket(uint256 _roundId)
external
nonReentrant
onlyStage(Stages.End, _roundId)
{
// ensure the user ticket exists in the round specified
Ticket memory ticket = userTicket[_roundId][msg.sender];
RoundData memory round = roundData[_roundId];
requi... | 0.8.0 |
/// @notice Pause recipient vesting
/// @dev This freezes the vesting schedule for the paused recipient.
/// Recipient will NOT be able to claim until unpaused.
/// Only owner of the vesting escrow can invoke this function.
/// Can only be invoked if the escrow is NOT terminated.
/// @param recipient The... | function pauseRecipient(address recipient) external onlyOwner escrowNotTerminated isNonZeroAddress(recipient) {
// current recipient status should be UnPaused
require(recipients[recipient].recipientVestingStatus == Status.UnPaused, "pauseRecipient: cannot pause");
// set vesting status of the re... | 0.7.6 |
/// @notice UnPause recipient vesting
/// @dev This unfreezes the vesting schedule for the paused recipient. Recipient will be able to claim.
/// In order to keep vestingPerSec for the recipient a constant, cliffDuration and endTime for the
/// recipient are shifted by the pause duration so that the recipient... | function unPauseRecipient(address recipient) external onlyOwner escrowNotTerminated isNonZeroAddress(recipient) {
// current recipient status should be Paused
require(recipients[recipient].recipientVestingStatus == Status.Paused, "unPauseRecipient: cannot unpause");
// set vesting status of the ... | 0.7.6 |
/// @notice Terminate recipient vesting
/// @dev This terminates the vesting schedule for the recipient forever.
/// Recipient will NOT be able to claim.
/// Only owner of the vesting escrow can invoke this function.
/// Can only be invoked if the escrow is NOT terminated.
/// @param recipient The recipi... | function terminateRecipient(address recipient) external onlyOwner escrowNotTerminated isNonZeroAddress(recipient) {
// current recipient status should NOT be Terminated
require(recipients[recipient].recipientVestingStatus != Status.Terminated, "terminateRecipient: cannot terminate");
// claim fo... | 0.7.6 |
// claim tokens for a specific recipient | function _claimFor(uint256 _amount, address _recipient) internal {
// get recipient
Recipient storage recipient = recipients[_recipient];
// recipient should be able to claim
require(canClaim(_recipient), "_claimFor: recipient cannot claim");
// max amount the user can claim ri... | 0.7.6 |
/// @notice Check if a recipient address can successfully invoke claim.
/// @dev Reverts if the recipient is a zero address.
/// @param recipient A zero address recipient address.
/// @return bool representing if the recipient can successfully invoke claim. | function canClaim(address recipient) public view isNonZeroAddress(recipient) returns (bool) {
Recipient memory _recipient = recipients[recipient];
// terminated recipients cannot claim
if (_recipient.recipientVestingStatus == Status.Terminated) {
return false;
}
// ... | 0.7.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.