comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* @dev add addresses to the whitelist, sender must have enough tokens
* @param _addresses addresses for adding to whitelist
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/ | function addAddressesToWhitelist(address[] _addresses) onlyOwnerOrCoOwner public returns (bool success) {
uint length = _addresses.length;
for (uint i = 0; i < length; i++) {
if (addAddressToWhitelist(_addresses[i])) {
success = true;
}
}
} | 0.4.23 |
/**
* @dev remove addresses from the whitelist
* @param _addresses addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/ | function removeAddressesFromWhitelist(address[] _addresses) onlyOwnerOrCoOwner public returns (bool success) {
uint length = _addresses.length;
for (uint i = 0; i < length; i++) {
if (removeAddressFromWhitelist(_addresses[i])) {
success = true;
}
}
... | 0.4.23 |
/**
* @notice Settle an auction, finalizing the bid and paying out to the owner.
* @dev If there are no bids, the Axon is burned.
*/ | function _settleAuction() internal {
IAxonsAuctionHouse.Auction memory _auction = auction;
require(_auction.startTime != 0, "Auction hasn't begun");
require(!_auction.settled, 'Auction has already been settled');
require(block.timestamp >= _auction.endTime, "Auction hasn't complete... | 0.8.10 |
/**
* @param _recipients list of repicients
* @param _amount list of no. tokens
*/ | function bonusToken(address[] _recipients, uint[] _amount) public onlyOwnerOrCoOwner onlyStopping {
uint len = _recipients.length;
uint len1 = _amount.length;
require(len == len1);
require(len <= MAX_TRANSFER);
uint i;
uint total = 0;
for (i = 0; i < len; i... | 0.4.23 |
/**
* Add an address to the whitelist
*
* @param _key Key type address to add to the whitelist
* @param _value Value type address to add to the whitelist under _key
*/ | function addPair(
address _key,
address _value
)
external
timeLockUpgrade
{
require(
whitelist[_key] == address(0),
"AddressToAddressWhiteList.addPair: Address pair already exists."
);
require(
_value != ad... | 0.5.7 |
/**
* Remove a address to address pair from the whitelist
*
* @param _key Key type address to remove to the whitelist
*/ | function removePair(
address _key
)
external
timeLockUpgrade
{
address valueToRemove = whitelist[_key];
require(
valueToRemove != address(0),
"AddressToAddressWhiteList.removePair: key type address is not current whitelisted."
)... | 0.5.7 |
/**
* Edit value type address associated with a key
*
* @param _key Key type address to add to the whitelist
* @param _value Value type address to add to the whitelist under _key
*/ | function editPair(
address _key,
address _value
)
external
timeLockUpgrade
{
require(
whitelist[_key] != address(0),
"AddressToAddressWhiteList.editPair: Address pair must exist."
);
require(
_value != addr... | 0.5.7 |
/**
* Return array of value type addresses based on passed in key type addresses
*
* @param _key Array of key type addresses to get value type addresses for
* @return address[] Array of value type addresses
*/ | function getValues(
address[] calldata _key
)
external
view
returns (address[] memory)
{
// Get length of passed array
uint256 arrayLength = _key.length;
// Instantiate value type addresses array
address[] memory values = new address[](... | 0.5.7 |
/**
* Return value type address associated with a passed key type address
*
* @param _key Address of key type
* @return address Address associated with _key
*/ | function getValue(
address _key
)
public
view
returns (address)
{
// Require key to have matching value type address
require(
whitelist[_key] != address(0),
"AddressToAddressWhiteList.getValue: No value for that address."
... | 0.5.7 |
/**
* Verifies an array of addresses against the whitelist
*
* @param _keys Array of key type addresses to check if value exists
* @return bool Whether all addresses in the list are whitelisted
*/ | function areValidAddresses(
address[] calldata _keys
)
external
view
returns (bool)
{
// Get length of passed array
uint256 arrayLength = _keys.length;
for (uint256 i = 0; i < arrayLength; i++) {
// Return false if key type address ... | 0.5.7 |
/**
* @dev calculate reward
*/ | function calculateReward(address _addr, uint256 _round) public view returns(uint256)
{
Player memory p = players[_addr];
Game memory g = games[_round];
if (g.endTime > now) return 0;
if (g.crystals == 0) return 0;
if (p.lastRound >= _round) return 0;
return Sa... | 0.4.25 |
/**
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/ | function approve(address _spender, uint256 _value) public returns (bool success) {
// The amount has to be bigger or equal to 0
require(_value >= 0);
allowances[msg.sender][_spender] = _value;
// Generate the public approval event and return success
emit Approval(msg.sender, _spender, _value);
ret... | 0.4.26 |
// Withdraw partial funds, normally used with a jar withdrawal | function withdraw(uint256 _amount) external {
require(msg.sender == controller, "!controller");
uint256 _balance = IERC20_1(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
... | 0.6.12 |
// Withdraw all funds, normally used when migrating strategies | function withdrawAll() external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
_withdrawAll();
balance = IERC20_1(want).balanceOf(address(this));
address _jar = IController(controller).jars(address(want));
require(_jar != address(0), "!jar"... | 0.6.12 |
// **** Emergency functions **** | function execute(address _target, bytes memory _data)
public
payable
returns (bytes memory response)
{
require(msg.sender == timelock, "!timelock");
require(_target != address(0), "!target");
// call contract in current context
assembly {
... | 0.6.12 |
// transfer tokens held by this contract in escrow to the recipient. Used when either claiming or cancelling gifts | function transferFromEscrow(address _recipient,uint256 _tokenId) internal{
require(super.ownerOf(_tokenId) == address(this),"The card must be owned by the contract for it to be in escrow");
super.clearApproval(this, _tokenId);
super.removeTokenFrom(this, _tokenId);
super.addTokenTo(_... | 0.4.24 |
//Allow addresses to buy token for another account | function buyRecipient(address recipient) public payable whenNotHalted {
if(msg.value == 0) throw;
if(!(preCrowdsaleOn()||crowdsaleOn())) throw;//only allows during presale/crowdsale
if(contributions[recipient].add(msg.value)>perAddressCap()) throw;//per address cap
uint256 tokens = m... | 0.4.8 |
//Return rate of token against ether. | function returnRate() public constant returns(uint256) {
if (block.number>=startBlock && block.number<=preEndBlock) return 8888; //Pre-crowdsale
if (block.number>=phase1StartBlock && block.number<=phase1EndBlock) return 8000; //Crowdsale phase1
if (block.number>phase1EndBlock && block.number<... | 0.4.8 |
/// @param _tulipId - Id of the tulip to auction.
/// @param _startingPrice - Starting price in wei.
/// @param _endingPrice - Ending price in wei.
/// @param _duration - Duration in seconds.
/// @param _seller - Seller address | function _createAuction(
uint256 _tulipId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
internal
{
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
u... | 0.4.18 |
/*
* @dev Cancel auction and return tulip to original owner.
* @param _tulipId - ID of the tulip on auction
*/ | function cancelAuction(uint256 _tulipId)
external
{
Auction storage auction = tokenIdToAuction[_tulipId];
require(auction.startedAt > 0);
// Only seller can call this function
address seller = auction.seller;
require(msg.sender == seller);
// Retur... | 0.4.18 |
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`).
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - ... | function transfer(address to, uint256 value) external override returns (bool) {
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[msg.sender];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[msg.sender] = balance -... | 0.8.7 |
/// @dev Moves `value` AnyswapV3ERC20 token from account (`from`) to account (`to`) using allowance mechanism.
/// `value` is then deducted from caller account's allowance, unless set to `type(uint256).max`.
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of calle... | function transferFrom(address from, address to, uint256 value) external override returns (bool) {
require(to != address(0) || to != address(this));
if (from != msg.sender) {
// _decreaseAllowance(from, msg.sender, value);
uint256 allowed = allowance[from][msg.sender];
... | 0.8.7 |
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event... | function transferAndCall(address to, uint value, bytes calldata data) external override returns (bool) {
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[msg.sender];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanc... | 0.8.7 |
//human 0.1 standard. Just an arbitrary versioning scheme.
//
//
//function name must match the contract name above | function GhostGold(
) {
balances[msg.sender] = 1000000; // Give the creator all initial tokens
totalSupply = 1000000; // Update total supply
name = "GhostGold"; // Set the name for display purposes
decimals = 0; ... | 0.4.19 |
/*
* creates a montage of the given token ids
*/ | function createMontage(
address creator,
string memory _name,
string memory _description,
bool _canBeUnpacked,
uint256[] memory _tokenIds
) external onlyOwner returns (uint256) {
// create the montage object
MontageData memory _montage = MontageData(cr... | 0.6.11 |
/**
* @dev Calculates a EIP712 domain separator.
* @param name The EIP712 domain name.
* @param version The EIP712 domain version.
* @param verifyingContract The EIP712 verifying contract.
* @return result EIP712 domain separator.
*/ | function hashDomainSeperator(
string memory name,
string memory version,
address verifyingContract
) internal view returns (bytes32 result) {
bytes32 typehash = EIP712DOMAIN_TYPEHASH;
// solhint-disable-next-line no-inline-assembly
assembly {
let nameHash... | 0.8.11 |
/**
* @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
* @param domainHash Hash of the domain domain separator data, computed with getDomainHash().
* @param hashStruct The EIP712 hash struct.
* @return result EIP712 hash applied to the given EIP712 Domain.
*/ | function hashMessage(bytes32 domainHash, bytes32 hashStruct) internal pure returns (bytes32 result) {
// solhint-disable-next-line no-inline-assembly
assembly {
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 h... | 0.8.11 |
/**
* @notice Get the full contents of the montage (i.e. name and tokeids) for a given token ID.
* @param tokenId the id of a previously minted montage
*/ | function getMontageInformation(uint256 tokenId)
public
view
onlyExistingTokens(tokenId)
returns (
address creator,
string memory name,
string memory description,
bool canBeUnpacked,
uint256[] memory tokenIds
)
... | 0.6.11 |
/**
* @dev Withdraw User Balance to user account, only Governance call it
*/ | function userWithdraw(address withdrawAddress, uint256 amount)
public
payable
onlyGovernance
{
require(
_totalAmount >= amount,
"User Balance should be more than withdraw amount."
);
// Send ETH From Contract to User Address
... | 0.7.0 |
/**
* @dev EmergencyWithdraw when need to update contract and then will restore it
*/ | function emergencyWithdraw() public payable onlyGovernance {
require(_totalAmount > 0, "Can't send over total ETH amount.");
uint256 amount = _totalAmount;
address governanceAddress = governance();
// Send ETH From Contract to Governance Address
(bool sent, ) = governanc... | 0.7.0 |
/**
* @notice Verify a signed approval permit and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param deadline The time at which this expires (unix time)
* @param v v of the signature
* @param r ... | function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual {
require(owner != address(0), "ERC2612/Invalid-address-0");
require(deadline >= block.timestamp, "ERC2612/Expire... | 0.8.11 |
/// @dev Tranfer tokens from one address to other
/// @param _from source address
/// @param _to dest address
/// @param _value tokens amount
/// @return transfer result | function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer checkFrozenAmount(_from, _value) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
... | 0.4.13 |
/// @dev Approve transfer
/// @param _spender holder address
/// @param _value tokens amount
/// @return result | function approve(address _spender, uint _value) returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethere... | 0.4.13 |
/// @dev Constructor
/// @param _token Pay Fair token address
/// @param _multisigWallet team wallet
/// @param _start token ICO start date | function PayFairTokenCrowdsale(address _token, address _multisigWallet, uint _start) {
require(_multisigWallet != 0);
require(_start != 0);
token = PayFairToken(_token);
multisigWallet = _multisigWallet;
startsAt = _start;
milestones.push(Milestone(startsAt, startsAt + 1 days, 20));
... | 0.4.13 |
/// @dev Get the current milestone or bail out if we are not in the milestone periods.
/// @return Milestone current bonus milestone | function getCurrentMilestone() private constant returns (Milestone) {
for (uint i = 0; i < milestones.length; i++) {
if (milestones[i].start <= now && milestones[i].end > now) {
return milestones[i];
}
}
} | 0.4.13 |
/// @dev Make an investment. Crowdsale must be running for one to invest.
/// @param receiver The Ethereum address who receives the tokens | function investInternal(address receiver) stopInEmergency private {
var state = getState();
require(state == State.Funding);
require(msg.value > 0);
// Add investment record
var weiAmount = msg.value;
investments.push(Investment(receiver, weiAmount, getCurrentMilestone().bonus + 100));
... | 0.4.13 |
/// @dev Finalize a succcesful crowdsale. | function finalizeCrowdsale() internal {
// Calculate divisor of the total token count
uint divisor;
for (uint i = 0; i < investments.length; i++)
divisor = safeAdd(divisor, safeMul(investments[i].weiValue, investments[i].weight));
uint localMultiplier = 10 ** 12;
// Get unit price
... | 0.4.13 |
/// @dev Crowdfund state machine management.
/// @return State current state | function getState() public constant returns (State) {
if (finalized)
return State.Finalized;
if (address(token) == 0 || address(multisigWallet) == 0)
return State.Preparing;
if (preIcoTokensDistributed < token.convertToDecimal(PRE_ICO_MAX_TOKENS))
return State.PreFunding;
if (... | 0.4.13 |
/**
* @dev Will deploy a balancer LBP. Can only be called by DAO.agent address
* @notice This function requires that the DAO.agent has approved this address for spending pool tokens (e.g. POP & USDC). It will revert if the DAO.agent has not approved this contract for spending those tokens. The PoolConfiguration.token... | function deployLBP() external {
require(msg.sender == dao.agent, "Only DAO can call this");
require(poolConfig.deployed != true, "The pool has already been deployed");
require(_hasTokensForPool(), "Manager does not have enough pool tokens");
poolConfig.deployed = true;
lbp = ILBP(
balancer.l... | 0.8.0 |
/**
* @notice The DAO.agent can call this function to shutdown and unwind the pool. The proceeds will be forwarded to the DAO.treasury
*/ | function withdrawFromPool() external {
require(poolConfig.deployed, "Pool has not been deployed yet");
require(msg.sender == dao.agent, "not today, buddy");
bytes32 poolId = lbp.getPoolId();
uint256[] memory minAmountsOut = new uint256[](poolConfig.tokens.length);
for (uint256 i; i < poolConfig.to... | 0.8.0 |
/**
* @dev check contribution amount and time
*/ | function isValidContribution() internal view returns(bool) {
uint256 currentUserContribution = safeAdd(msg.value, userTotalContributed[msg.sender]);
if(whiteList[msg.sender] && msg.value >= ETHER_MIN_CONTRIB) {
if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CO... | 0.4.21 |
/**
* @dev Check bnb contribution time, amount and hard cap overflow
*/ | function isValidBNBContribution() internal view returns(bool) {
if(token.limitedWallets(msg.sender)) {
return false;
}
if(!whiteList[msg.sender] && !privilegedList[msg.sender]) {
return false;
}
uint256 amount = bnbToken.allowance(msg.sender, addres... | 0.4.21 |
/**
* @dev Calc bonus amount by contribution time
*/ | function getBonus() internal constant returns (uint256, uint256) {
uint256 numerator = 0;
uint256 denominator = 100;
if(now < BONUS_WINDOW_1_END_TIME) {
numerator = 25;
} else if(now < BONUS_WINDOW_2_END_TIME) {
numerator = 15;
} else if(now < BON... | 0.4.21 |
/**
* @dev Process BNB token contribution
* Transfer all amount of tokens approved by sender. Calc bonuses and issue tokens to contributor.
*/ | function processBNBContribution() public whenNotPaused checkTime checkBNBContribution {
bool additionalBonusApplied = false;
uint256 bonusNum = 0;
uint256 bonusDenom = 100;
(bonusNum, bonusDenom) = getBonus();
uint256 amountBNB = bnbToken.allowance(msg.sender, address(this))... | 0.4.21 |
/**
* @dev Process ether contribution. Calc bonuses and issue tokens to contributor.
*/ | function processContribution(address contributor, uint256 amount) private checkTime checkContribution checkCap {
bool additionalBonusApplied = false;
uint256 bonusNum = 0;
uint256 bonusDenom = 100;
(bonusNum, bonusDenom) = getBonus();
uint256 tokenBonusAmount = 0;
... | 0.4.21 |
/**
* @dev Finalize crowdsale if we reached hard cap or current time > SALE_END_TIME
*/ | function finalizeCrowdsale() public onlyOwner {
if(
(totalEtherContributed >= safeSub(hardCap, 20 ether) && totalBNBContributed >= safeSub(BNB_HARD_CAP, 10000 ether)) ||
(now >= SALE_END_TIME && totalEtherContributed >= softCap)
) {
fund.onCrowdsaleEnd();
... | 0.4.21 |
/** @notice Deposit ERC20 tokens into the smart contract (remember to set allowance in the token contract first)
* @param token The address of the token to deposit
* @param amount The amount of tokens to deposit
*/ | function depositToken(address token, uint256 amount) public {
Token(token).transferFrom(msg.sender, address(this), amount); // Deposit ERC20
require(
checkERC20TransferSuccess(), // Check whether the ERC20 token transfer was successful
"ERC2... | 0.4.25 |
/** @notice User-submitted transfer with arbiters signature, which sends tokens to another addresses account in the smart contract
* @param token The token to transfer (ETH is address(address(0)))
* @param amount The amount of tokens to transfer
* @param nonce The nonce (t... | function multiSigTransfer(address token, uint256 amount, uint64 nonce, uint8 v, bytes32 r, bytes32 s, address receiving_address) public {
bytes32 hash = keccak256(abi.encodePacked( // Calculate the withdrawal/transfer hash from the parameters
"\x19Ethereum Signed Message:\n32... | 0.4.25 |
/** @notice Allows user to block funds for single-sig withdrawal after 24h waiting period
* (This period is necessary to ensure all trades backed by these funds will be settled.)
* @param token The address of the token to block (ETH is address(address(0)))
* @param amount The amount of the token to ... | function blockFundsForSingleSigWithdrawal(address token, uint256 amount) public {
if (balances[token][msg.sender] - blocked_for_single_sig_withdrawal[token][msg.sender] >= amount){ // Check if the user holds the required funds
blocked_for_single_sig_withdrawal[token][msg.sender] += amount; ... | 0.4.25 |
/** @notice Allows user to withdraw funds previously blocked after 24h
*/ | function initiateSingleSigWithdrawal(address token, uint256 amount) public {
if (
balances[token][msg.sender] >= amount // Check if the user holds the funds
&& blocked_for_single_sig_withdrawal[token][msg.sender] >= amount // Check if these fund... | 0.4.25 |
/*
* @notice Creates proposal for voting.
* @param _proposalText Text of the proposal.
* @param _resultsInBlock Number of block on which results will be counted.
*/ | function createVoting(
string calldata _proposalText,
uint _resultsInBlock
) onlyShareholder external returns (bool success){
require(
_resultsInBlock > block.number,
"Block for results should be later than current block"
);
votingCounterFo... | 0.5.11 |
/**
* @dev Performs a low level call, to the contract holding all the logic, changing state on this contract at the same time
*/ | function proxyCall() internal {
address impl = implementation();
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), impl, ptr, calldatasize(), 0, 0)
returndatacopy(ptr, 0, returndatasize())
... | 0.6.10 |
/** @notice Give the user the option to perform multiple on-chain cancellations of orders at once with arbiters multi-sig
* @param orderHashes Array of orderHashes of the orders to be canceled
* @param v Multi-sig v
* @param r Multi-sig r
* @param s Multi-sig s
*/ | function multiSigOrderBatchCancel(bytes32[] orderHashes, uint8 v, bytes32 r, bytes32 s) public {
if(
arbiters[ // Check if the signee is an arbiter
ecrecover( // Restore the signing address
... | 0.4.25 |
/** @notice revoke the delegation of an address
* @param delegate The delegated address
* @param v Multi-sig v
* @param r Multi-sig r
* @param s Multi-sig s
*/ | function revokeDelegation(address delegate, uint8 v, bytes32 r, bytes32 s) public {
bytes32 hash = keccak256(abi.encodePacked( // Restore the signed hash
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(
delegate,
msg.sende... | 0.4.25 |
/** @notice Allows the feeCollector to directly withdraw his funds (would allow a fee distribution contract to withdraw collected fees)
* @param token The token to withdraw
* @param amount The amount of tokens to withdraw
*/ | function feeWithdrawal(address token, uint256 amount) public {
if (
msg.sender == feeCollector // Check if the sender is the feeCollector
&& balances[token][feeCollector] >= amount // Check if feeCollector has the sufficient balance
)... | 0.4.25 |
/*
* @notice Vote for the proposal
* @param _proposalId Id (number) of the proposal
*/ | function voteFor(uint256 _proposalId) onlyShareholder external returns (bool success){
require(
resultsInBlock[_proposalId] > block.number,
"Voting already finished"
);
require(
!boolVotedFor[_proposalId][msg.sender] && !boolVotedAgainst[_proposalId]... | 0.5.11 |
// We have to check returndatasize after ERC20 tokens transfers, as some tokens are implemented badly (dont return a boolean) | function checkERC20TransferSuccess() pure private returns(bool){
uint256 success = 0;
assembly {
switch returndatasize // Check the number of bytes the token contract returned
case 0 { // Nothing returned, but contract did not throw ... | 0.4.25 |
/**
@notice This function is used to add single-sided protected liquidity to BancorV2 Pool
@dev This function stakes LPT Received so the
@param _fromTokenAddress The token used for investment (address(0x00) if ether)
@param _toBanConverterAddress The address of pool to add liquidity to
@param _toReserveToken... | function ZapInSingleSided(
address _fromTokenAddress,
address _toBanConverterAddress,
address _toReserveTokenAddress,
uint256 _amount,
uint256 _minPoolTokens,
address _allowanceTarget,
address _swapTarget,
bytes calldata swapData
)
ex... | 0.5.12 |
/**
@dev This function is used to calculate and transfer goodwill
@param _tokenContractAddress Token from which goodwill is deducted
@param valueToSend The total value being zapped in
@return The quantity of remaining tokens
*/ | function _transferGoodwill(
address _tokenContractAddress,
uint256 valueToSend
) internal returns (uint256) {
if (goodwill == 0) return valueToSend;
uint256 goodwillPortion = SafeMath.div(
SafeMath.mul(valueToSend, goodwill),
10000
);
... | 0.5.12 |
// Allows any user to withdraw his tokens.
// Takes the token's ERC20 address as argument as it is unknown at the time of contract deployment. | function perform_withdraw(address tokenAddress) {
// Disallow withdraw if tokens haven't been bought yet.
if (!bought_tokens) throw;
// Retrieve current token balance of contract.
ERC20 token = ERC20(tokenAddress);
uint256 contract_token_balance = token.balanceOf(address(this));
... | 0.4.17 |
/*
* @notice Vote against the proposal
* @param _proposalId Id (number) of the proposal
*/ | function voteAgainst(uint256 _proposalId) onlyShareholder external returns (bool success){
require(
resultsInBlock[_proposalId] > block.number,
"Voting finished"
);
require(
!boolVotedFor[_proposalId][msg.sender] && !boolVotedAgainst[_proposalId][msg... | 0.5.11 |
// Allows any user to get his eth refunded before the purchase is made or after approx. 20 days in case the devs refund the eth. | function refund_me() {
if (bought_tokens) {
// Only allow refunds when the tokens have been bought if the minimum refund block has been reached.
if (block.number < min_refund_block) throw;
}
// Store the user's balance prior to withdrawal in a temporary variable.
uint256 eth_to_w... | 0.4.17 |
// Buy the tokens. Sends ETH to the presale wallet and records the ETH amount held in the contract. | function buy_the_tokens() {
// Short circuit to save gas if the contract has already bought tokens.
if (bought_tokens) return;
// Throw if the contract balance is less than the minimum required amount
if (this.balance < min_required_amount) throw;
// Record that the contract has bou... | 0.4.17 |
/**
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
* generated by calculating keccak256 of a incremented counter.
* @param _paramsHash parameters hash
* @param _proposer address
* @param _organization address
*/ | function propose(uint256, bytes32 _paramsHash, address _proposer, address _organization)
external
returns(bytes32)
{
// solhint-disable-next-line not-rely-on-time
require(now > parameters[_paramsHash].activationTime, "not active yet");
//Check parameters existence.
... | 0.5.13 |
/**
* @dev executeBoosted try to execute a boosted or QuietEndingPeriod proposal if it is expired
* it rewards the msg.sender with P % of the proposal's upstakes upon a successful call to this function.
* P = t/150, where t is the number of seconds passed since the the proposal's timeout.
* P is capped by 10%.
... | function executeBoosted(bytes32 _proposalId) external returns(uint256 expirationCallBounty) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,
"proposal state in not Boosted nor QuietEndin... | 0.5.13 |
/* ============= Contract initialization
* dev: initializes token: set initial values for erc20 variables
* assigns all tokens ('totalSupply') to one address ('tokenOwner')
* @param _contractNumberInTheLedger Contract Id.
* @param _description Description of the project of organization (short text or just ... | function initToken(
uint _contractNumberInTheLedger,
string calldata _description,
string calldata _name,
string calldata _symbol,
uint _dividendsPeriod,
address _xEurContractAddress,
address _cryptonomicaVerificationContractAddress,
string calldat... | 0.5.11 |
/// @notice Compute the virtual liquidity from a position's parameters.
/// @param tickLower The lower tick of a position.
/// @param tickUpper The upper tick of a position.
/// @param liquidity The liquidity of a a position.
/// @dev vLiquidity = liquidity * validRange^2 / 1e6, where the validRange is the tick amount ... | function _getVLiquidityForNFT(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256 vLiquidity) {
// liquidity is roughly equals to sqrt(amountX*amountY)
require(liquidity >= 1e6, "LIQUIDITY TOO SMALL");
uint256 validRange = uint24(
... | 0.8.4 |
/*
* @dev initToken and issueTokens are separate functions because of
* 'Stack too deep' exception from compiler
* @param _tokenOwner Address that will get all new created tokens.
* @param _totalSupply Amount of tokens to create.
*/ | function issueTokens(
uint _totalSupply,
address _tokenOwner
) external returns (bool success){
require(
msg.sender == creator,
"Only creator can initialize token contract"
);
require(
totalSupply == 0,
"Contract a... | 0.5.11 |
// Enter the bar. Pay some 123bs. Earn some shares.
// Locks 123b and mints 123s | function enter(uint256 _amount) public {
// Gets the amount of 123b locked in the contract
uint256 total123b = bonus.balanceOf(address(this));
// Gets the amount of 123s in existence
uint256 totalShares = totalSupply();
// If no 123s exists, mint it 1:1 to the amount put in
... | 0.6.12 |
// Leave the bar. Claim back your 123b.
// Unlocks the staked + gained 123b and burns 123s | function leave(uint256 _share) public {
// Gets the amount of 123s in existence
uint256 totalShares = totalSupply();
// Calculates the amount of 123b the 123s is worth
uint256 what = _share.mul(bonus.balanceOf(address(this))).div(totalShares);
_burn(msg.sender, _share);
b... | 0.6.12 |
/// @notice withdraw a single position.
/// @param tokenId The related position id.
/// @param noReward true if donot collect reward | function withdraw(uint256 tokenId, bool noReward) external nonReentrant {
require(owners[tokenId] == msg.sender, "NOT OWNER OR NOT EXIST");
if (noReward) {
_updateGlobalStatus();
} else {
_collectReward(tokenId);
}
uint256 vLiquidity = tokenStatus[tokenId... | 0.8.4 |
// emergency withdraw without caring about pending earnings
// pending earnings will be lost / set to 0 if used emergency withdraw | function emergencyWithdraw(uint amountToWithdraw) public {
require(amountToWithdraw > 0, "Cannot withdraw 0 Tokens");
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
require(now.sub(depositTime[msg.sender]) > cliffTime, "You recently deposited!, please ... | 0.6.11 |
// function to allow admin to claim *other* ERC20 tokens sent to this contract (by mistake)
// Admin cannot transfer out deposit tokens from this smart contract
// Admin can transfer out reward tokens from this address once adminClaimableTime has reached | function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
require(_tokenAddr != trustedDepositTokenAddress, "Admin cannot transfer out Deposit Tokens from this contract!");
require((_tokenAddr != trustedRewardTokenAddress) || (now > adminClaimableTime)... | 0.6.11 |
/**
* @param _newAdmin Address of new admin
*/ | function addAdmin(address _newAdmin) public onlyAdmin returns (bool success){
require(
cryptonomicaVerification.keyCertificateValidUntil(_newAdmin) > now,
"New admin has to be verified on Cryptonomica.net"
);
// revokedOn returns uint256 (unix time), it's 0 if ve... | 0.5.11 |
// Deposit LP tokens to OneTwoThreeMasterChef for BONUS 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 pending =
user.amount.mul(pool.accBonusPerShare).div(1e12).sub... | 0.6.12 |
// Withdraw LP tokens from OneTwoThreeMasterChef. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending =
user.amount.mul(pool.accBon... | 0.6.12 |
/**
* @notice Get all view URIs for all nfts inside a given montage.
* @param _tokenId the id of a previously minted Montage NFT
* @return metadata the off-chain URIs to view the token metadata of each token in json format
*/ | function viewURIsInMontage(uint256 _tokenId)
public
override
view
onlyExistingTokens(_tokenId)
returns (string memory metadata)
{
uint256[] memory tokenIds = getTokenIds(_tokenId);
uint256 len = tokenIds.length;
// start JSON object
... | 0.6.11 |
/*
* unpacks the montage, transferring ownership of the individual nfts inside the montage to the montage owner before burning the montage nft
*/ | function unpackMontage(uint256 _tokenId) external override onlyTokenOwner(_tokenId) {
require(canBeUnpacked(_tokenId), "unpackMontage: cannot unpack this montage");
uint256[] memory tokenIds = getTokenIds(_tokenId);
uint256 len = tokenIds.length;
// transfer ownership of nfts from ... | 0.6.11 |
/**
* @notice Mint single token
* @param beneficiary This address will receive the token
* @param mintCode Can be anything, but it affects the token code, which will also affect image id
*/ | function mint(address beneficiary, bytes32 mintCode) external payable {
require(block.timestamp >= mintStart, "mint not started");
require(block.timestamp <= mintEnd, "mint finished");
require(msg.value == mintFee, "wrong mint fee");
require(totalSupply() < mintLimit, "mint limit exceed"... | 0.8.10 |
/**
* @notice Mint a new Voucher of the specified type.
* @param term_ Release term:
* One-time release type: fixed at 0;
* Linear and Staged release type: duration in seconds from start to end of release.
* @param amount_ Amount of assets (ERC20) to be locked up
* @param maturities_ Tim... | function mint(
uint64 term_, /*seconds*/
uint256 amount_,
uint64[] calldata maturities_,
uint32[] calldata percentages_,
string memory originalInvestor_
) external virtual override returns (uint256, uint256) {
(uint256 slot, uint256 tokenId) = _mint(
msg.s... | 0.7.6 |
/**
* @notice Mint multiple tokens
* @param beneficiaries List of addresses which will receive tokens
* @param mintCodes List of mint codes (also see mint() function)
*/ | function bulkMint(address[] calldata beneficiaries, bytes32[] calldata mintCodes) external payable {
require(block.timestamp >= mintStart, "mint not started");
require(block.timestamp <= mintEnd, "mint finished");
uint256 count = beneficiaries.length;
require(mintCodes.length == count, "... | 0.8.10 |
// function GetTreeByUserId(uint32 UserId, bool report) view public returns (User[]){
// //Get Position
// uint32 userposition = uint32(userlistbyid[uint32(UserId)].Position);
// //Try to return all data base on position
// uint userCount = 0;
// if(report){
// userCount = uint((2 ** (uint(c... | function CheckInvestmentExpiry() public onlyOwner{
require(!isContractAlive(), "Contract is alive.");
require(PayoutAmount == 0, "Contract balance is already calculated.");
if(MainterPayoutAmount != 0){
PayoutMaintainer();
}
//Current Date - ... | 0.4.26 |
/**
* @notice Calculates image id
* @param id Token id
*/ | function imageId(uint256 id) public view returns (bytes32) {
if (imageSalt == bytes32(0)) {
// Images are not revealed yet
return bytes32(0);
}
bytes32 tokenCode = tokenCodes[id];
if (tokenCode == bytes32(0)) return bytes32(0); // Non-existing token
return... | 0.8.10 |
/**
* Constructor function
*
* Initializes contract
*/ | function Opacity() public payable {
director = msg.sender;
name = "Opacity";
symbol = "OPQ";
decimals = 18;
directorLock = false;
funds = 0;
totalSupply = 130000000 * 10 ** uint256(decimals);
// Assign reserved OPQ supply to the director
balances[director] = totalSupply;
... | 0.4.25 |
/**
* Director can alter the storage-peg and broker fees
*/ | function amendClaim(uint8 claimAmountSet, uint8 payAmountSet, uint8 feeAmountSet, uint8 accuracy) public onlyDirector returns (bool success) {
require(claimAmountSet == (payAmountSet + feeAmountSet));
require(payAmountSet < claimAmountSet);
require(feeAmountSet < claimAmountSet);
require(claimAmount... | 0.4.25 |
/**
* Bury an address
*
* When an address is buried; only claimAmount can be withdrawn once per epoch
*/ | function bury() public returns (bool success) {
// The address must be previously unburied
require(!buried[msg.sender]);
// An address must have at least claimAmount to be buried
require(balances[msg.sender] >= claimAmount);
// Prevent addresses with large balances from getting buried
... | 0.4.25 |
/// @dev Return the entitied LP token balance for the given shares.
/// @param share The number of shares to be converted to LP balance. | function shareToBalance(uint256 share) public view returns (uint256) {
if (totalShare == 0) return share; // When there's no share, 1 share = 1 balance.
uint256 totalBalance = staking.balanceOf(address(this));
return share.mul(totalBalance).div(totalShare);
} | 0.5.16 |
/// @dev Return the number of shares to receive if staking the given LP tokens.
/// @param balance the number of LP tokens to be converted to shares. | function balanceToShare(uint256 balance) public view returns (uint256) {
if (totalShare == 0) return balance; // When there's no share, 1 share = 1 balance.
uint256 totalBalance = staking.balanceOf(address(this));
return balance.mul(totalShare).div(totalBalance);
} | 0.5.16 |
/// @dev Re-invest whatever this worker has earned back to staked LP tokens. | function reinvest() public onlyEOA nonReentrant {
// 1. Withdraw all the rewards.
staking.getReward();
uint256 reward = uni.myBalance();
if (reward == 0) return;
// 2. Send the reward bounty to the caller.
uint256 bounty = reward.mul(reinvestBountyBps) / 10000;
... | 0.5.16 |
/// @dev Work on the given position. Must be called by the operator.
/// @param id The position ID to work on.
/// @param user The original user that is interacting with the operator.
/// @param debt The amount of user debt to help the strategy make decisions.
/// @param data The encoded data, consisting of strategy ad... | function work(uint256 id, address user, uint256 debt, bytes calldata data)
external payable
onlyOperator nonReentrant
{
// 1. Convert this position back to LP tokens.
_removeShare(id);
// 2. Perform the worker strategy; sending LP tokens + ETH; expecting LP tokens + ETH... | 0.5.16 |
/// @dev Return maximum output given the input amount and the status of Uniswap reserves.
/// @param aIn The amount of asset to market sell.
/// @param rIn the amount of asset in reserve for input.
/// @param rOut The amount of asset in reserve for output. | function getMktSellAmount(uint256 aIn, uint256 rIn, uint256 rOut) public pure returns (uint256) {
if (aIn == 0) return 0;
require(rIn > 0 && rOut > 0, "bad reserve values");
uint256 aInWithFee = aIn.mul(997);
uint256 numerator = aInWithFee.mul(rOut);
uint256 denominator = rI... | 0.5.16 |
/// @dev Return the amount of ETH to receive if we are to liquidate the given position.
/// @param id The position ID to perform health check. | function health(uint256 id) external view returns (uint256) {
// 1. Get the position's LP balance and LP total supply.
uint256 lpBalance = shareToBalance(shares[id]);
uint256 lpSupply = lpToken.totalSupply(); // Ignore pending mintFee as it is insignificant
// 2. Get the pool's total... | 0.5.16 |
/// @dev Liquidate the given position by converting it to ETH and return back to caller.
/// @param id The position ID to perform liquidation | function liquidate(uint256 id) external onlyOperator nonReentrant {
// 1. Convert the position back to LP tokens and use liquidate strategy.
_removeShare(id);
lpToken.transfer(address(liqStrat), lpToken.balanceOf(address(this)));
liqStrat.execute(address(0), 0, abi.encode(fToken, 0))... | 0.5.16 |
// Deposit LP tokens to ScienTist for BIO 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 pending = user.amount.mul(pool.accBioPerShare).div(1e12).sub(user.rewardD... | 0.6.12 |
// Withdraw LP tokens from ScienTist. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accBioPerShar... | 0.6.12 |
/**
* @dev Initializes the TWAP cumulative values for the burn curve.
*/ | function initializeTwap() external onlyInitialDistributionAddress {
require(blockTimestampLast == 0, "twap already initialized");
(uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
uint256 ... | 0.6.6 |
/**
* @dev Claim an NFTs.
* @notice Claim a `_wearableId` NFT.
* @param _erc721Collection - collection address
* @param _wearableId - wearable id
*/ | function claimNFT(ERC721Collection _erc721Collection, string calldata _wearableId) external payable {
require(_erc721Collection.balanceOf(msg.sender) < maxSenderBalance, "The sender has already reached maxSenderBalance");
require(
canMint(_erc721Collection, _wearableId, 1),
"... | 0.5.11 |
/**
* @dev Remove owners from the list
* @param _address Address of owner to remove
*/ | function removeOwner(address _address) signed public returns (bool) {
uint NOT_FOUND = 1e10;
uint index = NOT_FOUND;
for (uint i = 0; i < owners.length; i++) {
if (owners[i] == _address) {
index = i;
break;
}
}
if (index == NOT_FOUND) {
return false;
... | 0.4.18 |
/**
* @notice Put a message in the L2 inbox that can be reexecuted for some fixed amount of time if it reverts
* @dev Advanced usage only (does not rewrite aliases for excessFeeRefundAddress and callValueRefundAddress). createRetryableTicket method is the recommended standard.
* @param destAddr destination L2 contra... | function createRetryableTicketNoRefundAliasRewrite(
address destAddr,
uint256 l2CallValue,
uint256 maxSubmissionCost,
address excessFeeRefundAddress,
address callValueRefundAddress,
uint256 maxGas,
uint256 gasPriceBid,
bytes calldata data
) public paya... | 0.6.11 |
/**
* @notice Executes a messages in an Outbox entry.
* @dev Reverts if dispute period hasn't expired, since the outbox entry
* is only created once the rollup confirms the respective assertion.
* @param batchNum Index of OutboxEntry in outboxEntries array
* @param proof Merkle proof of message inclusion in outbox... | function executeTransaction(
uint256 batchNum,
bytes32[] calldata proof,
uint256 index,
address l2Sender,
address destAddr,
uint256 l2Block,
uint256 l1Block,
uint256 l2Timestamp,
uint256 amount,
bytes calldata calldataForL1
) external v... | 0.6.11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.