comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
_mintOne function:
1. generate the NFT
*/ | function _mintOne(address toAddress, uint256 randomness) internal {
// Check supply
require(
mintedNumber < MAX_NFT_NUMBER,
"Insufficient supply"
);
uint256 seedIndex;
uint256 printIndex;
(seedIndex, printIndex) = _calc(randomness);
... | 0.6.12 |
/**
_calc: calculate the seed index and print index from the random number
*/ | function _calc(uint256 randomness) internal view returns (uint256, uint256) {
assert(mintedNumber < MAX_NFT_NUMBER);
uint256 n = randomness.safeMod(MAX_NFT_NUMBER.safeSub(mintedNumber)).safeAdd(1);
for (uint256 seedIndex = STARTING_INDEX; seedIndex <= MAX_SEED_NUMBER; seedIndex = seedIndex.sa... | 0.6.12 |
/**
* _genToken generates unique token for each NFT
* - 1st byte: seedIndex
* - 2nd byte: printIndex
* - 3rd byte: score
* - 4th byte: zero (reserved byte)
*/ | function _genToken(address toAddress, uint256 seedIndex, uint256 printIndex, uint256 score) internal view returns (uint256) {
bytes32 hash = keccak256(abi.encodePacked(block.number, blockhash(block.number - 1), toAddress, seedIndex, printIndex, score));
uint256 token = 0;
for (uint256 i = 0; ... | 0.6.12 |
/**
_getRandomNumber: send the request number request to chain.link
*/ | function _getRandomNumber(uint256 seed) internal returns (bytes32) {
uint256 linkBalance = LINK.balanceOf(address(this));
require(
linkBalance >= LINK_FEE,
"Contract doesn't have enough LINK"
);
console.log("operation:callChainLink seed:%s balance:%s", seed... | 0.6.12 |
/**
return the substring which has length of k
*/ | function _substr(string memory _str, uint256 k) internal pure returns (string memory) {
bytes memory bstr = bytes(_str);
if (k >= bstr.length) {
return _str;
}
bytes memory bsubstr = new bytes(k);
for (uint i = 0; i < k; i++) {
bsubstr[i] ... | 0.6.12 |
/**
* @dev Request the random number to be used for a batch mint
*/ | function requestRandomNumber() external onlyOwner {
// Can trigger only one randomness request at a time
require(
randomNumberStatus != RNStatus.requested,
"Random number already requested"
);
// We need some LINK to pay a fee to the oracles
require(LINK.balanceOf(address(this)) >= fee, ... | 0.8.4 |
/**
* Called by Chainlink oracles when sending back a random number for
* a given request
* This function cannot use more than 200,000 gas or the transaction
* will fail
*/ | function fulfillRandomness(bytes32 requestId, uint256 randomNumber)
internal
override
{
// Put 16 bytes of randomNumber into randomSeed
randomSeed =
randomNumber &
0xffffffffffffffff0000000000000000ffffffffffffffff0000000000000000;
// Put the other 16 bytes of randomNumber into randomI... | 0.8.4 |
/**
Get NEW TAT2, use approve/transferFrom
@param amount number of old TAT2
*/ | function swap(uint256 amount) external {
uint8 decimals = newtat2decimals - oldtat2decimals;
uint256 newamount = amount * (10 ** decimals);
require(
INterfaces(oldtat2).transferFrom(msg.sender, address(this), amount),
ERR_TRANSFER
);
require(
I... | 0.8.7 |
/// @dev Settle system debt in MakerDAO and free remaining collateral. | function settleTreasury() public {
require(
live == false,
"Unwind: Unwind first"
);
(uint256 ink, uint256 art) = vat.urns(WETH, address(treasury));
require(ink > 0, "Unwind: Nothing to settle");
_treasuryWeth = ink; // ... | 0.6.10 |
/// @dev Put all chai savings in MakerDAO and exchange them for weth | function cashSavings() public {
require(
end.tag(WETH) != 0,
"Unwind: End.sol not caged"
);
require(
end.fix(WETH) != 0,
"Unwind: End.sol not ready"
);
uint256 chaiTokens = chai.balanceOf(address(treasury));
... | 0.6.10 |
/// @dev Settles a series position in Controller for any user, and then returns any remaining collateral as weth using the unwind Dai to Weth price.
/// @param collateral Valid collateral type.
/// @param user User vault to settle, and wallet to receive the corresponding weth. | function settle(bytes32 collateral, address user) public {
(uint256 tokens, uint256 debt) = controller.erase(collateral, user);
require(tokens > 0, "Unwind: Nothing to settle");
uint256 remainder;
if (collateral == WETH) {
remainder = subFloorZero(tokens, daiToFixWeth(... | 0.6.10 |
/// @dev Redeems FYDai for weth for any user. FYDai.redeem won't work if MakerDAO is in shutdown.
/// @param maturity Maturity of an added series
/// @param user Wallet containing the fyDai to burn. | function redeem(uint256 maturity, address user) public {
IFYDai fyDai = controller.series(maturity);
require(fyDai.unlocked() == 1, "fyDai is still locked");
uint256 fyDaiAmount = fyDai.balanceOf(user);
require(fyDaiAmount > 0, "Unwind: Nothing to redeem");
fyDai.burn(user... | 0.6.10 |
/**
@notice This function adds liquidity to a Curve pool with ETH or ERC20 tokens
@param _fromTokenAddress The token used for entry (address(0) if ether)
@param _toTokenAddress The intermediate ERC20 token to swap to
@param _swapAddress Curve swap address for the pool
@param _incomingTokenQty The amount of fr... | function ZapIn(
address _fromTokenAddress,
address _toTokenAddress,
address _swapAddress,
uint256 _incomingTokenQty,
uint256 _minPoolTokens,
address _swapTarget,
bytes calldata _swapCallData,
address affiliate
) external payable stopInEmergenc... | 0.5.17 |
/**
@notice This function gets adds the liquidity for meta pools and returns the token index and swap tokens
@param _swapAddress Curve swap address for the pool
@param _toTokenAddress The ERC20 token to which from token to be convert
@param swapTokens amount of toTokens to invest
@return tokensBought- quanti... | function _enterMetaPool(
address _swapAddress,
address _toTokenAddress,
uint256 swapTokens
) internal returns (uint256 tokensBought, uint8 index) {
address[4] memory poolTokens = curveReg.getPoolTokens(_swapAddress);
for (uint8 i = 0; i < 4; i++) {
address ... | 0.5.17 |
/**
@notice This function adds liquidity to a curve pool
@param _swapAddress Curve swap address for the pool
@param amount The quantity of tokens being added as liquidity
@param index The token index for the add_liquidity call
@return crvTokensBought- the quantity of curve LP tokens received
*/ | function _enterCurve(
address _swapAddress,
uint256 amount,
uint8 index
) internal returns (uint256 crvTokensBought) {
address tokenAddress = curveReg.getTokenAddress(_swapAddress);
address depositAddress = curveReg.getDepositAddress(_swapAddress);
uint256 init... | 0.5.17 |
// base rate is 100, so for 1 to 1 send in 100 as ratio | function addMiningToken(address tokenAddr, uint ratio) onlyAdmin external {
require(exchangeRatios[tokenAddr] == 0 && ratio > 0 && ratio < 10000);
exchangeRatios[tokenAddr] = ratio;
bool found = false;
for (uint16 i = 0; i < miningTokens.length; i++) {
if (miningTokens[i] == tokenAddr) {
... | 0.4.24 |
// This function is called at the time of contract creation,
// it sets the initial variables and whitelists the contract owner. | function PresalePool (address receiverAddr, uint contractCap, uint cap, uint fee) public {
require (fee < 100);
require (contractCap >= cap);
owner = msg.sender;
receiverAddress = receiverAddr;
maxContractBalance = contractCap;
contributionCap = cap;
feePct = _toPct(fee,100);
} | 0.4.19 |
// Internal function for handling eth deposits during contract stage one. | function _ethDeposit () internal {
assert (contractStage == 1);
require (!whitelistIsActive || whitelistContract.isPaidUntil(msg.sender) > now);
require (tx.gasprice <= maxGasPrice);
require (this.balance <= maxContractBalance);
var c = whitelist[msg.sender];
uint newBalance = c.balance.ad... | 0.4.19 |
// This function is called to withdraw eth or tokens from the contract.
// It can only be called by addresses that are whitelisted and show a balance greater than 0.
// If called during stage one, the full eth balance deposited into the contract is returned and the contributor's balance reset to 0.
// If called during ... | function withdraw (address tokenAddr) public {
var c = whitelist[msg.sender];
require (c.balance > 0);
if (contractStage == 1) {
uint amountToTransfer = c.balance;
c.balance = 0;
msg.sender.transfer(amountToTransfer);
ContributorBalanceChanged(msg.sender, 0);
} else {
... | 0.4.19 |
// This internal function handles withdrawals during stage two.
// The associated events will fire to notify when a refund or token allocation is claimed. | function _withdraw (address receiver, address tokenAddr) internal {
assert (contractStage == 2);
var c = whitelist[receiver];
if (tokenAddr == 0x00) {
tokenAddr = activeToken;
}
var d = distributionMap[tokenAddr];
require ( (ethRefundAmount.length > c.ethRefund) || d.pct.length > c.... | 0.4.19 |
// This function is called by the owner to modify the cap at a future time. | function modifyNextCap (uint time, uint cap) public onlyOwner {
require (contractStage == 1);
require (contributionCap <= cap && maxContractBalance >= cap);
require (time > now);
nextCapTime = time;
nextContributionCap = cap;
} | 0.4.19 |
// This callable function returns the total pool cap, current balance and remaining balance to be filled. | function checkPoolBalance () view public returns (uint poolCap, uint balance, uint remaining) {
if (contractStage == 1) {
remaining = maxContractBalance.sub(this.balance);
} else {
remaining = 0;
}
return (maxContractBalance,this.balance,remaining);
} | 0.4.19 |
// This callable function returns the balance, contribution cap, and remaining available balance of any contributor. | function checkContributorBalance (address addr) view public returns (uint balance, uint cap, uint remaining) {
var c = whitelist[addr];
if (contractStage == 2) return (c.balance,0,0);
if (whitelistIsActive && whitelistContract.isPaidUntil(addr) < now) return (c.balance,0,0);
if (c.cap > 0) cap = c.c... | 0.4.19 |
// This callable function returns the token balance that a contributor can currently claim. | function checkAvailableTokens (address addr, address tokenAddr) view public returns (uint tokenAmount) {
var c = whitelist[addr];
var d = distributionMap[tokenAddr];
for (uint i = c.tokensClaimed[tokenAddr]; i < d.pct.length; i++) {
tokenAmount = tokenAmount.add(_applyPct(c.balance, d.pct[i]));
... | 0.4.19 |
// This function sends the pooled eth to the receiving address, calculates the % of unused eth to be returned,
// and advances the contract to stage two. It can only be called by the contract owner during stages one or two.
// The amount to send (given in wei) must be specified during the call. As this function can onl... | function submitPool (uint amountInWei) public onlyOwner noReentrancy {
require (contractStage == 1);
require (receiverAddress != 0x00);
require (block.number >= addressChangeBlock.add(6000));
if (amountInWei == 0) amountInWei = this.balance;
require (contributionMin <= amountInWei && amountInWe... | 0.4.19 |
// This function opens the contract up for token withdrawals.
// It can only be called by the owner during stage two. The owner specifies the address of an ERC20 token
// contract that this contract has a balance in, and optionally a bool to prevent this token from being
// the default withdrawal (in the event of an a... | function enableTokenWithdrawals (address tokenAddr, bool notDefault) public onlyOwner noReentrancy {
require (contractStage == 2);
if (notDefault) {
require (activeToken != 0x00);
} else {
activeToken = tokenAddr;
}
var d = distributionMap[tokenAddr];
if (d.pct.length==0)... | 0.4.19 |
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*
* HINT: This function is 'internal' and therefore can only be called from another
... | function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
... | 0.6.12 |
/**
@dev Inserts a new node between _prev and _next. When inserting a node already existing in
the list it will be automatically removed from the old position.
@param _prev the node which _new will be inserted after
@param _curr the id of the new node being inserted
@param _next the node which _new will be i... | function insert(Data storage self, uint _prev, uint _curr, uint _next) public {
require(_curr != NULL_NODE_ID);
remove(self, _curr);
require(_prev == NULL_NODE_ID || contains(self, _prev));
require(_next == NULL_NODE_ID || contains(self, _next));
require(getNext(self, _prev) == _next);
... | 0.4.24 |
/**
@notice Commits vote using hash of choice and secret salt to conceal vote until reveal
@param _pollID Integer identifier associated with target poll
@param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order)
@param _numTokens The number of tokens to be committed towar... | function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {
require(commitPeriodActive(_pollID));
// if msg.sender doesn't have enough voting rights,
// request for enough voting rights
if (voteTokenBalance[msg.sender] < _numTokens) {
... | 0.4.24 |
/**
@notice Commits votes using hashes of choices and secret salts to conceal votes until reveal
@param _pollIDs Array of integer identifiers associated with target polls
@param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order)
... | function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external {
// make sure the array lengths are all the same
require(_pollIDs.length == _secretHashes.length);
require(_pollIDs.length == _numsTokens.length);
require(_pollIDs.length... | 0.4.24 |
/**
@dev Compares previous and next poll's committed tokens for sorting purposes
@param _prevID Integer identifier associated with previous poll in sorted order
@param _nextID Integer identifier associated with next poll in sorted order
@param _voter Address of user to check DLL position for
@param _numTokens... | function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) {
bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID));
// if next is zero node, _numTokens does not need to be greater
bool nextValid = (_numTokens <= getNumToke... | 0.4.24 |
/**
@notice Reveals vote with choice and secret salt used in generating commitHash to attribute committed tokens
@param _pollID Integer identifier associated with target poll
@param _voteOption Vote choice used to generate commitHash for associated poll
@param _salt Secret number used to generate commitHash for... | function revealVote(uint _pollID, uint _voteOption, uint _salt) public {
// Make sure the reveal period is active
require(revealPeriodActive(_pollID));
require(pollMap[_pollID].didCommit[msg.sender]); // make sure user has committed a vote for this poll
requir... | 0.4.24 |
/**
@notice Reveals multiple votes with choices and secret salts used in generating commitHashes to attribute committed tokens
@param _pollIDs Array of integer identifiers associated with target polls
@param _voteOptions Array of vote choices used to generate commitHashes for associated polls
@p... | function revealVotes(uint[] _pollIDs, uint[] _voteOptions, uint[] _salts) external {
// make sure the array lengths are all the same
require(_pollIDs.length == _voteOptions.length);
require(_pollIDs.length == _salts.length);
// loop through arrays, revealing each individual vote va... | 0.4.24 |
/**
@param _voter Address of voter who voted in the majority bloc
@param _pollID Integer identifier associated with target poll
@return correctVotes Number of tokens voted for winning option
*/ | function getNumPassingTokens(address _voter, uint _pollID) public constant returns (uint correctVotes) {
require(pollEnded(_pollID));
require(pollMap[_pollID].didReveal[_voter]);
uint winningChoice = isPassed(_pollID) ? 1 : 0;
uint voterVoteOption = pollMap[_pollID].voteOptions[_vo... | 0.4.24 |
/**
@dev Initiates a poll with canonical configured parameters at pollID emitted by PollCreated event
@param _voteQuorum Type of majority (out of 100) that is necessary for poll to be successful
@param _commitDuration Length of desired commit period in seconds
@param _revealDuration Length of desired reveal per... | function startPoll(uint _voteQuorum, uint _commitDuration, uint _revealDuration) public returns (uint pollID) {
pollNonce = pollNonce + 1;
uint commitEndDate = block.timestamp.add(_commitDuration);
uint revealEndDate = commitEndDate.add(_revealDuration);
pollMap[pollNonce] = Poll... | 0.4.24 |
/*
@dev Takes the last node in the user's DLL and iterates backwards through the list searching
for a node with a value less than or equal to the provided _numTokens value. When such a node
is found, if the provided _pollID matches the found nodeID, this operation is an in-place
update. In that case, return the... | function getInsertPointForNumTokens(address _voter, uint _numTokens, uint _pollID)
constant public returns (uint prevNode) {
// Get the last node in the list and the number of tokens in that node
uint nodeID = getLastNode(_voter);
uint tokensInNode = getNumTokens(_voter, nodeID);
... | 0.4.24 |
/**
@notice propose a reparamaterization of the key _name's value to _value.
@param _name the name of the proposed param to be set
@param _value the proposed value to set the param to be set
*/ | function proposeReparameterization(string _name, uint _value) public returns (bytes32) {
uint deposit = get("pMinDeposit");
bytes32 propID = keccak256(abi.encodePacked(_name, _value));
if (keccak256(abi.encodePacked(_name)) == keccak256(abi.encodePacked("dispensationPct")) ||
k... | 0.4.24 |
/**
@notice challenge the provided proposal ID, and put tokens at stake to do so.
@param _propID the proposal ID to challenge
*/ | function challengeReparameterization(bytes32 _propID) public returns (uint challengeID) {
ParamProposal memory prop = proposals[_propID];
uint deposit = prop.deposit;
require(propExists(_propID) && prop.challengeID == 0);
//start poll
uint pollID = voting.startPoll(
... | 0.4.24 |
/**
@notice Claim the tokens owed for the msg.sender in the provided challenge
@param _challengeID the challenge ID to claim tokens for
*/ | function claimReward(uint _challengeID) public {
Challenge storage challenge = challenges[_challengeID];
// ensure voter has not already claimed tokens and challenge results have been processed
require(challenge.tokenClaims[msg.sender] == false);
require(challenge.resolved == true);
... | 0.4.24 |
/**
@notice Determines the number of tokens to awarded to the winning party in a challenge
@param _challengeID The challengeID to determine a reward for
*/ | function challengeWinnerReward(uint _challengeID) public view returns (uint) {
if(voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) {
// Edge case, nobody voted, give all tokens to the challenger.
return 2 * challenges[_challengeID].stake;
}
return ... | 0.4.24 |
/**
@dev resolves a challenge for the provided _propID. It must be checked in advance whether the _propID has a challenge on it
@param _propID the proposal ID whose challenge is to be resolved.
*/ | function resolveChallenge(bytes32 _propID) private {
ParamProposal memory prop = proposals[_propID];
Challenge storage challenge = challenges[prop.challengeID];
// winner gets back their full staked deposit, and dispensationPct*loser's stake
uint reward = challengeWinnerReward(prop... | 0.4.24 |
/**
* @dev override transferFrom token for a specified address to add validDestination
* @param _from The address to transfer from.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | function transferFrom(address _from, address _to, uint256 _value)
onlyPayloadSize(32 + 32 + 32) // address (32) + address (32) + uint256 (32)
validDestination(_to)
onlyWhenTransferEnabled
public
returns (bool)
{
return super.transferFrom(_from, _to, _value);
} | 0.4.26 |
// can never adjust tradable cards
// each season gets a 'balancing beta'
// totally immutable: season, rarity | function replaceProto(
uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) public onlyGovernor {
ProtoCard memory pc = protos[index];
require(!seasonTradable[pc.season]);
protos[index] = ProtoCard({
exists: true,
... | 0.4.24 |
/**
* @param proposed : the claimed owner of the cards
* @param ids : the ids of the cards to check
* @return whether proposed owns all of the cards
*/ | function ownsAll(address proposed, uint[] ids) public view returns (bool) {
for (uint i = 0; i < ids.length; i++) {
if (!owns(proposed, ids[i])) {
return false;
}
}
return true;
} | 0.4.24 |
/**
* @param id : the index of the token to burn
*/ | function burn(uint id) public {
// require(isTradable(cards[id].proto));
require(owns(msg.sender, id));
burnCount++;
// use the internal transfer function as the external
// has a guard to prevent transfers to 0x0
_transfer(msg.sender, address(0), id);
} | 0.4.24 |
/**
* @param to : the address to which the token should be transferred
* @param id : the index of the token to transfer
*/ | function transferFrom(address from, address to, uint id) public payable {
require(to != address(0));
require(to != address(this));
// TODO: why is this necessary
// if you're approved, why does it matter where it comes from?
require(ownerOf(id) == from);
... | 0.4.24 |
// store purity and shine as one number to save users gas | function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16) {
if (randOne >= 998) {
return 3000 + randTwo;
} else if (randOne >= 988) {
return 2000 + randTwo;
} else if (randOne >= 938) {
return 1000 + randTwo;
} else {
... | 0.4.24 |
// can be called by anybody | function callback(uint id) public {
Purchase storage p = purchases[id];
require(p.randomness == 0);
bytes32 bhash = blockhash(p.commit);
uint random = uint(keccak256(abi.encodePacked(totalCount, bhash)));
totalCount += p.count;
if (uint(bhash) == 0) {
... | 0.4.24 |
// Get all tiers | function getAllTiers() external view returns (Tier[] memory) {
Tier[] memory tiers = new Tier[](numTiers);
for (uint256 i = 1; i < numTiers + 1; i++) {
tiers[i - 1] = allTiers[i];
}
return tiers;
} | 0.8.4 |
// Before all token transfer | function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
// Store token last transfer timestamp by id
tokenLastTransferredAt[_tokenId] = block.timestamp;
// TODO: update tracker of from/to owned... | 0.8.4 |
/// @notice Check if the index has been marked as claimed.
/// @param index - the index to check
/// @return true if index has been marked as claimed. | function isClaimed(uint256 index) public view returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[week][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
... | 0.8.9 |
/// @notice Claim the given amount of the token to the given address.
/// Reverts if the inputs are invalid.
/// @param index - claimer index
/// @param account - claimer account
/// @param amount - claim amount
/// @param merkleProof - merkle proof for the claim
/// @param option - claiming option | function claim(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
Option option
) external nonReentrant {
require(!frozen, "Claiming is frozen.");
require(!isClaimed(index), "Drop already claimed.");
// Verify the merkle ... | 0.8.9 |
/// @notice Update the merkle root and increment the week.
/// @param _merkleRoot - the new root to push | function updateMerkleRoot(bytes32 _merkleRoot) public onlyAdmin {
require(frozen, "Contract not frozen.");
// Increment the week (simulates the clearing of the claimedBitMap)
week = week + 1;
// Set the new merkle root
merkleRoot = _merkleRoot;
emit MerkleRootUpdated(me... | 0.8.9 |
///@notice Transfer tokens between accounts
///@param from The benefactor/sender account.
///@param to The beneficiary account
///@param value The amount to be transfered | function transferFrom(address from, address to, uint value) returns (bool success){
require(
allowance[from][msg.sender] >= value
&&balances[from] >= value
&& value > 0
);
balances[from] = balances[from].sub(value);
... | 0.4.11 |
///@notice Transfer tokens to the beneficiary account
///@param to The beneficiary account
///@param value The amount of tokens to be transfered | function transfer(address to, uint value) returns (bool success){
require(
balances[msg.sender] >= value
&& value > 0
&& (!frozenAccount[msg.sender]) // Allow transfer only if account is not frozen
);
balances[msg.sender] = balances[m... | 0.4.11 |
///@notice Increase the number of coins
///@param target The address of the account where the coins would be added.
///@param mintedAmount The amount of coins to be added | function mintToken(address target, uint256 mintedAmount) onlyOwner {
balances[target] = balances[target].add(mintedAmount); //Add the amount of coins to be increased to the balance
currentSupply = currentSupply.add(mintedAmount); //Add the amount of coins to be increased to the supply
... | 0.4.11 |
/// Notice - Maximum length for _source will be 32 chars otherwise returned bytes32 value will have lossy value. | function bytesToBytes32(bytes _b, uint _offset) internal pure returns (bytes32) {
bytes32 result;
for (uint i = 0; i < _b.length; i++) {
result |= bytes32(_b[_offset + i] & 0xFF) >> (i * 8);
}
return result;
} | 0.4.24 |
/**
* @notice Changes the bytes32 into string
* @param _source that need to convert into string
*/ | function bytes32ToString(bytes32 _source) internal pure returns (string result) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(_source) * 2 ** (8 * j)));
if (char != 0) {
... | 0.4.24 |
/**
* @notice Gets function signature from _data
* @param _data Passed data
* @return bytes4 sig
*/ | function getSig(bytes _data) internal pure returns (bytes4 sig) {
uint len = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < len; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i))));
}
} | 0.4.24 |
/**
* @notice Validates permissions with PermissionManager if it exists. If there's no permission return false
* @dev Note that IModule withPerm will allow ST owner all permissions by default
* @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
* @param ... | function checkPermission(address[] storage _modules, address _delegate, address _module, bytes32 _perm) public view returns(bool) {
if (_modules.length == 0) {
return false;
}
for (uint8 i = 0; i < _modules.length; i++) {
if (IPermissionManager(_modules[i]).checkPe... | 0.4.24 |
/**
* @notice Queries a value at a defined checkpoint
* @param _checkpoints is array of Checkpoint objects
* @param _checkpointId is the Checkpoint ID to query
* @param _currentValue is the Current value of checkpoint
* @return uint256
*/ | function getValueAt(Checkpoint[] storage _checkpoints, uint256 _checkpointId, uint256 _currentValue) public view returns(uint256) {
//Checkpoint id 0 is when the token is first created - everyone has a zero balance
if (_checkpointId == 0) {
return 0;
}
if (_checkpoints.l... | 0.4.24 |
/**
* @notice Stores the changes to the checkpoint objects
* @param _checkpoints is the affected checkpoint object array
* @param _newValue is the new value that needs to be stored
*/ | function adjustCheckpoints(TokenLib.Checkpoint[] storage _checkpoints, uint256 _newValue, uint256 _currentCheckpointId) public {
//No checkpoints set yet
if (_currentCheckpointId == 0) {
return;
}
//No new checkpoints since last update
if ((_checkpoints.length >... | 0.4.24 |
/**
* @notice Keeps track of the number of non-zero token holders
* @param _investorData Date releated to investor metrics
* @param _from Sender of transfer
* @param _to Receiver of transfer
* @param _value Value of transfer
* @param _balanceTo Balance of the _to address
* @param _balanceFrom Balance of t... | function adjustInvestorCount(
InvestorDataStorage storage _investorData,
address _from,
address _to,
uint256 _value,
uint256 _balanceTo,
uint256 _balanceFrom
) public {
if ((_value == 0) || (_from == _to)) {
return;
}
... | 0.4.24 |
/**
* @notice Attachs a module to the SecurityToken
* @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it
* @dev to control restrictions on transfers.
* @param _moduleFactory is the address of the module factory to be added
* @param _data is data packed into bytes used ... | function addModule(
address _moduleFactory,
bytes _data,
uint256 _maxCost,
uint256 _budget
) external onlyOwner nonReentrant {
//Check that the module factory exists in the ModuleRegistry - will throw otherwise
IModuleRegistry(moduleRegistry).useModule(_moduleF... | 0.4.24 |
/**
* @notice Removes a module attached to the SecurityToken
* @param _module address of module to unarchive
*/ | function removeModule(address _module) external onlyOwner {
require(modulesToData[_module].isArchived, "Not archived");
require(modulesToData[_module].module != address(0), "Module missing");
/*solium-disable-next-line security/no-block-members*/
emit ModuleRemoved(modulesToData[_mod... | 0.4.24 |
/**
* @notice Internal - Removes a module attached to the SecurityToken by index
*/ | function _removeModuleWithIndex(uint8 _type, uint256 _index) internal {
uint256 length = modules[_type].length;
modules[_type][_index] = modules[_type][length - 1];
modules[_type].length = length - 1;
if ((length - 1) != _index) {
//Need to find index of _type in modul... | 0.4.24 |
/**
* @notice allows owner to increase/decrease POLY approval of one of the modules
* @param _module module address
* @param _change change in allowance
* @param _increase true if budget has to be increased, false if decrease
*/ | function changeModuleBudget(address _module, uint256 _change, bool _increase) external onlyOwner {
require(modulesToData[_module].module != address(0), "Module missing");
uint256 currentAllowance = IERC20(polyToken).allowance(address(this), _module);
uint256 newAllowance;
if (_increa... | 0.4.24 |
/**
* @notice returns an array of investors at a given checkpoint
* NB - this length may differ from investorCount as it contains all investors that ever held tokens
* @param _checkpointId Checkpoint id at which investor list is to be populated
* @return list of investors
*/ | function getInvestorsAt(uint256 _checkpointId) external view returns(address[]) {
uint256 count = 0;
uint256 i;
for (i = 0; i < investorData.investors.length; i++) {
if (balanceOfAt(investorData.investors[i], _checkpointId) > 0) {
count++;
}
... | 0.4.24 |
/**
* @notice generates subset of investors
* NB - can be used in batches if investor list is large
* @param _start Position of investor to start iteration from
* @param _end Position of investor to stop iteration at
* @return list of investors
*/ | function iterateInvestors(uint256 _start, uint256 _end) external view returns(address[]) {
require(_end <= investorData.investors.length, "Invalid end");
address[] memory investors = new address[](_end.sub(_start));
uint256 index = 0;
for (uint256 i = _start; i < _end; i++) {
... | 0.4.24 |
/**
* @notice Updates internal variables when performing a transfer
* @param _from sender of transfer
* @param _to receiver of transfer
* @param _value value of transfer
* @param _data data to indicate validation
* @return bool success
*/ | function _updateTransfer(address _from, address _to, uint256 _value, bytes _data) internal nonReentrant returns(bool) {
// NB - the ordering in this function implies the following:
// - investor counts are updated before transfer managers are called - i.e. transfer managers will see
//invest... | 0.4.24 |
/**
* @notice Validate transfer with TransferManager module if it exists
* @dev TransferManager module has a key of 2
* @dev _isTransfer boolean flag is the deciding factor for whether the
* state variables gets modified or not within the different modules. i.e isTransfer = true
* leads to change in the modul... | function _verifyTransfer(
address _from,
address _to,
uint256 _value,
bytes _data,
bool _isTransfer
) internal checkGranularity(_value) returns (bool) {
if (!transfersFrozen) {
bool isInvalid = false;
bool isValid = false;
... | 0.4.24 |
/**
* @notice mints new tokens and assigns them to the target _investor.
* @dev Can only be called by the issuer or STO attached to the token
* @param _investor Address where the minted tokens will be delivered
* @param _value Number of tokens be minted
* @param _data data to indicate validation
* @return s... | function mintWithData(
address _investor,
uint256 _value,
bytes _data
) public onlyModuleOrOwner(MINT_KEY) isMintingAllowed() returns (bool success) {
require(_investor != address(0), "Investor is 0");
require(_updateTransfer(address(0), _investor, _value, _data), "... | 0.4.24 |
/**
* @notice Mints new tokens and assigns them to the target _investor.
* @dev Can only be called by the issuer or STO attached to the token.
* @param _investors A list of addresses to whom the minted tokens will be dilivered
* @param _values A list of number of tokens get minted and transfer to corresponding ... | function mintMulti(address[] _investors, uint256[] _values) external returns (bool success) {
require(_investors.length == _values.length, "Incorrect inputs");
for (uint256 i = 0; i < _investors.length; i++) {
mint(_investors[i], _values[i]);
}
return true;
} | 0.4.24 |
/**
* @notice Validate permissions with PermissionManager if it exists, If no Permission return false
* @dev Note that IModule withPerm will allow ST owner all permissions anyway
* @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
* @param _delegate add... | function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) {
for (uint256 i = 0; i < modules[PERMISSION_KEY].length; i++) {
if (!modulesToData[modules[PERMISSION_KEY][i]].isArchived)
return TokenLib.checkPermission(modules[PERMISSION_KEY]... | 0.4.24 |
/**
* @notice Used by a controller to execute a forced transfer
* @param _from address from which to take tokens
* @param _to address where to send tokens
* @param _value amount of tokens to transfer
* @param _data data to indicate validation
* @param _log data attached to the transfer by controller to emit... | function forceTransfer(address _from, address _to, uint256 _value, bytes _data, bytes _log) public onlyController {
require(_to != address(0));
require(_value <= balances[_from]);
bool verified = _updateTransfer(_from, _to, _value, _data);
balances[_from] = balances[_from].sub(_value... | 0.4.24 |
/**
* @notice deploys the token and adds default modules like the GeneralTransferManager.
* Future versions of the proxy can attach different modules or pass different parameters.
*/ | function deployToken(
string _name,
string _symbol,
uint8 _decimals,
string _tokenDetails,
address _issuer,
bool _divisible,
address _polymathRegistry
) external returns (address) {
address newSecurityTokenAddress = new SecurityToken(
... | 0.4.24 |
/// @dev See {ILairControls.claimBloodBags} | function claimBloodBags(address sender, uint16 tokenId)
external
override
onlyControllers
returns (uint256 owed)
{
uint8 score = _predatorScoreForVampire(tokenId);
VampireStake memory stake = scoreStakingMap[score][
stakeIndices[tokenId]
];
... | 0.8.7 |
/// ==== Migration | function migrate(
uint16[] calldata vampires,
uint8[] calldata predatorIndices
) external nonReentrant {
require(
vampires.length == predatorIndices.length,
"ARRAYS_SHOULD_HAVE_SAME_SIZE"
);
uint16 tokenId;
uint8 predatorIndex;
for (ui... | 0.8.7 |
//Accrual of referral bonuses to the participant | function setRefererBonus(address addr, uint256 amount, uint256 level_percent, uint256 level_num) private {
if (addr.notZero()) {
uint256 revenue = amount.mul(level_percent).div(100);
if (!checkInvestor(addr)) {
createInvestor(addr, address(0));
}
investors[addr].referals_profit = investors[a... | 0.4.25 |
//Accrual of referral bonuses to participants | function setAllRefererBonus(address addr, uint256 amount) private {
address ref_addr_level_1 = investors[addr].referer;
address ref_addr_level_2 = investors[ref_addr_level_1].referer;
address ref_addr_level_3 = investors[ref_addr_level_2].referer;
setRefererBonus (ref_addr_level_1, amount, ref_bonus_lev... | 0.4.25 |
//Get the number of dividends | function calcDivedents (address addr) public view returns (uint256) {
uint256 current_perc = 0;
if (address(this).balance < 2000 ether) {
current_perc = dividends_perc_before_2000eth;
}
else {
current_perc = dividends_perc_after_2000eth;
}
return investors[addr].investment.mul(current_perc).... | 0.4.25 |
//Income payment | function withdraw_revenue(address addr) private {
uint256 withdraw_amount = calcDivedents(addr);
if (check_x2_profit(addr,withdraw_amount) == true) {
withdraw_amount = 0;
}
if (withdraw_amount > 0) {
investors[addr].investment_profit = investors[addr].investment_profit.add(withdraw_amou... | 0.4.25 |
//Checking the x2 profit | function check_x2_profit(address addr, uint256 dividends) private returns(bool) {
if (investors[addr].investment_profit.add(dividends) > investors[addr].investment.mul(2)) {
investors[addr].investment_profit_balance = investors[addr].investment.mul(2).sub(investors[addr].investment_profit);
investors[addr... | 0.4.25 |
//Investor account statistics | function getInvestorInfo(address addr) public view returns (address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
Investor memory investor_info = investors[addr];
return (investor_info.referer,
investor_info.investment,
investor_info.investment_time,
investo... | 0.4.25 |
/**
* @notice Given an amount of EToken, how much TokenA and TokenB have to be deposited, withdrawn for it
* initial issuance / last redemption: sqrt(amountA * amountB) -> such that the inverse := EToken amount ** 2
* subsequent issuances / non nullifying redemptions: claim on EToken supply * reserveA/B
*/ | function tokenATokenBForEToken(
IEPool.Tranche memory t,
uint256 amount,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal view returns (uint256 amountA, uint256 amountB) {
if (t.reserveA + t.reserveB == 0) {
uint256 amountsA = amount * sFactorA ... | 0.8.1 |
/**
* @dev See {IStaking-setStakingOptions}
*
* Requirements:
*
* - `stakeDurations` and `stakePercentageBasisPoints` arrays passed to
* this function cannot be empty or have a different length.
*/ | function setStakingOptions(
uint256[] memory stakeDurations,
uint16[] memory stakePercentageBasisPoints
) external override onlyOwner {
require(
stakeDurations.length == stakePercentageBasisPoints.length && stakeDurations.length > 0,
"Staking: stake duration and percentage basis points arrays ... | 0.7.0 |
/**
* @dev See {IStaking-getStakingOptions}
*/ | function getStakingOptions()
external
override
view
returns (
uint256[] memory stakeOptionIndexes,
uint256[] memory stakeDurations,
uint16[] memory stakePercentageBasisPoints
)
{
stakeOptionIndexes = new uint256[](_stakeOptions[_currentStakeOptionArrayIndex].length);
stak... | 0.7.0 |
/**
* @dev See {IStaking-getPersonalStakeIndexes}
*/ | function getPersonalStakeIndexes(
address user,
uint256 amountToRetrieve,
uint256 offset
) external override view returns (uint256[] memory) {
uint256[] memory indexes;
(indexes, , , , ) = getPersonalStakes(user, amountToRetrieve, offset);
return indexes;
} | 0.7.0 |
/**
* @dev See {IStaking-getPersonalStakeUnlockedTimestamps}
*/ | function getPersonalStakeUnlockedTimestamps(
address user,
uint256 amountToRetrieve,
uint256 offset
) external override view returns (uint256[] memory) {
uint256[] memory timestamps;
(, timestamps, , , ) = getPersonalStakes(user, amountToRetrieve, offset);
return timestamps;
} | 0.7.0 |
/**
* @dev See {IStaking-getPersonalStakeActualAmounts}
*/ | function getPersonalStakeActualAmounts(
address user,
uint256 amountToRetrieve,
uint256 offset
) external override view returns (uint256[] memory) {
uint256[] memory actualAmounts;
(, , actualAmounts, , ) = getPersonalStakes(user, amountToRetrieve, offset);
return actualAmounts;
} | 0.7.0 |
/**
* @dev See {IStaking-getPersonalStakeForAddresses}
*/ | function getPersonalStakeForAddresses(
address user,
uint256 amountToRetrieve,
uint256 offset
) external override view returns (address[] memory) {
address[] memory stakedFor;
(, , , stakedFor, ) = getPersonalStakes(user, amountToRetrieve, offset);
return stakedFor;
} | 0.7.0 |
/**
* @dev See {IStaking-getPersonalStakePercentageBasisPoints}
*/ | function getPersonalStakePercentageBasisPoints(
address user,
uint256 amountToRetrieve,
uint256 offset
) external override view returns (uint256[] memory) {
uint256[] memory stakePercentageBasisPoints;
(, , , , stakePercentageBasisPoints) = getPersonalStakes(user, amountToRetrieve, offset);
r... | 0.7.0 |
/**
* @dev Helper function to get specific properties of all of the personal stakes created by the `user`
* @param user address The address to query
* @return (uint256[], uint256[], address[], uint256[] memory)
* timestamps array, actualAmounts array, stakedFor array, stakePercentageBasisPoints array
*/ | function getPersonalStakes(
address user,
uint256 amountToRetrieve,
uint256 offset
)
public
view
returns (
uint256[] memory,
uint256[] memory,
uint256[] memory,
address[] memory,
uint256[] memory
)
{
StakeContract storage stakeContract = _stakeHolders[us... | 0.7.0 |
/**
* @dev Helper function to create stakes for a given address
* @param user address The address the stake is being created for
* @param amount uint256 The number of tokens being staked
* @param lockInDuration uint256 The duration to lock the tokens for
* @param data bytes optional data to include in the Stake ev... | function createStake(
address user,
uint256 amount,
uint256 lockInDuration,
uint16 stakePercentageBasisPoints,
bytes calldata data
) internal {
require(
_stakingToken.transferFrom(_msgSender(), address(this), amount),
"Staking: stake required"
);
if (!_stakeHolders[user].e... | 0.7.0 |
/**
* @dev Helper function to withdraw stakes for the msg.sender
* @param personalStakeIndex uint256 index of the stake to withdraw in the personalStakes mapping
* @param data bytes optional data to include in the Unstake event
*
* Requirements:
*
* - valid personal stake index is passed.
* - stake should not b... | function withdrawStake(uint256 personalStakeIndex, bytes calldata data) internal {
require(
personalStakeIndex <= _stakeHolders[_msgSender()].personalStakesLastIndex.sub(1),
"Staking: passed the wrong personal stake index"
);
Stake storage personalStake = _stakeHolders[_msgSender()].personalSta... | 0.7.0 |
/**
* @notice Given amountB, which amountA is required such that amountB / amountA is equal to the ratio
* amountA := amountBInTokenA * ratio
*/ | function tokenAForTokenB(
uint256 amountB,
uint256 ratio,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns(uint256) {
return (((amountB * sFactorI / sFactorB) * ratio) / rate) * sFactorA / sFactorI;
} | 0.8.1 |
/**
* @notice Given an amount of TokenA, how can it be split up proportionally into amountA and amountB
* according to the ratio
* amountA := total - (total / (1 + ratio)) == (total * ratio) / (1 + ratio)
* amountB := (total / (1 + ratio)) * rate
*/ | function tokenATokenBForTokenA(
uint256 _totalA,
uint256 ratio,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 amountA, uint256 amountB) {
amountA = _totalA - (_totalA * sFactorI / (sFactorI + ratio));
amountB = (((_totalA * ... | 0.8.1 |
/**
* @notice Create a crowdsale contract, a token and initialize them
* @param _ownerTokens Amount of tokens that will be mint to owner during the sale
*/ | function UP1KCrowdsale(uint256 _startTimestamp, uint256 _endTimestamp, uint256 _rate, uint256 _hardCap,
uint256 _ownerTokens, uint32 _buyFeeMilliPercent, uint32 _sellFeeMilliPercent, uint256 _minBuyAmount, uint256 _minSellAmount) public {
require(_startTimestamp < _endTimestamp);
require(_ra... | 0.4.18 |
/*
Airdrop function which take up a array of address and amount and call the
transfer function to send the token
*/ | function doAirDrop(address[] _address, uint256 _amount) onlyOwner public returns (bool) {
uint256 count = _address.length;
for (uint256 i = 0; i < count; i++)
{
/* calling transfer function from contract */
tokenInstance.transfer(_address [i],_amount);
}
} | 0.4.19 |
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/ | function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
msto... | 0.6.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.