comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
/**
* @notice Returns the target ratio if reserveA and reserveB are 0 (for initial deposit)
* currentRatio := (reserveA denominated in tokenB / reserveB denominated in tokenB) with decI decimals
*/
|
function currentRatio(
IEPool.Tranche memory t,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns(uint256) {
if (t.reserveA == 0 || t.reserveB == 0) {
if (t.reserveA == 0 && t.reserveB == 0) return t.targetRatio;
if (t.reserveA == 0) return 0;
if (t.reserveB == 0) return type(uint256).max;
}
return ((t.reserveA * rate / sFactorA) * sFactorI) / (t.reserveB * sFactorI / sFactorB);
}
|
0.8.1
|
/**
* @notice Returns the deviation of reserveA and reserveB from target ratio
* currentRatio > targetRatio: release TokenA liquidity and add TokenB liquidity
* currentRatio < targetRatio: add TokenA liquidity and release TokenB liquidity
* deltaA := abs(t.reserveA, (t.reserveB / rate * t.targetRatio)) / (1 + t.targetRatio)
* deltaB := deltaA * rate
*/
|
function trancheDelta(
IEPool.Tranche memory t,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange) {
rChange = (currentRatio(t, rate, sFactorA, sFactorB) < t.targetRatio) ? 1 : 0;
deltaA = (
Math.abs(t.reserveA, tokenAForTokenB(t.reserveB, t.targetRatio, rate, sFactorA, sFactorB)) * sFactorA
) / (sFactorA + (t.targetRatio * sFactorA / sFactorI));
// (convert to TokenB precision first to avoid altering deltaA)
deltaB = ((deltaA * sFactorB / sFactorA) * rate) / sFactorI;
// round to 0 in case of rounding errors
if (deltaA == 0 || deltaB == 0) (deltaA, deltaB, rChange) = (0, 0, 0);
}
|
0.8.1
|
/**
* @notice Returns the sum of the tranches reserve deltas
*/
|
function delta(
IEPool.Tranche[] memory ts,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv) {
uint256 totalReserveA;
int256 totalDeltaA;
int256 totalDeltaB;
for (uint256 i = 0; i < ts.length; i++) {
totalReserveA += ts[i].reserveA;
(uint256 _deltaA, uint256 _deltaB, uint256 _rChange) = trancheDelta(
ts[i], rate, sFactorA, sFactorB
);
(totalDeltaA, totalDeltaB) = (_rChange == 0)
? (totalDeltaA - int256(_deltaA), totalDeltaB + int256(_deltaB))
: (totalDeltaA + int256(_deltaA), totalDeltaB - int256(_deltaB));
}
if (totalDeltaA > 0 && totalDeltaB < 0) {
(deltaA, deltaB, rChange) = (uint256(totalDeltaA), uint256(-totalDeltaB), 1);
} else if (totalDeltaA < 0 && totalDeltaB > 0) {
(deltaA, deltaB, rChange) = (uint256(-totalDeltaA), uint256(totalDeltaB), 0);
}
rDiv = (totalReserveA == 0) ? 0 : deltaA * EPoolLibrary.sFactorI / totalReserveA;
}
|
0.8.1
|
/**
* @dev Set geneSequences of assets available
* @dev Used as 1 of 1s or 1 of Ns (N being same geneSequence repeated N times)
*/
|
function setAssets(uint16[] memory _assets) public onlyOwner {
uint256 maxSupply = lobsterBeachClub.maxSupply();
require(_assets.length <= maxSupply, "You cannot supply more assets than max supply");
for (uint i; i < _assets.length; i++) {
require(_assets[i] > 0 && _assets[i] < 1000, "Asset id must be between 1 and 999");
}
assets = _assets;
}
|
0.8.7
|
/**
* @notice how much EToken can be issued, redeemed for amountA and amountB
* initial issuance / last redemption: sqrt(amountA * amountB)
* subsequent issuances / non nullifying redemptions: claim on reserve * EToken total supply
*/
|
function eTokenForTokenATokenB(
IEPool.Tranche memory t,
uint256 amountA,
uint256 amountB,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal view returns (uint256) {
uint256 amountsA = totalA(amountA, amountB, rate, sFactorA, sFactorB);
if (t.reserveA + t.reserveB == 0) {
return (Math.sqrt((amountsA * t.sFactorE / sFactorA) * t.sFactorE));
}
uint256 reservesA = totalA(t.reserveA, t.reserveB, rate, sFactorA, sFactorB);
uint256 share = ((amountsA * t.sFactorE / sFactorA) * t.sFactorE) / (reservesA * t.sFactorE / sFactorA);
return share * t.eToken.totalSupply() / t.sFactorE;
}
|
0.8.1
|
/**
* Utility internal function used to safely transfer `value` tokens `from` -> `to`. Throws if transfer is impossible.
* @param from - account to make the transfer from
* @param to - account to transfer `value` tokens to
* @param value - tokens to transfer to account `to`
*/
|
function internalTransfer (address from, address to, uint value) internal {
require(to != address(0x0)); // Prevent people from accidentally burning their tokens
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
|
0.7.0
|
/**
* Utility internal function used to safely transfer `value1` tokens `from` -> `to1`, and `value2` tokens
* `from` -> `to2`, minimizing gas usage (calling `internalTransfer` twice is more expensive). Throws if
* transfers are impossible.
* @param from - account to make the transfer from
* @param to1 - account to transfer `value1` tokens to
* @param value1 - tokens to transfer to account `to1`
* @param to2 - account to transfer `value2` tokens to
* @param value2 - tokens to transfer to account `to2`
*/
|
function internalDoubleTransfer (address from, address to1, uint value1, address to2, uint value2) internal {
require(to1 != address(0x0) && to2 != address(0x0)); // Prevent people from accidentally burning their tokens
balanceOf[from] = balanceOf[from].sub(value1.add(value2));
balanceOf[to1] = balanceOf[to1].add(value1);
emit Transfer(from, to1, value1);
if (value2 > 0) {
balanceOf[to2] = balanceOf[to2].add(value2);
emit Transfer(from, to2, value2);
}
}
|
0.7.0
|
/**
* Utility costly function to encode bytes HEX representation as string.
* @param sig - signature as bytes32 to represent as string
*/
|
function hexToString (bytes32 sig) internal pure returns (bytes memory) {
bytes memory str = new bytes(64);
for (uint8 i = 0; i < 32; ++i) {
str[2 * i] = byte((uint8(sig[i]) / 16 < 10 ? 48 : 87) + uint8(sig[i]) / 16);
str[2 * i + 1] = byte((uint8(sig[i]) % 16 < 10 ? 48 : 87) + (uint8(sig[i]) % 16));
}
return str;
}
|
0.7.0
|
/**
* This function distincts transaction signer from transaction executor. It allows anyone to transfer tokens
* from the `from` account by providing a valid signature, which can only be obtained from the `from` account
* owner.
* Note that passed parameter sigId is unique and cannot be passed twice (prevents replay attacks). When there's
* a need to make signature once again (because the first one is lost or whatever), user should sign the message
* with the same sigId, thus ensuring that the previous signature can't be used if the new one passes.
* Use case: the user wants to send some tokens to another user or smart contract, but don't have Ether to do so.
* @param from - the account giving its signature to transfer `value` tokens to `to` address
* @param to - the account receiving `value` tokens
* @param value - the value in tokens to transfer
* @param fee - a fee to pay to `feeRecipient`
* @param feeRecipient - account which will receive fee
* @param deadline - until when the signature is valid
* @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use
*/
|
function transferViaSignature (
address from,
address to,
uint256 value,
uint256 fee,
address feeRecipient,
uint256 deadline,
uint256 sigId,
bytes calldata sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(abi.encodePacked(address(this), from, to, value, fee, feeRecipient, deadline, sigId)),
from, deadline, sigId, sig, sigStd, sigDestination.transfer
);
internalDoubleTransfer(from, to, value, feeRecipient, fee);
return true;
}
|
0.7.0
|
/**
* Same as `transferViaSignature`, but for `approve`.
* Use case: the user wants to set an allowance for the smart contract or another user without having Ether on
* their balance.
* @param from - the account to approve withdrawal from, which signed all below parameters
* @param spender - the account allowed to withdraw tokens from `from` address
* @param value - the value in tokens to approve to withdraw
* @param fee - a fee to pay to `feeRecipient`
* @param feeRecipient - account which will receive fee
* @param deadline - until when the signature is valid
* @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use
*/
|
function approveViaSignature (
address from,
address spender,
uint256 value,
uint256 fee,
address feeRecipient,
uint256 deadline,
uint256 sigId,
bytes calldata sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(abi.encodePacked(address(this), from, spender, value, fee, feeRecipient, deadline, sigId)),
from, deadline, sigId, sig, sigStd, sigDestination.approve
);
allowance[from][spender] = value;
emit Approval(from, spender, value);
internalTransfer(from, feeRecipient, fee);
return true;
}
|
0.7.0
|
/**
* Same as `transferViaSignature`, but for `transferFrom`.
* Use case: the user wants to withdraw tokens from a smart contract or another user who allowed the user to
* do so. Important note: the fee is subtracted from the `value`, and `to` address receives `value - fee`.
* @param signer - the address allowed to call transferFrom, which signed all below parameters
* @param from - the account to make withdrawal from
* @param to - the address of the recipient
* @param value - the value in tokens to withdraw
* @param fee - a fee to pay to `feeRecipient`
* @param feeRecipient - account which will receive fee
* @param deadline - until when the signature is valid
* @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use
*/
|
function transferFromViaSignature (
address signer,
address from,
address to,
uint256 value,
uint256 fee,
address feeRecipient,
uint256 deadline,
uint256 sigId,
bytes calldata sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(abi.encodePacked(address(this), from, to, value, fee, feeRecipient, deadline, sigId)),
signer, deadline, sigId, sig, sigStd, sigDestination.transferFrom
);
allowance[from][signer] = allowance[from][signer].sub(value);
internalDoubleTransfer(from, to, value.sub(fee), feeRecipient, fee);
return true;
}
|
0.7.0
|
/**
* Same as `approveViaSignature`, but for `approveAndCall`.
* Use case: the user wants to send tokens to the smart contract and pass additional data within one transaction.
* @param fromAddress - the account to approve withdrawal from, which signed all below parameters
* @param spender - the account allowed to withdraw tokens from `from` address (in this case, smart contract only)
* @param value - the value in tokens to approve to withdraw
* @param extraData - additional data to pass to the `spender` smart contract
* @param fee - a fee to pay to `feeRecipient`
* @param feeRecipient - account which will receive fee
* @param deadline - until when the signature is valid
* @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice
* @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters
* @param sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use
*/
|
function approveAndCallViaSignature (
address fromAddress,
address spender,
uint256 value,
bytes calldata extraData,
uint256 fee,
address feeRecipient,
uint256 deadline,
uint256 sigId,
bytes calldata sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(abi.encodePacked(address(this), fromAddress, spender, value, extraData, fee, feeRecipient, deadline, sigId)), fromAddress, deadline, sigId, sig, sigStd, sigDestination.approveAndCall);
allowance[fromAddress][spender] = value;
emit Approval(fromAddress, spender, value);
tokenRecipient(spender).receiveApproval(fromAddress, value, address(this), extraData);
internalTransfer(fromAddress, feeRecipient, fee);
return true;
}
|
0.7.0
|
/**
* @dev Deterministically decides which tokenIds of maxSupply from lobsterBeachClub will receive each asset
* @dev Determination is based on seedNumber
* @dev To prevent from tokenHolders knowing which section of tokenIds are more likely to receive an asset
* the direction which assets are chosen from 0 or maxSupply is also deterministic on the seedNumber
*/
|
function getAssetOwned(uint256 tokenId) public view returns (uint16 assetId) {
uint256 maxSupply = lobsterBeachClub.maxSupply();
uint256 seedNumber = lobsterBeachClub.seedNumber();
uint256 totalDistance = maxSupply;
uint256 direction = seedNumber % 2;
for (uint i; i < assets.length; i++) {
uint256 difference = totalDistance / (assets.length - i);
uint256 assetSeed = uint256(keccak256(abi.encode(seedNumber, i)));
uint256 distance = (assetSeed % difference) + 1;
totalDistance -= distance;
if ((direction == 0 && totalDistance == tokenId) || (direction == 1 && (maxSupply - totalDistance - 1 == tokenId))) {
return assets[i];
}
}
return 0;
}
|
0.8.7
|
/**
* @notice Given amountA, which amountB is required such that amountB / amountA is equal to the ratio
* amountB := amountAInTokenB / ratio
*/
|
function tokenBForTokenA(
uint256 amountA,
uint256 ratio,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns(uint256) {
return (((amountA * sFactorI / sFactorA) * rate) / ratio) * sFactorB / sFactorI;
}
|
0.8.1
|
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
|
function PSIToken() public {
totalSupply = INITIAL_SUPPLY;
//Round A Investors 15%
balances[0xa801fcD3CDf65206F567645A3E8c4537739334A2] = 150000000 * (10 ** uint256(decimals));
emit Transfer(msg.sender, 0xa801fcD3CDf65206F567645A3E8c4537739334A2, 150000000 * (10 ** uint256(decimals)));
//Presales Mining 35%
balances[0xE95aaFA9286337c89746c97fFBD084aD90AFF8Df] = 350000000 * (10 ** uint256(decimals));
emit Transfer(msg.sender,0xE95aaFA9286337c89746c97fFBD084aD90AFF8Df, 350000000 * (10 ** uint256(decimals)));
//Community 10%
balances[0xDCe73461af69C315B87dbb015F3e1341294d72c7] = 100000000 * (10 ** uint256(decimals));
emit Transfer(msg.sender, 0xDCe73461af69C315B87dbb015F3e1341294d72c7, 100000000 * (10 ** uint256(decimals)));
//Platform Sales 23%
balances[0x0d5A4EBbC1599006fdd7999F0e1537b3e60f0dc0] = 230000000 * (10 ** uint256(decimals));
emit Transfer(msg.sender, 0x0d5A4EBbC1599006fdd7999F0e1537b3e60f0dc0, 230000000 * (10 ** uint256(decimals)));
//Core Teams 12%
balances[0x63de19f0028F8402264052D9163AC66ca0c8A26c] = 120000000 * (10 ** uint256(decimals));
emit Transfer(msg.sender,0x63de19f0028F8402264052D9163AC66ca0c8A26c, 120000000 * (10 ** uint256(decimals)));
//Expense 3%
balances[0x403121629cfa4fC39aAc8Bf331AD627B31AbCa29] = 30000000 * (10 ** uint256(decimals));
emit Transfer(msg.sender, 0x403121629cfa4fC39aAc8Bf331AD627B31AbCa29, 30000000 * (10 ** uint256(decimals)));
//Bounty 2%
balances[0xBD1acB661e8211EE462114d85182560F30BE7A94] = 20000000 * (10 ** uint256(decimals));
emit Transfer(msg.sender, 0xBD1acB661e8211EE462114d85182560F30BE7A94, 20000000 * (10 ** uint256(decimals)));
}
|
0.4.25
|
/**
* @notice Return the total value of amountA and amountB denominated in TokenA
* totalA := amountA + (amountB / rate)
*/
|
function totalA(
uint256 amountA,
uint256 amountB,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 _totalA) {
return amountA + ((((amountB * sFactorI / sFactorB) * sFactorI) / rate) * sFactorA) / sFactorI;
}
|
0.8.1
|
/**
* @notice Return the total value of amountA and amountB denominated in TokenB
* totalB := amountB + (amountA * rate)
*/
|
function totalB(
uint256 amountA,
uint256 amountB,
uint256 rate,
uint256 sFactorA,
uint256 sFactorB
) internal pure returns (uint256 _totalB) {
return amountB + ((amountA * rate / sFactorA) * sFactorB) / sFactorI;
}
|
0.8.1
|
/**
* @notice Return the withdrawal fee for a given amount of TokenA and TokenB
* feeA := amountA * feeRate
* feeB := amountB * feeRate
*/
|
function feeAFeeBForTokenATokenB(
uint256 amountA,
uint256 amountB,
uint256 feeRate
) internal pure returns (uint256 feeA, uint256 feeB) {
feeA = amountA * feeRate / EPoolLibrary.sFactorI;
feeB = amountB * feeRate / EPoolLibrary.sFactorI;
}
|
0.8.1
|
/**
* @param oToken opyn put option
* @param _oTokenPayment USDC required for purchasing oTokens
* @param _maxPayment in ETH for purchasing USDC; caps slippage
* @param _0xFee 0x protocol fee. Any extra is refunded
* @param _0xSwapData 0x swap encoded data
*/
|
function _mint(
address oToken,
uint _opeth,
uint _oTokenPayment,
uint _maxPayment,
uint _0xFee,
bytes calldata _0xSwapData
) internal {
// Swap ETH for USDC (for purchasing oToken)
Uni(uni).swapETHForExactTokens{value: _maxPayment}(
_oTokenPayment,
path,
address(this),
now
);
// Purchase oToken
(bool success,) = exchange.call{value: _0xFee}(_0xSwapData);
require(success, "SWAP_CALL_FAILED");
opeth.mintFor(msg.sender, oToken, _opeth);
// refund dust eth, if any
safeTransferETH(msg.sender, address(this).balance);
}
|
0.6.12
|
/**
* @dev Claims/mints an NFT token if the sender is eligible to claim via the merkle proof.
*/
|
function claim(bytes32[] memory proof) external {
require(_root != 0, 'merkle root not set');
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(verify(proof, _root, leaf), 'sender not eligible to claim');
require(!_claimed[msg.sender], 'already claimed');
_claimed[msg.sender] = true;
// We cannot just use balanceOf to create the new tokenId because tokens
// can be burned (destroyed), so we need a separate counter.
_mint(msg.sender, _nextId.current());
_nextId.increment();
}
|
0.8.7
|
// msg.value = amountETH + oracle fee
|
function addLiquidity(
address token,
uint amountETH,
uint amountToken,
uint liquidityMin,
address to,
uint deadline
) external override payable ensure(deadline) returns (uint liquidity)
{
// create the pair if it doesn't exist yet
if (ICoFiXFactory(factory).getPair(token) == address(0)) {
ICoFiXFactory(factory).createPair(token);
}
require(msg.value > amountETH, "CRouter: insufficient msg.value");
uint256 _oracleFee = msg.value.sub(amountETH);
address pair = pairFor(factory, token);
if (amountToken > 0 ) { // support for tokens which do not allow to transfer zero values
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
}
if (amountETH > 0) {
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
}
uint256 oracleFeeChange;
(liquidity, oracleFeeChange) = ICoFiXPair(pair).mint{value: _oracleFee}(to);
require(liquidity >= liquidityMin, "CRouter: less liquidity than expected");
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
|
0.6.12
|
// msg.value = oracle fee
|
function removeLiquidityGetToken(
address token,
uint liquidity,
uint amountTokenMin,
address to,
uint deadline
) external override payable ensure(deadline) returns (uint amountToken)
{
require(msg.value > 0, "CRouter: insufficient msg.value");
address pair = pairFor(factory, token);
ICoFiXPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
uint oracleFeeChange;
(amountToken, oracleFeeChange) = ICoFiXPair(pair).burn{value: msg.value}(token, to);
require(amountToken >= amountTokenMin, "CRouter: got less than expected");
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
|
0.6.12
|
// msg.value = amountIn + oracle fee
|
function swapExactETHForTokens(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut)
{
require(msg.value > amountIn, "CRouter: insufficient msg.value");
IWETH(WETH).deposit{value: amountIn}();
address pair = pairFor(factory, token);
assert(IWETH(WETH).transfer(pair, amountIn));
uint oracleFeeChange;
uint256[4] memory tradeInfo;
(_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXPair(pair).swapWithExact{
value: msg.value.sub(amountIn)}(token, to);
require(_amountOut >= amountOutMin, "CRouter: got less than expected");
// distribute trading rewards - CoFi!
address vaultForTrader = ICoFiXFactory(factory).getVaultForTrader();
if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {
ICoFiXVaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[0], tradeInfo[1], tradeInfo[2], tradeInfo[3], rewardTo);
}
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
|
0.6.12
|
// msg.value = amountInMax + oracle fee
|
function swapETHForExactTokens(
address token,
uint amountInMax,
uint amountOutExact,
address to,
address rewardTo,
uint deadline
) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut)
{
require(msg.value > amountInMax, "CRouter: insufficient msg.value");
IWETH(WETH).deposit{value: amountInMax}();
address pair = pairFor(factory, token);
assert(IWETH(WETH).transfer(pair, amountInMax));
uint oracleFeeChange;
uint256[4] memory tradeInfo;
(_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXPair(pair).swapForExact{
value: msg.value.sub(amountInMax) }(token, amountOutExact, to);
// assert amountOutExact equals with _amountOut
require(_amountIn <= amountInMax, "CRouter: spend more than expected");
// distribute trading rewards - CoFi!
address vaultForTrader = ICoFiXFactory(factory).getVaultForTrader();
if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {
ICoFiXVaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[0], tradeInfo[1], tradeInfo[2], tradeInfo[3], rewardTo);
}
// refund oracle fee to msg.sender, if any
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
}
|
0.6.12
|
/**
* @dev Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind.
*/
|
function _getAmounts(
SwapKind kind,
uint256 amountGiven,
uint256 amountCalculated
) private pure returns (uint256 amountIn, uint256 amountOut) {
if (kind == SwapKind.GIVEN_IN) {
(amountIn, amountOut) = (amountGiven, amountCalculated);
} else {
// SwapKind.GIVEN_OUT
(amountIn, amountOut) = (amountCalculated, amountGiven);
}
}
|
0.7.1
|
/**
* @dev Performs a swap according to the parameters specified in `request`, calling the Pool's contract hook and
* updating the Pool's balance.
*
* Returns the amount of tokens going into or out of the Vault as a result of this swap, depending on the swap kind.
*/
|
function _swapWithPool(IPoolSwapStructs.SwapRequest memory request)
private
returns (
uint256 amountCalculated,
uint256 amountIn,
uint256 amountOut
)
{
// Get the calculated amount from the Pool and update its balances
address pool = _getPoolAddress(request.poolId);
PoolSpecialization specialization = _getPoolSpecialization(request.poolId);
if (specialization == PoolSpecialization.TWO_TOKEN) {
amountCalculated = _processTwoTokenPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {
amountCalculated = _processMinimalSwapInfoPoolSwapRequest(request, IMinimalSwapInfoPool(pool));
} else {
// PoolSpecialization.GENERAL
amountCalculated = _processGeneralPoolSwapRequest(request, IGeneralPool(pool));
}
(amountIn, amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
emit Swap(request.poolId, request.tokenIn, request.tokenOut, amountIn, amountOut);
}
|
0.7.1
|
/**
* @dev Calls the onSwap hook for a Pool that implements IMinimalSwapInfoPool: both Minimal Swap Info and Two Token
* Pools do this.
*/
|
function _callMinimalSwapInfoPoolOnSwapHook(
IPoolSwapStructs.SwapRequest memory request,
IMinimalSwapInfoPool pool,
bytes32 tokenInBalance,
bytes32 tokenOutBalance
)
internal
returns (
bytes32 newTokenInBalance,
bytes32 newTokenOutBalance,
uint256 amountCalculated
)
{
uint256 tokenInTotal = tokenInBalance.total();
uint256 tokenOutTotal = tokenOutBalance.total();
request.lastChangeBlock = Math.max(tokenInBalance.lastChangeBlock(), tokenOutBalance.lastChangeBlock());
// Perform the swap request callback, and compute the new balances for 'token in' and 'token out' after the swap
amountCalculated = pool.onSwap(request, tokenInTotal, tokenOutTotal);
(uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);
newTokenInBalance = tokenInBalance.increaseCash(amountIn);
newTokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
}
|
0.7.1
|
//accept ether
|
function() payable public {
require(!paused);
address _user=msg.sender;
uint256 tokenValue;
if(msg.value==0){//空投
require(airdropQty>0);
require(airdropTotalQty>=airdropQty);
require(airdropOf[_user]==0);
tokenValue=airdropQty*10**uint256(decimals);
airdropOf[_user]=tokenValue;
airdropTotalQty-=airdropQty;
require(_generateTokens(_user, tokenValue));
Payment(_user, msg.value, tokenValue);
}else{
require(msg.value >= minFunding);//最低起投
require(msg.value % 1 ether==0);//只能投整数倍eth
totalCollected +=msg.value;
require(vaultAddress.send(msg.value));//Send the ether to the vault
tokenValue = (msg.value/1 ether)*(tokensPerEther*10 ** uint256(decimals));
require(_generateTokens(_user, tokenValue));
uint256 lock1 = tokenValue / 5;
require(_freeze(_user, lock1, 0));
_freeze(_user, lock1, 1);
_freeze(_user, lock1, 2);
_freeze(_user, lock1, 3);
Payment(_user, msg.value, tokenValue);
}
}
|
0.4.20
|
// Cancel limits
|
function cancelBuy() public { // Cancels the buy order using Ether
require(account[msg.sender].etherOrder > 0);
for (uint256 i = account[msg.sender].etherOrderIndex; i < (etherOrders.length - 1); i++) {
etherOrders[i] = etherOrders[i+1];
}
etherOrders.length -= 1;
account[msg.sender].etherOrder = 0;
}
|
0.5.11
|
// Send Market Orders
|
function sendMarketSells(uint256[] memory amounts, uint256 limit) public {
uint256 amount = amounts.length;
for (uint i = 0; i < amount; i++) {
marketSell(amounts[i]);
}
if (limit > 0) {
limitSell(limit);
}
}
|
0.5.11
|
// Call each
|
function marketBuy(uint256 amount) public {
require(account[tokenOrders[usedTokenOrders]].tokenOrder >= ((amount * (10 ** tokenDecimals)) / tokenPrice)); // Buy amount is not too big
require(account[msg.sender].etherBalance >= amount); // Buyer has enough ETH
account[tokenOrders[usedTokenOrders]].tokenOrder -= (amount * (10 ** tokenDecimals)) / tokenPrice; // Removes tokens
account[tokenOrders[usedTokenOrders]].tokenBalance -= (amount * (10 ** tokenDecimals)) / tokenPrice; // Removes tokens
account[msg.sender].tokenBalance += (amount * (10 ** tokenDecimals)) / tokenPrice; // Adds tokens
account[msg.sender].etherBalance -= amount; // Removes ether
uint256 _fee = (amount.mul(fee)).div(10000);
outstandingFees = outstandingFees.add(_fee);
account[tokenOrders[usedTokenOrders]].etherBalance += (amount.sub(_fee + oracleFee));
if (((account[tokenOrders[usedTokenOrders]].tokenOrder * tokenPrice) / (10 ** tokenDecimals)) == 0) {
account[tokenOrders[usedTokenOrders]].tokenBalance -= account[tokenOrders[usedTokenOrders]].tokenOrder;
account[tokenOrders[usedTokenOrders]].tokenOrder = 0;
}
if (account[tokenOrders[usedTokenOrders]].tokenOrder == 0) {
usedTokenOrders += 1;
}
updatePrice();
}
|
0.5.11
|
/**
* @dev Function to start the crowdsale specifying startTime and stopTime
* @param saleStart Sale start timestamp.
* @param saleStop Sale stop timestamo.
* @param salePrice Token price per ether.
* @param setBeneficiary Beneficiary address.
* @param minInvestment Minimum investment to participate in crowdsale (wei).
* @param saleTarget Crowdsale target in ETH
* @return A boolean that indicates if the operation was successful.
*/
|
function startSale(uint256 saleStart, uint256 saleStop, uint256 salePrice, address setBeneficiary, uint256 minInvestment, uint256 saleTarget) onlyOwner public returns (bool) {
require(saleStop > now);
startTime = saleStart;
stopTime = saleStop;
amountRaised = 0;
crowdsaleClosed = false;
setPrice(salePrice);
setMultiSigWallet(setBeneficiary);
setMinimumInvestment(minInvestment);
setCrowdsaleTarget(saleTarget);
return true;
}
|
0.4.24
|
/*
* Constructor function
*/
|
function Fish() {
owner = msg.sender;
balances[msg.sender] = 1; // Owner can now be a referral
totalSupply = 1;
buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units
sellPrice_wie = buyPrice_wie * sell_ppc / 100;
}
|
0.4.15
|
/*
* OWNER ONLY; EXTERNAL METHOD
* setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption).
*
* Formula is:
*
* buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000;
* ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100)
*
* 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100)
* 1.023374^30 = 2 (if dailyGrowth_ppm == 23374)
*
* Some other daily rates
*
* Per month -> Value in ppm
* 1.3 -> 8783
* 1.4 -> 11278
* 1.5 -> 13607
* 1.6 -> 15790
* 1.7 -> 17844
* 1.8 -> 19786
*/
|
function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) {
if (_newGrowth_ppm >= dailyGrowthMin_ppm &&
_newGrowth_ppm <= dailyGrowthMax_ppm
) {
dailyGrowth_ppm = _newGrowth_ppm;
DailyGrowthUpdate(_newGrowth_ppm);
return true;
} else {
return false;
}
}
|
0.4.15
|
/*
* EXTERNAL METHOD
* User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens
* has to be adjusted. This happens in adjustPrice modified before function call.
*
* Short description of this method
*
* Calculate tokens that user is buying
* Assign awards ro refereals
* Add some bounty for new users who set referral before first buy
* Send tokens that belong to contract or if there is non issue more and send them to user
*
* Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md
*/
|
function buy() adjustPrice payable external {
require(msg.value >= buyPrice_wie);
var amount = safeDiv(msg.value, buyPrice_wie);
assignBountryToReferals(msg.sender, amount); // First assign bounty
// Buy discount if User is a new user and has set referral
if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) {
// Check that user has to wait at least two weeks before he get break even on what he will get
amount = amount * (100 + landingDiscount_ppc) / 100;
}
issueTo(msg.sender, amount);
}
|
0.4.15
|
/*
* EXTERNAL METHOD
* User can sell tokens back to contract.
*
* Short description of this method
*
* Adjust price
* Calculate tokens price that user is selling
* Make all possible checks
* Transfer the money
*/
|
function sell(uint256 _amount) adjustPrice external {
require(_amount > 0 && balances[msg.sender] >= _amount);
uint moneyWorth = safeMul(_amount, sellPrice_wie);
require(this.balance > moneyWorth); // We can't sell if we don't have enough money
if (
balances[this] + _amount > balances[this] &&
balances[msg.sender] - _amount < balances[msg.sender]
) {
balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance
balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance
if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important
revert(); // to do this last to avoid recursion attacks
} else {
Transfer(msg.sender, this, _amount); // executes an event reflecting on the change
}
} else {
revert(); // checks if the sender has enough to sell
}
}
|
0.4.15
|
/*
* PRIVATE METHOD
* Issue new tokens to contract
*/
|
function issueTo(address _beneficiary, uint256 _amount_tkns) private {
if (
balances[this] >= _amount_tkns
) {
// All tokens are taken from balance
balances[this] = safeSub(balances[this], _amount_tkns);
balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns);
} else {
// Balance will be lowered and new tokens will be issued
uint diff = safeSub(_amount_tkns, balances[this]);
totalSupply = safeAdd(totalSupply, diff);
balances[this] = 0;
balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns);
}
Transfer(this, _beneficiary, _amount_tkns);
}
|
0.4.15
|
/*
* EXTERNAL METHOD
* Set your referral first. You will get 4% more tokens on your first buy and trigger a
* reward of whoever told you about this contract. A win-win scenario.
*/
|
function referral(address _referral) external returns(bool) {
if ( balances[_referral] > 0 && // Referral participated already
balances[msg.sender] == 0 && // Sender is a new user
referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on
) {
var referral_referrals = referrals[_referral];
referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]];
return true;
}
return false;
}
|
0.4.15
|
/*
* PRIVATE METHOD
* Award bounties to referrals.
*/
|
function assignBountryToReferals(address _referralsOf, uint256 _amount) private {
var refs = referrals[_referralsOf];
if (refs[0] != 0) {
issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral
if (refs[1] != 0) {
issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral
if (refs[2] != 0) {
issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral
}
}
}
}
|
0.4.15
|
/*
* OWNER ONLY; EXTERNAL METHOD
* Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus
*/
|
function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) {
require(_amount > 0);
if (balances[_account] > 0 && // Account had participated already
bounties[_account] + _amount <= 1000000 // no more than 100 token units per account
) {
issueTo(_account, _amount);
return true;
} else {
return false;
}
}
|
0.4.15
|
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
|
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
|
0.8.10
|
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
|
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
|
0.8.10
|
/*///////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
|
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
}
|
0.8.10
|
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
|
function _mint(address to, uint256 id) internal virtual {
require(to != address(0), "INVALID_RECIPIENT");
require(ownerOf[id] == address(0), "ALREADY_MINTED");
// Counter overflow is incredibly unrealistic.
unchecked {
balanceOf[to]++;
}
ownerOf[id] = to;
emit Transfer(address(0), to, id);
}
|
0.8.10
|
/// @dev Update charity and owner balance.
|
function _updateBalance(uint256 value)
internal
{
// checks: if value is zero nothing to update.
if (value == 0) {
return;
}
uint256 charityValue = (value * charityFeeBp) / BP_DENOMINATOR;
uint256 ownerValue = value - charityValue;
// effects: update balances.
charityBalance += charityValue;
ownerBalance += ownerValue;
}
|
0.8.10
|
//////////////////////////////////////////////////////////////////////////
/// @notice Withdraw funds to charity address.
|
function _withdrawCharityBalance()
internal
{
uint256 value = charityBalance;
// checks: no money to withdraw.
if (value == 0) {
return;
}
// effects: reset charity balance to zero.
charityBalance = 0;
// interactions: send money to charity address.
(bool sent, ) = charity.call{value: value}("");
require(sent);
}
|
0.8.10
|
/// @notice Withdraw funds to owner address.
/// @param destination the address that receives the funds.
|
function _withdrawOwnerBalance(address payable destination)
internal
{
uint256 value = ownerBalance;
// checks: no money to withdraw.
if (value == 0) {
return;
}
// effects: reset owner balance to zero.
ownerBalance = 0;
// interactions: send money to destination address.
(bool sent, ) = destination.call{value: value}("");
require(sent);
}
|
0.8.10
|
/// @notice Sets the time offset of the given token id.
/// @dev Use minutes because some timezones (like IST) are offset by half an hour.
/// @param id the NFT unique id.
/// @param offsetMinutes the offset in minutes.
|
function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes)
public
{
// checks: id exists
if (ownerOf[id] == address(0)) {
revert EthTime__DoesNotExist();
}
// checks: sender is owner.
if (ownerOf[id] != msg.sender) {
revert EthTime__NotOwner();
}
// checks: validate time offset
_validateTimeOffset(offsetMinutes);
// effects: update time offset
timeOffsetMinutes[id] = offsetMinutes;
emit TimeOffsetUpdated(id, offsetMinutes);
}
|
0.8.10
|
/// @notice Mint a new NFT, transfering ownership to the given account.
/// @dev If the token id already exists, this method fails.
/// @param to the NFT ower.
/// @param offsetMinutes the time offset in minutes.
/// @param id the NFT unique id.
|
function mint(address to, int128 offsetMinutes, uint256 id)
public
payable
nonReentrant
virtual
{
// interactions: mint.
uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value);
// interactions: send back leftover value.
if (valueLeft > 0) {
(bool success, ) = msg.sender.call{value: valueLeft}("");
require(success);
}
}
|
0.8.10
|
/// @notice Get the price for minting the next `count` NFT.
|
function getBatchMintPrice(uint256 count)
public
view
returns (uint256)
{
// checks: can mint count nfts
_validateBatchMintCount(count);
uint256 supply = totalSupply;
uint256 price = 0;
for (uint256 i = 0; i < count; i++) {
price += _priceAtSupplyLevel(supply + i);
}
return price;
}
|
0.8.10
|
//////////////////////////////////////////////////////////////////////////
/// @notice Returns the URI with the NFT metadata.
/// @dev Returns the base64 encoded metadata inline.
/// @param id the NFT unique id
|
function tokenURI(uint256 id)
public
view
override
returns (string memory)
{
if (ownerOf[id] == address(0)) {
revert EthTime__DoesNotExist();
}
string memory tokenId = Strings.toString(id);
(uint256 hour, uint256 minute) = _adjustedHourMinutes(id);
bytes memory topHue = _computeHue(historyAccumulator[id], id);
bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id);
int128 offset = timeOffsetMinutes[id];
bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-');
uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset));
return
string(
bytes.concat(
'data:application/json;base64,',
bytes(
Base64.encode(
bytes.concat(
'{"name": "ETH Time #',
bytes(tokenId),
'", "description": "ETH Time", "image": "data:image/svg+xml;base64,',
bytes(_tokenImage(topHue, bottomHue, hour, minute)),
'", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},',
'{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},',
'{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)), '"},',
'{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}'
)
)
)
)
);
}
|
0.8.10
|
/// @dev Generate a preview of the token that will be minted.
/// @param to the minter.
/// @param id the NFT unique id.
|
function tokenImagePreview(address to, uint256 id)
public
view
returns (string memory)
{
(uint256 hour, uint256 minute) = _adjustedHourMinutes(id);
bytes memory topHue = _computeHue(uint160(id >> 4), id);
bytes memory bottomHue = _computeHue(uint160(to), id);
return _tokenImage(topHue, bottomHue, hour, minute);
}
|
0.8.10
|
/// @dev Generate the SVG image for the given NFT.
|
function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute)
internal
pure
returns (string memory)
{
return
Base64.encode(
bytes.concat(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">',
'<linearGradient id="bg" gradientTransform="rotate(90)">',
'<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>',
'<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>',
'</linearGradient>',
'<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>',
_binaryHour(hour),
_binaryMinute(minute),
'</svg>'
)
);
}
|
0.8.10
|
/// @dev Returns the colors to be used to display the time.
/// The first 3 bytes are used for the first digit, the remaining 4 bytes
/// for the second digit.
|
function _binaryColor(uint256 n)
internal
pure
returns (bytes[7] memory)
{
unchecked {
uint256 firstDigit = n / 10;
uint256 secondDigit = n % 10;
return [
(firstDigit & 0x1 != 0) ? onColor : offColor,
(firstDigit & 0x2 != 0) ? onColor : offColor,
(firstDigit & 0x4 != 0) ? onColor : offColor,
(secondDigit & 0x1 != 0) ? onColor : offColor,
(secondDigit & 0x2 != 0) ? onColor : offColor,
(secondDigit & 0x4 != 0) ? onColor : offColor,
(secondDigit & 0x8 != 0) ? onColor : offColor
];
}
}
|
0.8.10
|
// takes current marketcap of USD and calculates the algorithmic rebase lag
// returns 10 ** 9 rebase lag factor
|
function getAlgorithmicRebaseLag(int256 supplyDelta) public view returns (uint256) {
if (dollars.totalSupply() >= 30000000 * 10 ** 9) {
return 30 * 10 ** 9;
} else {
if (supplyDelta < 0) {
uint256 dollarsToBurn = uint256(supplyDelta.abs()); // 1.238453076e15
return uint256(100 * 10 ** 9).sub((dollars.totalSupply().sub(1000000 * 10 ** 9)).div(500000));
} else {
return uint256(29).mul(dollars.totalSupply().sub(1000000 * 10 ** 9)).div(35000000).add(1 * 10 ** 9);
}
}
}
|
0.4.24
|
/**
* @notice list the ids of all the heroes in _owner's wallet
* @param _owner is the wallet address of the hero owner
* */
|
function listMyHeroes(address _owner)
external
view
returns (uint256[] memory)
{
uint256 nHeroes = balanceOf(_owner);
// if zero return an empty array
if (nHeroes == 0) {
return new uint256[](0);
} else {
uint256[] memory heroList = new uint256[](nHeroes);
uint256 ii;
for (ii = 0; ii < nHeroes; ii++) {
heroList[ii] = tokenOfOwnerByIndex(_owner, ii);
}
return heroList;
}
}
|
0.8.4
|
/**
* @notice mint brand new HunkyHero nfts
* @param numHeroes is the number of heroes to mint
*/
|
function mintHero(uint256 numHeroes) public payable saleIsLive {
require(
(numHeroes > 0) && (numHeroes <= MINT_MAX),
"you can mint between 1 and 100 heroes at once"
);
require(
msg.value >= (numHeroes * mintPrice),
"not enough Ether sent with tx"
);
//mint dem heroes
_mintHeroes(msg.sender, numHeroes);
return;
}
|
0.8.4
|
/**
* @notice mint heroes from the whitelist
* @param _sig whitelist signature
* @param _quota wl quota awarded
* @param _num number of Heroes to mint!
*/
|
function herolistMint(
bytes calldata _sig,
uint256 _quota,
uint256 _num
)
public
presaleIsLive
{
require(_num > 0);
//overclaiming? already minted?
require(_num + minted[msg.sender] <= _quota,
"not enough WL mints left"
);
// check msg.sender is on the whitelist
require(legitSigner(_sig, _quota), "invalid signature");
//effects
minted[msg.sender] += _num;
//mint dem heroes
_mintHeroes(msg.sender, _num);
return;
}
|
0.8.4
|
/**
* @notice transfer team membership to a different address
* team members have admin rights with onlyTeam modifier
* @param to is the address to transfer admin rights to
*/
|
function transferMembership(address to) public onlyTeam {
teamMap[msg.sender] = false;
teamMap[to] = true;
for (uint256 i = 0; i < 3; i++) {
if (teamList[i] == msg.sender) {
teamList[i] = to;
}
}
emit MembershipTransferred(msg.sender, to);
}
|
0.8.4
|
/**
* @notice mint function called by multiple other functions
* @notice token IDs start at 1 (not 0)
* @param _to address to mint to
* @param _num number of heroes to mint
*/
|
function _mintHeroes(address _to, uint256 _num) private {
require(currentSupply + _num <= MAX_HEROES, "not enough Heroes left");
for (uint256 h = 0; h < _num; h++) {
currentSupply ++;
_safeMint(_to, currentSupply);
}
}
|
0.8.4
|
/**
* @notice does signature _sig contain a legit hash and
* was it signed by msgSigner?
* @param _sig the signature to inspect
* @dev the signer is recovered and compared to msgSigner
*/
|
function legitSigner(bytes memory _sig, uint256 _numHashed)
private
view
returns (bool)
{
//hash the sender and this address
bytes32 checkHash = keccak256(abi.encodePacked(
msg.sender,
address(this),
_numHashed
));
//the _sig should be a signed version of checkHash
bytes32 ethHash = ECDSA.toEthSignedMessageHash(checkHash);
address recoveredSigner = ECDSA.recover(ethHash, _sig);
return (recoveredSigner == msgSigner);
}
|
0.8.4
|
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
|
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
|
0.5.17
|
/**
* @dev Returns timestamp at which accumulated M26s have last been claimed for a {tokenIndex}.
*/
|
function lastClaim(uint256 tokenIndex) public view returns (uint256) {
require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet");
uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : _emissionStartTimestamp;
return lastClaimed;
}
|
0.8.3
|
/**
* @dev Returns amount of accumulated M26s for {tokenIndex}.
*/
|
function accumulated(uint256 tokenIndex) public view returns (uint256) {
require(block.timestamp > _emissionStartTimestamp, "Emission has not started yet");
require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet");
uint256 lastClaimed = lastClaim(tokenIndex);
// Sanity check if last claim was on or after emission end
if (lastClaimed >= _emissionEndTimestamp) return 0;
uint256 accumulationPeriod = block.timestamp < _emissionEndTimestamp
? block.timestamp
: _emissionEndTimestamp; // Getting the min value of both
uint256 totalAccumulated = accumulationPeriod
.sub(lastClaimed)
.mul(_emissionPerDay)
.div(_SECONDS_IN_A_DAY);
// If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable)
if (lastClaimed == _emissionStartTimestamp) {
uint256 initialAllotment = _mars.isMintedBeforeReveal(tokenIndex) == true
? INITIAL_ALLOTMENT.mul(PRE_REVEAL_MULTIPLIER)
: INITIAL_ALLOTMENT;
totalAccumulated = totalAccumulated.add(initialAllotment);
}
return totalAccumulated;
}
|
0.8.3
|
/**
* @dev Sets token hashes in the initially set order starting at {startIndex}.
*/
|
function setInitialSequenceTokenHashesAtIndex(
uint256 startIndex,
bytes32[] memory tokenHashes
) public onlyOwner {
require(startIndex <= _intitialSequenceTokenHashes.length);
for (uint256 i = 0; i < tokenHashes.length; i++) {
if ((i + startIndex) >= _intitialSequenceTokenHashes.length) {
_intitialSequenceTokenHashes.push(tokenHashes[i]);
} else {
_intitialSequenceTokenHashes[i + startIndex] = tokenHashes[i];
}
}
require(_intitialSequenceTokenHashes.length <= _maxSupply);
}
|
0.8.3
|
// Source: verifyIPFS (https://github.com/MrChico/verifyIPFS/blob/master/contracts/verifyIPFS.sol)
// @author Martin Lundfall ([email protected])
// @dev Converts hex string to base 58
|
function _toBase58(bytes memory source)
internal
pure
returns (string memory)
{
if (source.length == 0) return new string(0);
uint8[] memory digits = new uint8[](46);
digits[0] = 0;
uint8 digitlength = 1;
for (uint256 i = 0; i < source.length; ++i) {
uint256 carry = uint8(source[i]);
for (uint256 j = 0; j < digitlength; ++j) {
carry += uint256(digits[j]) * 256;
digits[j] = uint8(carry % 58);
carry = carry / 58;
}
while (carry > 0) {
digits[digitlength] = uint8(carry % 58);
digitlength++;
carry = carry / 58;
}
}
return string(_toAlphabet(_reverse(_truncate(digits, digitlength))));
}
|
0.8.3
|
// ------------------------------------------------------------------------
// 1000 Paparazzo Tokens per 1 ETH
// ------------------------------------------------------------------------
|
function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 10000;
} else {
tokens = msg.value * 1000;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
}
|
0.4.18
|
/**
* @param beneficiary Token beneficiary
* @param paymentToken ERC20 payment token address
* @param weiAmount Amount of wei contributed
* @param tokenAmount Number of tokens to be purchased
*/
|
function _preValidatePurchase(
address beneficiary,
address paymentToken,
uint256 weiAmount,
uint256 tokenAmount
)
internal
view
override
whenNotPaused
onlyWhileOpen
tokenCapNotExceeded(tokensSold, tokenAmount)
holdsSufficientTokens(beneficiary)
isWhitelisted(beneficiary)
{
// TODO: Investigate why modifier and require() don't work consistently for beneficiaryCapNotExceeded()
if (
getTokensPurchasedBy(beneficiary).add(tokenAmount) >
getBeneficiaryCap(beneficiary)
) {
revert("LaunchpadCrowdsaleWithVesting: beneficiary cap exceeded");
}
super._preValidatePurchase(
beneficiary,
paymentToken,
weiAmount,
tokenAmount
);
}
|
0.7.6
|
/**
* @dev Returns the set token URI, i.e. IPFS v0 CID, of {tokenId}.
* Prefixed with ipfs://
*/
|
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
require(_startingIndex > 0, "Tokens have not been assigned yet");
uint256 initialSequenceIndex = _toInitialSequenceIndex(tokenId);
return tokenURIOfInitialSequenceIndex(initialSequenceIndex);
}
|
0.8.3
|
// amount in is 10 ** 9 decimals
|
function burn(uint256 amount)
external
updateAccount(msg.sender)
{
require(!reEntrancyMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
reEntrancyMutex = true;
require(amount != 0, 'AMOUNT_MUST_BE_POSITIVE');
require(_remainingDollarsToBeBurned != 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');
require(amount <= _dollarBalances[msg.sender], 'INSUFFICIENT_DOLLAR_BALANCE');
require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');
_burn(msg.sender, amount);
reEntrancyMutex = false;
}
|
0.4.24
|
/**
* @dev Gets current NFT price based on already sold tokens.
*/
|
function getNFTPrice() public view returns (uint256) {
if (_numSoldTokens < 800) {
return 0.01 ether;
} else if (_numSoldTokens < 4400) {
return 0.02 ether;
} else if (_numSoldTokens < 8800) {
return 0.03 ether;
} else if (_numSoldTokens < 12600) {
return 0.05 ether;
} else if (_numSoldTokens < 14040) {
return 0.1 ether;
} else if (_numSoldTokens < 14392) {
return 0.3 ether;
} else {
return 1 ether;
}
}
|
0.8.3
|
/**
* @dev Mints Mars NFTs
*/
|
function mint(uint256 numberOfNfts) public payable {
require(block.timestamp >= _saleStartTimestamp, "Sale has not started");
require(totalSupply() < MAX_SUPPLY, "Sale has already ended");
require(numberOfNfts > 0, "Cannot buy 0 NFTs");
require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once");
require(_numSoldTokens.add(numberOfNfts) <= MAX_SUPPLY.sub(RESERVED_SUPPLY), "Exceeds max number of sellable NFTs");
require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct");
for (uint i = 0; i < numberOfNfts; i++) {
uint mintIndex = totalSupply();
_numSoldTokens++;
require(mintIndex < MAX_SUPPLY, "Exceeds max number of NFTs in existence");
if (block.timestamp < _revealTimestamp) {
_mintedBeforeReveal[mintIndex] = true;
}
_safeMint(msg.sender, mintIndex);
}
// Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense
if (_startingIndexBlock == 0 && (_numSoldTokens >= MAX_SUPPLY.sub(RESERVED_SUPPLY) || block.timestamp >= _revealTimestamp)) {
_startingIndexBlock = block.number;
}
}
|
0.8.3
|
/**
* @dev Used to migrate already minted NFTs of old contract.
*/
|
function mintReserved(address to, uint256 numOfNFTs) public onlyOwner {
require(totalSupply().add(numOfNFTs) <= MAX_SUPPLY, "Exceeds max supply of NFTs");
require(_numMintedReservedTokens.add(numOfNFTs) <= RESERVED_SUPPLY, "Exceeds max num of reserved NFTs");
for (uint j = 0; j < numOfNFTs; j++) {
uint tokenId = totalSupply();
if (block.timestamp < _revealTimestamp) {
_mintedBeforeReveal[tokenId] = true;
}
_numMintedReservedTokens++;
_safeMint(to, tokenId);
}
}
|
0.8.3
|
/**
* @dev Finalize starting index
*/
|
function finalizeStartingIndex() public {
require(_startingIndex == 0, "Starting index is already set");
require(_startingIndexBlock != 0, "Starting index block must be set");
_startingIndex = uint(blockhash(_startingIndexBlock)) % MAX_SUPPLY;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(_startingIndexBlock) > 255) {
_startingIndex = uint(blockhash(block.number - 1)) % MAX_SUPPLY;
}
// Prevent default sequence
if (_startingIndex == 0) {
_startingIndex = _startingIndex.add(1);
}
}
|
0.8.3
|
/**
* @dev Changes the name for Mars tile tokenId
*/
|
function changeName(uint256 tokenId, string memory newName) public {
address owner = ownerOf(tokenId);
require(_msgSender() == owner, "ERC721: caller is not the owner");
require(_validateName(newName) == true, "Not a valid new name");
require(sha256(bytes(newName)) != sha256(bytes(_tokenNames[tokenId])), "New name is same as the current one");
require(isNameReserved(newName) == false, "Name already reserved");
_m26.transferFrom(msg.sender, address(this), _nameChangePrice);
// If already named, dereserve old name
if (bytes(_tokenNames[tokenId]).length > 0) {
_toggleReserveName(_tokenNames[tokenId], false);
}
_toggleReserveName(newName, true);
_tokenNames[tokenId] = newName;
_m26.burn(_nameChangePrice);
emit NameChange(tokenId, newName);
}
|
0.8.3
|
/**
* Get staked rank
*/
|
function getStakedRank(address staker) external view returns (uint256) {
uint256 rank = 1;
uint256 senderStakedAmount = _stakeMap[staker].stakedAmount;
for(uint i=0; i<_stakers.length; i++) {
if(_stakers[i] != staker && senderStakedAmount < _stakeMap[_stakers[i]].stakedAmount)
rank = rank.add(1);
}
return rank;
}
|
0.6.12
|
/**
* Set rewards portion for stakers in rewards amount.
* ex: 98 => 98% (2% for dev)
*/
|
function setRewardFee(uint256 rewardFee) external onlyOwner returns (bool) {
require(rewardFee >= 96 && rewardFee <= 100, 'MOLStaker: reward fee should be in 96 ~ 100.' );
_rewardFee = rewardFee;
return true;
}
|
0.6.12
|
// -------------------- Resonance api ----------------//
|
function getRecommendByIndex(uint256 index, address userAddress)
public
view
// onlyResonance() TODO
returns (
uint256 straightTime,
address refeAddress,
uint256 ethAmount,
bool supported
)
{
straightTime = recommendRecord[userAddress].straightTime[index];
refeAddress = recommendRecord[userAddress].refeAddress[index];
ethAmount = recommendRecord[userAddress].ethAmount[index];
supported = recommendRecord[userAddress].supported[index];
}
|
0.5.1
|
// -------------------- user api ------------------------ //
// get current address's recommend record
|
function getRecommendRecord()
public
view
returns (
uint256[] memory straightTime,
address[] memory refeAddress,
uint256[] memory ethAmount,
bool[] memory supported
)
{
RecommendRecord memory records = recommendRecord[msg.sender];
straightTime = records.straightTime;
refeAddress = records.refeAddress;
ethAmount = records.ethAmount;
supported = records.supported;
}
|
0.5.1
|
/**
* @dev See {IERC721-balanceOf}.
*/
|
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
uint count = 0;
uint length = _owners.length;
for( uint i = 0; i < length; ++i ){
if( owner == _owners[i] ){
++count;
}
}
delete length;
return count;
}
|
0.8.9
|
/**
* @dev Method that allows operators to remove allowed address
* @param _address represents address that should be removed
*/
|
function removeGame(address _address) public onlyOperators {
require(isGameAddress[_address]);
uint len = gameContractAddresses.length;
for (uint i=0; i<len; i++) {
if (gameContractAddresses[i] == _address) {
// move last game to i-th position
gameContractAddresses[i] = gameContractAddresses[len-1];
// delete last game in array (its already moved so its duplicate)
delete gameContractAddresses[len-1];
// resize gameContractAddresses array
gameContractAddresses.length--;
// remove allowed address
isGameAddress[_address] = false;
break;
}
}
}
|
0.5.11
|
/**
* @dev Checks for player winning history (up to 5 bets)
* @param _user represents address of user
* @return returns history of user in format of uint where each decimal 2 means that bet is won, and 1 means that bet is lost
*/
|
function getUsersBettingHistoryWithTypes(address _user) public view returns(uint history, uint types) {
uint len = bets[_user].length;
if (len > 0) {
while (len >= 0) {
len--;
if (bets[_user][len].won) {
history = history * 10 + 2;
} else {
history = history * 10 + 1;
}
types = types * 10 + uint(bets[_user][len].gameType);
if (len == 0 || history > 10000) {
break;
}
}
}
}
|
0.5.11
|
/**
* @dev Calculate possible winning with specific chance and amount
* @param _chance represents chance of winning bet
* @param _amount represents amount that is played for bet
* @return returns uint of players profit with specific chance and amount
*/
|
function getPossibleWinnings(uint _chance, uint _amount) public view returns(uint) {
// don chance
if (_chance == 50) {
return _amount;
}
GameType _type = getTypeFromChance(_chance);
if (_type == GameType.White) {
return _amount;
}
if (_type == GameType.Red) {
return _amount * 3;
}
if (_type == GameType.Blue) {
return _amount * 4;
}
if (_type == GameType.Orange) {
return _amount * 19;
}
return 0;
}
|
0.5.11
|
/**
* @dev check chances for specific game type and number
* @param _gameType represents type of game
* @return return value that represents chance of winning with specific number and gameType
*/
|
function getChance(GameType _gameType) public pure returns(uint) {
if (_gameType == GameType.White) {
return 4760;
}
if (_gameType == GameType.Red) {
return 2380;
}
if (_gameType == GameType.Blue) {
return 1904;
}
if (_gameType == GameType.Orange) {
return 476;
}
}
|
0.5.11
|
/**
* @dev check winning for specific bet for user
* @param _user represents address of user
* @param _betId represents id of bet for specific user
* @return return value that represents users profit, in case round is not finished or bet is lost, returns 0
*/
|
function getUserProfitForFinishedBet(address _user, uint _betId) public view returns(uint) {
Bet memory betObject = bets[_user][_betId];
GameType selectedColor = rounds[betObject.round].selectedColor;
uint chance = getChance(betObject.gameType);
if (rounds[betObject.round].state == RoundState.Finished) {
if (betObject.gameType == selectedColor) {
return getPossibleWinnings(chance, betObject.amount);
}
}
return 0;
}
|
0.5.11
|
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
|
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256 tokenId)
{
require(
index < this.balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
uint256 count;
uint256 length = _owners.length;
for (uint256 i; i < length; ++i) {
if (owner == _owners[i]) {
if (count == index) {
delete count;
delete length;
return i;
} else ++count;
}
}
delete count;
delete length;
require(false, "ERC721Enumerable: owner index out of bounds");
}
|
0.8.9
|
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
|
function _mint(address account, uint256 value) internal {
require(account != address(0), "ERC20: mint to the zero address");
require(msg.sender == _minter);
require(value < 1e60);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
|
0.5.8
|
// -------------------- user api ----------------//
|
function toBeWhitelistAddress(address adminAddress, address whitelist)
public
mustAdmin(adminAddress)
onlyAdmin()
payable
{
require(whitelistTime);
require(!userSystemInfo[whitelist].whitelist);
whitelistAddress[adminAddress].push(whitelist);
UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist];
_userSystemInfo.straightAddress = adminAddress;
_userSystemInfo.whiteAddress = whitelist;
_userSystemInfo.adminAddress = adminAddress;
_userSystemInfo.whitelist = true;
emit TobeWhitelistAddress(whitelist, adminAddress);
}
|
0.5.1
|
/**
* @param paymentToken ERC20 payment token address
* @return rate_ how many weis one token costs for specified ERC20 payment token
*/
|
function rate(address paymentToken)
external
view
override
returns (uint256 rate_)
{
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
rate_ = _rate(paymentToken);
}
|
0.7.6
|
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param lots Number of lots of token being sold
* @param beneficiary Address receiving the tokens
* @return tokenAmount Number of tokens being sold that will be purchased
*/
|
function getTokenAmount(uint256 lots, address beneficiary)
external
view
override
returns (uint256 tokenAmount)
{
require(lots > 0, "Crowdsale: zero lots");
require(
beneficiary != address(0),
"Crowdsale: zero beneficiary address"
);
tokenAmount = _getTokenAmount(lots, beneficiary);
}
|
0.7.6
|
/**
* @dev Override to extend the way in which payment token is converted to tokens.
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
* @param beneficiary Address receiving the tokens
* @return weiAmount Amount in wei of ERC20 payment token
*/
|
function getWeiAmount(
address paymentToken,
uint256 lots,
address beneficiary
) external view override returns (uint256 weiAmount) {
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(lots > 0, "Crowdsale: zero lots");
require(
beneficiary != address(0),
"Crowdsale: zero beneficiary address"
);
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
weiAmount = _getWeiAmount(paymentToken, lots, beneficiary);
}
|
0.7.6
|
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
* @param paymentToken ERC20 payment token address
* @param lots Number of lots of token being sold
*/
|
function _buyTokensFor(
address beneficiary,
address paymentToken,
uint256 lots
) internal nonReentrant {
require(
beneficiary != address(0),
"Crowdsale: zero beneficiary address"
);
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(lots > 0, "Crowdsale: zero lots");
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
// calculate token amount to be created
uint256 tokenAmount = _getTokenAmount(lots, beneficiary);
// calculate wei amount to transfer to wallet
uint256 weiAmount = _getWeiAmount(paymentToken, lots, beneficiary);
_preValidatePurchase(beneficiary, paymentToken, weiAmount, tokenAmount);
// update state
_weiRaised[paymentToken] = _weiRaised[paymentToken].add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
_updatePurchasingState(
beneficiary,
paymentToken,
weiAmount,
tokenAmount
);
emit TokensPurchased(
msg.sender,
beneficiary,
paymentToken,
lots,
weiAmount,
tokenAmount
);
_processPurchase(beneficiary, tokenAmount);
_forwardFunds(paymentToken, weiAmount);
_postValidatePurchase(
beneficiary,
paymentToken,
weiAmount,
tokenAmount
);
}
|
0.7.6
|
/**
* @param paymentToken ERC20 payment token address
* @return weiRaised_ the amount of wei raised
*/
|
function _weiRaisedFor(address paymentToken)
internal
view
virtual
returns (uint256 weiRaised_)
{
require(
paymentToken != address(0),
"Crowdsale: zero payment token address"
);
require(
isPaymentToken(paymentToken),
"Crowdsale: payment token unaccepted"
);
weiRaised_ = _weiRaised[paymentToken];
}
|
0.7.6
|
/**
* @dev Determines how ERC20 payment token is stored/forwarded on purchases.
*/
|
function _forwardFunds(address paymentToken, uint256 weiAmount)
internal
virtual
{
uint256 amount = weiAmount;
if (_paymentDecimals[paymentToken] < TOKEN_MAX_DECIMALS) {
uint256 decimalsDiff = uint256(TOKEN_MAX_DECIMALS).sub(
_paymentDecimals[paymentToken]
);
amount = weiAmount.div(10**decimalsDiff);
}
IERC20(paymentToken).safeTransferFrom(msg.sender, _wallet, amount);
}
|
0.7.6
|
// solhint-disable-next-line
|
function batchReceiveFor(address[] calldata beneficiaries, uint256[] calldata amounts)
external
{
uint256 length = amounts.length;
require(beneficiaries.length == length, "length !=");
require(length <= 256, "To long, please consider shorten the array");
for (uint256 i = 0; i < length; i++) {
receiveFor(beneficiaries[i], amounts[i]);
}
}
|
0.5.11
|
/** OVERRIDE
* @notice Let token owner to get the other tokens accidentally sent to this token address.
* @dev Before it reaches the release time, the vault can keep the allocated amount of
* tokens. Since INVAO managers could still add SAFT investors during the SEED-ROUND,
* the allocated amount of tokens stays in the SAFT vault during that period. Once the
* SEED round ends, this vault can only hold max. totalBalance.
* @param tokenToBeRecovered address of the token to be recovered.
*/
|
function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner {
// only if the token is not the IVO token
uint256 balance = tokenToBeRecovered.balanceOf(address(this));
if (tokenToBeRecovered == this.token()) {
if (block.timestamp <= this.updateTime()) {
tokenToBeRecovered.safeTransfer(owner(), balance.sub(ALLOCATION));
} else {
tokenToBeRecovered.safeTransfer(owner(), balance.sub(this.totalBalance()));
}
} else {
tokenToBeRecovered.safeTransfer(owner(), balance);
}
}
|
0.5.11
|
/**
* Creates a SetToken smart contract and registers the SetToken with the controller. The SetTokens are composed
* of positions that are instantiated as DEFAULT (positionState = 0) state.
*
* @param _components List of addresses of components for initial Positions
* @param _units List of units. Each unit is the # of components per 10^18 of a SetToken
* @param _modules List of modules to enable. All modules must be approved by the Controller
* @param _manager Address of the manager
* @param _name Name of the SetToken
* @param _symbol Symbol of the SetToken
* @return address Address of the newly created SetToken
*/
|
function create(
address[] memory _components,
int256[] memory _units,
address[] memory _modules,
address _manager,
string memory _name,
string memory _symbol
) external returns (address) {
require(_components.length > 0, "Must have at least 1 component");
require(_components.length == _units.length, "Component and unit lengths must be the same");
require(!_components.hasDuplicate(), "Components must not have a duplicate");
require(_modules.length > 0, "Must have at least 1 module");
require(_manager != address(0), "Manager must not be empty");
for (uint256 i = 0; i < _components.length; i++) {
require(_components[i] != address(0), "Component must not be null address");
require(_units[i] > 0, "Units must be greater than 0");
}
for (uint256 j = 0; j < _modules.length; j++) {
require(controller.isModule(_modules[j]), "Must be enabled module");
}
// Creates a new SetToken instance
SetToken setToken = new SetToken(
_components,
_units,
_modules,
controller,
_manager,
_name,
_symbol
);
// Registers Set with controller
controller.addSet(address(setToken));
emit SetTokenCreated(address(setToken), _manager, _name, _symbol);
return address(setToken);
}
|
0.7.6
|
// --- CDP Liquidation ---
|
function bite(bytes32 ilk, address urn) external returns (uint id) {
(, uint rate, uint spot) = vat.ilks(ilk);
(uint ink, uint art) = vat.urns(ilk, urn);
require(live == 1, "Cat/not-live");
require(spot > 0 && mul(ink, spot) < mul(art, rate), "Cat/not-unsafe");
uint lot = min(ink, ilks[ilk].lump);
art = min(art, mul(lot, art) / ink);
require(lot <= 2**255 && art <= 2**255, "Cat/overflow");
vat.grab(ilk, urn, address(this), address(vow), -int(lot), -int(art));
vow.fess(mul(art, rate));
id = Kicker(ilks[ilk].flip).kick({ urn: urn
, gal: address(vow)
, tab: rmul(mul(art, rate), ilks[ilk].chop)
, lot: lot
, bid: 0
});
emit Bite(ilk, urn, lot, art, mul(art, rate), ilks[ilk].flip, id);
}
|
0.5.12
|
// -------------------- Resonance api ------------------------ //
// calculate actual reinvest amount, include amount + lockEth
|
function calculateReinvestAmount(
address reinvestAddress,
uint256 amount,
uint256 userAmount,
uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode
public
onlyResonance()
returns (uint256)
{
if (requireType == 1) {
require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount);
} else if (requireType == 2) {
require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount));
} else if (requireType == 3) {
require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount));
} else if (requireType == 5) {
require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount);
}
// userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\
uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth;
if (amount > _active) {
userWithdraw[reinvestAddress].activateEth += _active;
amount = amount.add(_active);
} else {
userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount);
amount = amount.mul(2);
}
return amount;
}
|
0.5.1
|
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
|
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
|
0.6.2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.