Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
146 | // The amount of USDC you get in exchange, at the current token price | uint256 withdrawalAmount = toErc20Amount(receiptTokenAmount);
require(withdrawalAmount <= _records[currentPeriod].totalDeposited, "Invalid withdrawal amount");
uint256 maxWithdrawalAmount = getMaxWithdrawalAmount();
require(withdrawalAmount <= maxWithdrawalAmount, "Max withdrawal amount exceeded");
uint256 currentBalance = tokenInterface.balanceOf(address(this));
require(currentBalance > withdrawalAmount, "Insufficient funds in the buffer");
| uint256 withdrawalAmount = toErc20Amount(receiptTokenAmount);
require(withdrawalAmount <= _records[currentPeriod].totalDeposited, "Invalid withdrawal amount");
uint256 maxWithdrawalAmount = getMaxWithdrawalAmount();
require(withdrawalAmount <= maxWithdrawalAmount, "Max withdrawal amount exceeded");
uint256 currentBalance = tokenInterface.balanceOf(address(this));
require(currentBalance > withdrawalAmount, "Insufficient funds in the buffer");
| 43,923 |
121 | // Stop rewards Only callable by owner. Needs to be for emergency. / | function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
lpToken.safeTransferFrom(
address(rewardTokenHolder),
address(msg.sender),
_amount
);
}
| function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
lpToken.safeTransferFrom(
address(rewardTokenHolder),
address(msg.sender),
_amount
);
}
| 26,664 |
496 | // Accessor method for the total collateral stored within the PerpetualPositionManager.return totalCollateral amount of all collateral within the position manager. / | function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
| function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
| 3,861 |
96 | // 2 days after starttime | block.timestamp > starttime.add(172800) &&
block.timestamp > nextBoostPurchaseTime[msg.sender],
"early boost purchase"
);
| block.timestamp > starttime.add(172800) &&
block.timestamp > nextBoostPurchaseTime[msg.sender],
"early boost purchase"
);
| 60,613 |
42 | // validate input | require(getReserveSaleEnabled(converter, fromToken));
| require(getReserveSaleEnabled(converter, fromToken));
| 23,346 |
20 | // Implements the not equal operation (!=) in the SD59x18 type. | function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = unwrap(x) != unwrap(y);
}
| function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
result = unwrap(x) != unwrap(y);
}
| 16,935 |
0 | // Contract keys | bytes32 public RULES_CONTRACT = 0x72756c6573000000000000000000000000000000000000000000000000000000; // "rules"
bytes32 public ADMIN_CONTRACT = 0x61646d696e697374726174696f6e000000000000000000000000000000000000; // "administration"
| bytes32 public RULES_CONTRACT = 0x72756c6573000000000000000000000000000000000000000000000000000000; // "rules"
bytes32 public ADMIN_CONTRACT = 0x61646d696e697374726174696f6e000000000000000000000000000000000000; // "administration"
| 2,386 |
19 | // ╔══════════════════════════════╗/An NFT is open for offers/ | function _isSaleOngoing(address _nftContractAddress, uint256 _tokenId, address _nftSeller)
internal view returns (bool)
| function _isSaleOngoing(address _nftContractAddress, uint256 _tokenId, address _nftSeller)
internal view returns (bool)
| 17,159 |
20 | // 取得精準度 | function decimals() public onlyOwner view override returns (uint8) {
return decimals_;
}
| function decimals() public onlyOwner view override returns (uint8) {
return decimals_;
}
| 30,417 |
141 | // TOKEN ADMIN/ | {
return delegateCall(_token);
}
| {
return delegateCall(_token);
}
| 48,062 |
21 | // 返回当前调用该合约的账户地址 | function getAddress() public view returns (address) {
return sender;
}
| function getAddress() public view returns (address) {
return sender;
}
| 46,388 |
30 | // Transfers `_amount` to `_recipient` and withdraws accrued tokens. _recipient The entity receiving the funds. _amount The amount to tranfer in base units./ | function transfer(address _recipient, uint256 _amount) public returns (bool) {
uint256 newSupplyFrom;
uint256 pendingDelegatedAccruedValue = getDelegatedAccruedValue(msg.sender);
if (accruedSince[msg.sender] != 0 && proofOfHumanity.isRegistered(msg.sender)) {
newSupplyFrom = accruedPerSecond.mul(block.timestamp.sub(accruedSince[msg.sender]));
totalSupply = totalSupply.add(newSupplyFrom);
accruedSince[msg.sender] = block.timestamp;
}
balance[msg.sender] = balance[msg.sender].add(newSupplyFrom).sub(pendingDelegatedAccruedValue).sub(_amount, "ERC20: transfer amount exceeds balance");
balance[_recipient] = balance[_recipient].add(_amount);
emit Transfer(msg.sender, _recipient, _amount);
return true;
}
| function transfer(address _recipient, uint256 _amount) public returns (bool) {
uint256 newSupplyFrom;
uint256 pendingDelegatedAccruedValue = getDelegatedAccruedValue(msg.sender);
if (accruedSince[msg.sender] != 0 && proofOfHumanity.isRegistered(msg.sender)) {
newSupplyFrom = accruedPerSecond.mul(block.timestamp.sub(accruedSince[msg.sender]));
totalSupply = totalSupply.add(newSupplyFrom);
accruedSince[msg.sender] = block.timestamp;
}
balance[msg.sender] = balance[msg.sender].add(newSupplyFrom).sub(pendingDelegatedAccruedValue).sub(_amount, "ERC20: transfer amount exceeds balance");
balance[_recipient] = balance[_recipient].add(_amount);
emit Transfer(msg.sender, _recipient, _amount);
return true;
}
| 41,852 |
7 | // return _ristore.tokenBalances(owner); | return _estore.uIntStorage(keccak256(abi.encodePacked("tokenBalance", owner)));
| return _estore.uIntStorage(keccak256(abi.encodePacked("tokenBalance", owner)));
| 8,979 |
198 | // Embalmer can extend the resurrection time of the sarcophagus,as long as the previous resurrection time is in the future data the system's data struct instance identifier the identifier of the sarcophagus resurrectionTime new resurrection time for the rewrappedsarcophagus diggingFee new digging fee for the rewrapped sarcophagus bounty new bounty for the rewrapped sarcophagus sarcoToken the SARCO token used for payment handlingreturn bool indicating that the rewrap was successful / | function rewrapSarcophagus(
Datas.Data storage data,
bytes32 identifier,
uint256 resurrectionTime,
uint256 diggingFee,
uint256 bounty,
IERC20 sarcoToken
| function rewrapSarcophagus(
Datas.Data storage data,
bytes32 identifier,
uint256 resurrectionTime,
uint256 diggingFee,
uint256 bounty,
IERC20 sarcoToken
| 57,763 |
36 | // Finish ICO and emit tokens for bounty company and team/ | function finishIco() external managerOnly {
require(statusICO == StatusICO.IcoStage5);
uint256 totalAmount = LTO.totalSupply();
LTO.mintTokens(BountyFund, bountyPart.mul(totalAmount).div(1000));
LTO.mintTokens(TeamFund, teamPart.mul(totalAmount).div(1000));
LTO.mintTokens(Company, companyPart.mul(totalAmount).div(1000));
statusICO = StatusICO.IcoFinished;
canIBuy = false;
if(soldTotal >= SOFT_CAP){canIWithdraw = false;}
emit LogFinishICO(BountyFund, Company, TeamFund);
}
| function finishIco() external managerOnly {
require(statusICO == StatusICO.IcoStage5);
uint256 totalAmount = LTO.totalSupply();
LTO.mintTokens(BountyFund, bountyPart.mul(totalAmount).div(1000));
LTO.mintTokens(TeamFund, teamPart.mul(totalAmount).div(1000));
LTO.mintTokens(Company, companyPart.mul(totalAmount).div(1000));
statusICO = StatusICO.IcoFinished;
canIBuy = false;
if(soldTotal >= SOFT_CAP){canIWithdraw = false;}
emit LogFinishICO(BountyFund, Company, TeamFund);
}
| 24,617 |
8 | // require the candidate exists | require(_candidateId > 0 && _candidateId <= candidatesCount);
| require(_candidateId > 0 && _candidateId <= candidatesCount);
| 10,639 |
12 | // Allow given spender to transfer given number of tokens from message sender._spender address to allow the owner of to transfer tokens from message sender _value number of tokens to allow to transferreturn true if token transfer was successfully approved, false otherwise / | function approve (address _spender, uint256 _value)
| function approve (address _spender, uint256 _value)
| 10,772 |
36 | // Set base URL even on retirement. Files will have to be maintained for a very long time, and for example domain name could change. To manage this, owner should be able to set base url anytime | function setBaseUrl(string _baseUrl) public onlyOwner {
baseUrl = _baseUrl;
}
| function setBaseUrl(string _baseUrl) public onlyOwner {
baseUrl = _baseUrl;
}
| 37,669 |
2 | // Link event is emitted when a new link is created./ChainID Chain id the contract is linked to./linkedContract Contract address linked to. | event Linkevent(uint8 indexed ChainID, address indexed linkedContract);
| event Linkevent(uint8 indexed ChainID, address indexed linkedContract);
| 12,082 |
6 | // Callback after a new agreement is terminated.superToken The super token used for the agreement.agreementClass The agreement class address.agreementId The agreementIdagreementData The agreement data (non-compressed)cbdata The data returned from the before-hook callback.ctx The context data. return newCtx The current context of the transaction. @custom:note- State changes is permitted. - Revert is not permitted./ | function afterAgreementTerminated(
| function afterAgreementTerminated(
| 13,665 |
159 | // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one | rebalancer.migrateProvider(_newStrategy);
| rebalancer.migrateProvider(_newStrategy);
| 15,494 |
20 | // Generate hash to prove whitelist eligibility | function getSigningHash(address recipient) public pure returns (bytes32) {
return keccak256(abi.encodePacked(recipient));
}
| function getSigningHash(address recipient) public pure returns (bytes32) {
return keccak256(abi.encodePacked(recipient));
}
| 11,652 |
149 | // _setProtocolSeizeShareFresh emits protocol-seize-share-update-specific logs on errors, so we don't need to. | return _setProtocolSeizeShareFresh(newProtocolSeizeShareMantissa);
| return _setProtocolSeizeShareFresh(newProtocolSeizeShareMantissa);
| 23,098 |
19 | // TODO: return the balance of _owner | return balances[_owner];
| return balances[_owner];
| 14,169 |
5 | // user payback pool amount | tempVar = getRateToPxlAmount(_value, council.getUserPaybackRate());
compareAmount = compareAmount.sub(tempVar);
distribution.push(
DistributionDetail(
council.getUserPaybackPool(), tempVar, true, _from)
);
| tempVar = getRateToPxlAmount(_value, council.getUserPaybackRate());
compareAmount = compareAmount.sub(tempVar);
distribution.push(
DistributionDetail(
council.getUserPaybackPool(), tempVar, true, _from)
);
| 45,367 |
281 | // Upgrade mode enter event | event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
| event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
| 78,448 |
22 | // Emitted by successful `confirmCeilingRaise` calls. | event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
| event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
| 53,721 |
46 | // The ```RevokeLiquidationFeeSetter``` event is emitted when the liquidation fee setter is revoked | event RevokeLiquidationFeeSetter();
| event RevokeLiquidationFeeSetter();
| 16,607 |
546 | // compute gas and bps fees | (uint gasPortion, uint feePortion) = _computeFees(order, order.gasEstimate);
| (uint gasPortion, uint feePortion) = _computeFees(order, order.gasEstimate);
| 6,633 |
660 | // See `IERC20.balanceOf`. / | function balanceOf(address account) public view returns (uint256) {
| function balanceOf(address account) public view returns (uint256) {
| 31,938 |
64 | // Don't allow a zero index, start counting at 1 | uint256 randomIndex = index + 1;
uint256 acc = 0;
uint256 stickerIndex = 0;
for (uint256 s = 0; s < _stickers.length; s++) {
acc += _stickers[s].amountRemaining;
if (randomIndex <= acc) {
stickerIndex = s;
break;
}
| uint256 randomIndex = index + 1;
uint256 acc = 0;
uint256 stickerIndex = 0;
for (uint256 s = 0; s < _stickers.length; s++) {
acc += _stickers[s].amountRemaining;
if (randomIndex <= acc) {
stickerIndex = s;
break;
}
| 7,805 |
12 | // Calculate how many lp tokens are needed to withdraw the dola | uint bptNeeded = bptNeededForDola(amountDola);
require(bptNeeded <= bptSupply(), "Not enough BPT tokens");
| uint bptNeeded = bptNeededForDola(amountDola);
require(bptNeeded <= bptSupply(), "Not enough BPT tokens");
| 26,440 |
19 | // This function can not access the official timelocked tokens; just other random ERC20 tokens that may have been accidently sent here | require(token != erc20Contract, "Token address can not be ERC20 address which was passed into the constructor");
| require(token != erc20Contract, "Token address can not be ERC20 address which was passed into the constructor");
| 26,528 |
26 | // More compatibility with ERC20 / | contract ERC20CompatibleToken {
using SafeMath for uint;
mapping(address => uint) balances; // List of user balances.
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping (address => mapping (address => uint256)) internal allowed;
// Function to access name of token .
function name() public view returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() public view returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
| contract ERC20CompatibleToken {
using SafeMath for uint;
mapping(address => uint) balances; // List of user balances.
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping (address => mapping (address => uint256)) internal allowed;
// Function to access name of token .
function name() public view returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() public view returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
| 8,926 |
7 | // Updates the allow list merkle root for the nft contractand emits an event. This method assume msg.sender is an nft contract and itsERC165 interface id matches INonFungibleSeaDropToken. Note: Be sure only authorized users can call this fromtoken contracts that implement INonFungibleSeaDropToken.allowListData The allow list data. / | function updateAllowList(AllowListData calldata allowListData) external;
| function updateAllowList(AllowListData calldata allowListData) external;
| 27,085 |
12 | // slither-disable-start weak-prng,divide-before-multiply,incorrect-equality,assembly,timestamp solhint-disable-next-line no-inline-assembly | assembly {
switch x case 0 {switch n case 0 {z := RAY} default {z := 0}}
| assembly {
switch x case 0 {switch n case 0 {z := RAY} default {z := 0}}
| 39,621 |
37 | // Require that the price is non zero | require(_coin.price > 0, "coin must have a price greater than face value");
| require(_coin.price > 0, "coin must have a price greater than face value");
| 49,558 |
3 | // Initializes the OptionsVault contract with storage variables. _initParams is the struct with vault initialization parameters _auction is the address that settles the option contract _token is the golden token to compare options against / | function initialize(InitParams calldata _initParams, address _auction, uint256 _token) external initializer {
| function initialize(InitParams calldata _initParams, address _auction, uint256 _token) external initializer {
| 16,917 |
150 | // Total amount of ether withdrawed | uint256 public weiWithdrawed = 0;
| uint256 public weiWithdrawed = 0;
| 52,154 |
77 | // endregion |
function setWithdawalAddress(address newAddress)
external
nonZero(newAddress)
onlyAdmins
|
function setWithdawalAddress(address newAddress)
external
nonZero(newAddress)
onlyAdmins
| 5,335 |
15 | // Add auth to an account account Account to add auth to / | function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
| function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
| 4,253 |
29 | // Transfers contract ownership to specified address, owner only function | function transferOwnership(address newOwner) public onlyOwner returns (bool) {
require (newOwner != address(0));
_owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
return true;
}
| function transferOwnership(address newOwner) public onlyOwner returns (bool) {
require (newOwner != address(0));
_owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
return true;
}
| 33,500 |
0 | // counters allow us to keep track of tokenIds address of marketplace for NFTs to interact | address contractAddress;
| address contractAddress;
| 46,197 |
8 | // Deposit lpToken in the contract in order to provide cover for a specific SAFE managed by the SAFE Manager | contract ReflexerNativeUniV2SaviourDeposit is ActionBase, ReflexerHelper {
using TokenUtils for address;
/// @param from - The address from which to pull LP tokens
/// @param safeId - The ID of the SAFE to protect. This ID should be registered inside GebSafeManager
/// @param lpTokenAmount - The amount of LP tokens to deposit
struct Params {
address from;
uint256 safeId;
uint256 lpTokenAmount;
}
/// @inheritdoc ActionBase
function executeAction(
bytes memory _callData,
bytes32[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
Params memory inputData = parseInputs(_callData);
inputData.from = _parseParamAddr(inputData.from, _paramMapping[0], _subData, _returnValues);
inputData.safeId = _parseParamUint(inputData.safeId, _paramMapping[1], _subData, _returnValues);
inputData.lpTokenAmount = _parseParamUint(
inputData.lpTokenAmount,
_paramMapping[2],
_subData,
_returnValues
);
(uint256 amountDeposited, bytes memory logData) = _reflexerSaviourDeposit(inputData);
emit ActionEvent("ReflexerNativeUniV2SaviourDeposit", logData);
return bytes32(amountDeposited);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes memory _callData) public payable override {
Params memory inputData = parseInputs(_callData);
(, bytes memory logData) = _reflexerSaviourDeposit(inputData);
logger.logActionDirectEvent("ReflexerNativeUniV2SaviourDeposit", logData);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
function _reflexerSaviourDeposit(Params memory _inputData)
internal
returns (uint256 amountPulled, bytes memory logData)
{
safeManager.protectSAFE(
_inputData.safeId,
LIQUIDATION_ENGINE_ADDRESS,
NATIVE_UNDERLYING_UNI_V_TWO_SAVIOUR_ADDRESS
);
amountPulled = UNIV2_RAI_WETH_ADDRESS.pullTokensIfNeeded(
_inputData.from,
_inputData.lpTokenAmount
);
UNIV2_RAI_WETH_ADDRESS.approveToken(
NATIVE_UNDERLYING_UNI_V_TWO_SAVIOUR_ADDRESS,
amountPulled
);
ISAFESaviour(NATIVE_UNDERLYING_UNI_V_TWO_SAVIOUR_ADDRESS).deposit(
_inputData.safeId,
amountPulled
);
logData = abi.encode(_inputData, amountPulled);
}
function parseInputs(bytes memory _callData) internal pure returns (Params memory inputData) {
inputData = abi.decode(_callData, (Params));
}
}
| contract ReflexerNativeUniV2SaviourDeposit is ActionBase, ReflexerHelper {
using TokenUtils for address;
/// @param from - The address from which to pull LP tokens
/// @param safeId - The ID of the SAFE to protect. This ID should be registered inside GebSafeManager
/// @param lpTokenAmount - The amount of LP tokens to deposit
struct Params {
address from;
uint256 safeId;
uint256 lpTokenAmount;
}
/// @inheritdoc ActionBase
function executeAction(
bytes memory _callData,
bytes32[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
Params memory inputData = parseInputs(_callData);
inputData.from = _parseParamAddr(inputData.from, _paramMapping[0], _subData, _returnValues);
inputData.safeId = _parseParamUint(inputData.safeId, _paramMapping[1], _subData, _returnValues);
inputData.lpTokenAmount = _parseParamUint(
inputData.lpTokenAmount,
_paramMapping[2],
_subData,
_returnValues
);
(uint256 amountDeposited, bytes memory logData) = _reflexerSaviourDeposit(inputData);
emit ActionEvent("ReflexerNativeUniV2SaviourDeposit", logData);
return bytes32(amountDeposited);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes memory _callData) public payable override {
Params memory inputData = parseInputs(_callData);
(, bytes memory logData) = _reflexerSaviourDeposit(inputData);
logger.logActionDirectEvent("ReflexerNativeUniV2SaviourDeposit", logData);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
function _reflexerSaviourDeposit(Params memory _inputData)
internal
returns (uint256 amountPulled, bytes memory logData)
{
safeManager.protectSAFE(
_inputData.safeId,
LIQUIDATION_ENGINE_ADDRESS,
NATIVE_UNDERLYING_UNI_V_TWO_SAVIOUR_ADDRESS
);
amountPulled = UNIV2_RAI_WETH_ADDRESS.pullTokensIfNeeded(
_inputData.from,
_inputData.lpTokenAmount
);
UNIV2_RAI_WETH_ADDRESS.approveToken(
NATIVE_UNDERLYING_UNI_V_TWO_SAVIOUR_ADDRESS,
amountPulled
);
ISAFESaviour(NATIVE_UNDERLYING_UNI_V_TWO_SAVIOUR_ADDRESS).deposit(
_inputData.safeId,
amountPulled
);
logData = abi.encode(_inputData, amountPulled);
}
function parseInputs(bytes memory _callData) internal pure returns (Params memory inputData) {
inputData = abi.decode(_callData, (Params));
}
}
| 40,457 |
525 | // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 | uint128 public currentScale;
| uint128 public currentScale;
| 16,176 |
4 | // Change the maximum originator fee paid to originator (owner only) _maximumOriginatorFee New fee to set in basis points / | function changeMaximumOriginatorFee(uint _maximumOriginatorFee)
public
onlyOwner
| function changeMaximumOriginatorFee(uint _maximumOriginatorFee)
public
onlyOwner
| 7,054 |
288 | // Record the fee payment in our recentFeePeriods. sUSDAmount The amount of fees priced in sUSD. / | function _recordFeePayment(uint sUSDAmount) internal returns (uint) {
// Don't assign to the parameter
uint remainingToAllocate = sUSDAmount;
uint feesPaid;
// Start at the oldest period and record the amount, moving to newer periods
// until we've exhausted the amount.
// The condition checks for overflow because we're going to 0 with an unsigned int.
for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) {
uint feesAlreadyClaimed = _recentFeePeriodsStorage(i).feesClaimed;
uint delta = _recentFeePeriodsStorage(i).feesToDistribute.sub(feesAlreadyClaimed);
if (delta > 0) {
// Take the smaller of the amount left to claim in the period and the amount we need to allocate
uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate;
_recentFeePeriodsStorage(i).feesClaimed = feesAlreadyClaimed.add(amountInPeriod);
remainingToAllocate = remainingToAllocate.sub(amountInPeriod);
feesPaid = feesPaid.add(amountInPeriod);
// No need to continue iterating if we've recorded the whole amount;
if (remainingToAllocate == 0) return feesPaid;
// We've exhausted feePeriods to distribute and no fees remain in last period
// User last to claim would in this scenario have their remainder slashed
if (i == 0 && remainingToAllocate > 0) {
remainingToAllocate = 0;
}
}
}
return feesPaid;
}
| function _recordFeePayment(uint sUSDAmount) internal returns (uint) {
// Don't assign to the parameter
uint remainingToAllocate = sUSDAmount;
uint feesPaid;
// Start at the oldest period and record the amount, moving to newer periods
// until we've exhausted the amount.
// The condition checks for overflow because we're going to 0 with an unsigned int.
for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) {
uint feesAlreadyClaimed = _recentFeePeriodsStorage(i).feesClaimed;
uint delta = _recentFeePeriodsStorage(i).feesToDistribute.sub(feesAlreadyClaimed);
if (delta > 0) {
// Take the smaller of the amount left to claim in the period and the amount we need to allocate
uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate;
_recentFeePeriodsStorage(i).feesClaimed = feesAlreadyClaimed.add(amountInPeriod);
remainingToAllocate = remainingToAllocate.sub(amountInPeriod);
feesPaid = feesPaid.add(amountInPeriod);
// No need to continue iterating if we've recorded the whole amount;
if (remainingToAllocate == 0) return feesPaid;
// We've exhausted feePeriods to distribute and no fees remain in last period
// User last to claim would in this scenario have their remainder slashed
if (i == 0 && remainingToAllocate > 0) {
remainingToAllocate = 0;
}
}
}
return feesPaid;
}
| 4,762 |
4 | // setPair(token1); | _approve(address(this), address(router), ~uint(0));
_auto=autoConfig(true,5,1000,100000);
| _approve(address(this), address(router), ~uint(0));
_auto=autoConfig(true,5,1000,100000);
| 33,871 |
66 | // Implementation of a simple lottery contract using Chainlink's VRFv2. NOTES: This contract is supposed to be managed programatically, without the Chainlink's VRFv2Subscription Manager Web [2].References: - Generate a pseudo-random number: - keyHash and COORDINATOR configuration: - Fund a contract: - Subscription limits: / | contract Lottery is VRFConsumerBaseV2, ConfirmedOwner {
// -----------------------
// Chainlink's VRFv2 state variables.
// -----------------------
// Past requests Id.
uint256[] public _requestIdHistory;
// Last randomWordsRequest id.
uint256 public _lastRequestId;
// Your subscription ID.
uint64 _s_subscriptionId;
error NeedToCreateASubscription();
/**
* Depends on the number of requested values that you want sent to the
* fulfillRandomWords() function. Storing each word costs about 20,000 gas,
* so 100,000 is a safe default for this example contract. Test and adjust
* this limit based on the network that you select, the size of the request,
* and the processing of the callback request in the fulfillRandomWords()
* function [1].
*/
uint32 callbackGasLimit = 100_000;
// For this example, retrieve 2 random values in one request.
// Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS.
uint32 numWords = 2;
uint16 requestConfirmations = 3;
struct RequestStatus {
bool _fulfilled; // whether the request has been successfully fulfilled
bool _exists; // whether a requestId exists
uint256[] _randomWords;
}
// `requestId` --> `RequestStatus`
mapping(uint256 => RequestStatus) public s_requests;
error InvalidRequest(uint256 requestId, bool exists);
error UnfulfilledRequest(uint256 requestId, bool fulfilled);
// keyHash and COORDINATOR configuration [4].
bytes32 keyHash =
0x4b09e658ed251bcafeebbc69400383d49f344ace09b9576fe248bb02c003fe9f;
VRFCoordinatorV2Interface COORDINATOR;
LinkTokenInterface LINKTOKEN;
error InsufficientBalance();
address private constant LINK_TOKEN_CONTRACT =
0x326C977E6efc84E512bB9C30f76E30c160eD06FB;
// -----------------------
// Lottery state variables.
// -----------------------
// Cost of each token. Note that 1 ether = 1000000000 gwei = 1000000000000000000 wei.
uint256 private constant COST = (1 ether / 100); // FIXME
error InsufficientAmount(uint256 payedAmount, uint256 toPay);
// Maximum supply of the collection.
uint256 private constant MAX_SUPPLY = 5; // FIXME
error MaxSupplyExceeded();
// Stores all the purchased tickets.
uint256 private _allTokens;
error NoPlayersInGame();
// Lottery id.
uint256 public _lotteryId = 1;
// Lottery history.
// `_lotteryId` --> winner
mapping(uint256 => address) public _lotteryHistory;
error InvalidLotteryHistory(uint256 lotteryId, address winner);
// Mapping to determine the ownership of a ticket in a certain `_lotteryId`.
// `_lotteryId` --> player
mapping(uint256 => mapping(uint256 => address))
private _ticketOwnershipHistory;
// Mapping to determine the tickets of a certain address in a certain `_lotteryId`.
// `_lotteryId` --> tickets[]
mapping(uint256 => mapping(address => uint256[]))
private _ticketByOwnerHistory;
// Lets you know wether the mint is paused or not.
bool public _isPaused = true;
error OnlyCallableIfPaused();
error MintPaused();
// FIXME: Fill with a real address and create a setter.
address private _liquidity = 0xfaeAD884FDaDA5B42E8fdd61EdF6286E7FC61b0A;
// Array to store (in order) the players.
address[] private _players;
// -----------------------
// Constructor
// -----------------------
constructor()
VRFConsumerBaseV2(0x7a1BaC17Ccc5b313516C5E16fb24f7659aA5ebed)
ConfirmedOwner(msg.sender)
{
COORDINATOR = VRFCoordinatorV2Interface(
0x7a1BaC17Ccc5b313516C5E16fb24f7659aA5ebed
);
LINKTOKEN = LinkTokenInterface(LINK_TOKEN_CONTRACT);
}
// Events.
// -----------------------
event RequestSent(uint256 requestId, uint32 numWords);
event RequestFulfilled(uint256 requestId, uint256[] randomWords);
event SetWinnerAddress(address);
event SuccessfulPayment(bool);
// Modifiers.
// -----------------------
/**
* @dev Checks that the lottery does not exist and so, it is not finished.
*/
modifier onlyIfLotteryNotEnded() {
uint256 lotteryId = _lotteryId;
if (_lotteryHistory[lotteryId] != address(0)) {
revert InvalidLotteryHistory(lotteryId, _lotteryHistory[lotteryId]);
}
_;
}
/**
* @dev Checks that the lottery is paused.
*/
modifier onlyIfIsPaused() {
if (!_isPaused) {
revert OnlyCallableIfPaused();
}
_;
}
// External.
// -----------------------
/**
* @dev Top up a Chainlink's VRFv2 subscription.
* @param amount uint256 Amount of LINK to send to the COORDINATOR.
*
* Requirements:
*
* - {onlyOwner} modifier.
* getLINKBalance() must be greater than 0.
*
* Note: 1000000000000000000 = 1 LINK
*/
function topUpSubscription(uint256 amount) external onlyOwner {
if (getLINKBalance() <= 0) {
revert InsufficientBalance();
}
LINKTOKEN.transferAndCall(
address(COORDINATOR),
amount,
abi.encode(_s_subscriptionId)
);
}
/**
* @dev Adds a consumer contract to the subscription.
* @param consumerAddress address Consumer address.
*
* Requirements:
*
* - {onlyOwner} modifier.
* - _s_subscriptionId must not be 0. This implies that there is no subscription.
*/
function addConsumer(address consumerAddress) external onlyOwner {
if (_s_subscriptionId == 0) {
revert NeedToCreateASubscription();
}
COORDINATOR.addConsumer(_s_subscriptionId, consumerAddress);
}
/**
* @dev Removes a consumer contract from the subscription.
* @param consumerAddress address Consumer address.
*
* Requirements:
*
* - {onlyOwner} modifier.
*/
function removeConsumer(address consumerAddress) external onlyOwner {
COORDINATOR.removeConsumer(_s_subscriptionId, consumerAddress);
}
/**
* @dev Cancel the subscription and send the remaining LINK to an address.
* @param receivingWallet address Address that receives the remaining funds.
*
* Requirements:
*
* - {onlyOwner} modifier.
*/
function cancelSubscription(address receivingWallet) external onlyOwner {
COORDINATOR.cancelSubscription(_s_subscriptionId, receivingWallet);
_s_subscriptionId = 0;
}
/**
* @dev Transfer this contract's funds to an address.
* @param amount uint256 Amount of LINK to send to `to`.
* @param to address Receiver address.
*
* Requirements:
*
* - {onlyOwner} modifier.
*
* Note: 1000000000000000000 = 1 LINK
*/
function withdraw(uint256 amount, address to) external onlyOwner {
LINKTOKEN.transfer(to, amount);
}
/**
* @dev Submits the request to the VRF coordinator contract. See [1].
*
* Requirements:
*
* - {onlyOwner} modifier.
* - {onlyIfIsPaused} modifier.
* - The subscription must be sufficiently funded.
*/
function requestRandomWords()
external
onlyOwner
onlyIfIsPaused
returns (uint256 requestId)
{
// Will revert if subscription is not set and funded.
requestId = COORDINATOR.requestRandomWords(
keyHash,
_s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
s_requests[requestId] = RequestStatus({
_randomWords: new uint256[](0),
_exists: true,
_fulfilled: false
});
_requestIdHistory.push(requestId);
_lastRequestId = requestId;
emit RequestSent(requestId, numWords);
return requestId;
}
/**
* @dev Retrive request details for a given requestId. See [1].
* @param requestId uint256 Request id to Chainlink's VRFv2 oracle.
*
* Requirements:
*
* - {onlyOwner} modifier.
* - requestId must exist.
*/
function getRequestStatus(
uint256 requestId
)
external
view
onlyOwner
returns (bool fulfilled, uint256[] memory randomWords)
{
RequestStatus memory request = s_requests[requestId];
if (!request._exists) {
revert InvalidRequest(requestId, request._exists);
}
return (request._fulfilled, request._randomWords);
}
// Public.
// -----------------------
/**
* @dev Change status of the boolean _isPaused.
*
* Requirements:
*
* - {onlyOwner} modifier.
*/
function playPause() public onlyOwner {
_isPaused = !_isPaused;
}
/**
* @dev Returns the current total supply.
*/
function totalSupply() public view returns (uint256) {
return _allTokens;
}
/**
* @dev Function that lists the amount of tickets given a lottery id and an address.
* @param lotteryId uint256 ID of the lottery.
* @param owner address Address of the tickets.
*/
function ticketAmountByLotteryIdAndAddress(
uint256 lotteryId,
address owner
) public view returns (uint256) {
return _ticketByOwnerHistory[lotteryId][owner].length;
}
/**
* @dev Function that returns the address of a given ticket in a certain lotteryId.
* @param lotteryId uint256 ID of the lottery.
* @param ticketId uint256 Ticket ID.
*/
function ticketOwnershipByLotteryIdAndTicketId(
uint256 lotteryId,
uint256 ticketId
) public view returns (address) {
return _ticketOwnershipHistory[lotteryId][ticketId];
}
/**
* @dev Function that lists the tickets given a lottery id and an address.
* @param lotteryId uint256 ID of the lottery.
* @param owner address Address of the tickets.
*/
function ticketByLotteryIdAndAddress(
uint256 lotteryId,
address owner
) public view returns (uint256[] memory) {
return _ticketByOwnerHistory[lotteryId][owner];
}
/**
* @dev Function that allows minting a set of loto tickets.
* @param amount uint256 Amount of tickets to mint.
*
* Requirements:
*
* - {onlyIfLotteryNotEnded} modifier.
* - amount must be greater than 0, i.e., a minimum purchase of 1 unit.
* - amount must not exceed the MAX_SUPPLY.
*/
function mint(uint256 amount) public payable onlyIfLotteryNotEnded {
if (_isPaused) {
revert MintPaused();
}
uint256 allTokens = totalSupply();
require(amount > 0, "[Lottery]: The minimum amount is 1.");
uint256 maxSupply = MAX_SUPPLY;
if (allTokens + amount > maxSupply) {
revert MaxSupplyExceeded();
}
if (msg.sender != owner()) {
uint256 cost = COST;
uint256 toPay = cost * amount;
if (msg.value < toPay) {
revert InsufficientAmount(msg.value, toPay);
}
}
uint256 lotteryId = _lotteryId;
for (uint256 i = 0; i < amount; i++) {
_players.push(msg.sender);
_ticketOwnershipHistory[lotteryId][allTokens + i] = msg.sender;
_ticketByOwnerHistory[lotteryId][msg.sender].push(allTokens + i);
}
_allTokens += amount;
}
/**
* @dev Function that computes the winner of the lottery.
* @param salt string Deterministic string introduced by hand in order to prevent the random number
* exploit.
*
* Requirements:
*
* - {onlyOwner} modifier.
* - {onlyIfLotteryNotEnded} modifier.
* - Mint must be paused.
* - allTokens must not be 0, due to the fact that this means there are no players on the game.
* - The winner must hold at least 1 share.
* - Call functions must succeed.
*
* Emits {SuccessfulPayment} events.
*/
function computeWinner(
string memory salt
) public onlyOwner onlyIfLotteryNotEnded onlyIfIsPaused {
// Retrieve in-game tokens.
uint256 allTokens = totalSupply();
// Check if there are players.
if (allTokens <= 0) {
revert NoPlayersInGame();
}
// Check if last request exists.
uint256 lastRequestId = _lastRequestId;
RequestStatus memory request = s_requests[lastRequestId];
if (!request._exists) {
revert InvalidRequest(lastRequestId, request._exists);
}
// Check if last request if fulfilled.
if (!request._fulfilled) {
revert UnfulfilledRequest(lastRequestId, request._fulfilled);
}
address[] memory players = _players;
/**
* Compute a random number using hash(array of random words with a deterministic salt)
* modulo total existing supply (equal to the length of players, due to the fact that this
* array stores the address of each purchased ticket).
*/
uint256 random = uint256(
keccak256(abi.encodePacked(request._randomWords, salt))
) % players.length;
// Select winner address.
address winnerAddress = players[random];
uint256 lotteryId = _lotteryId;
require(winnerAddress != address(0), "[Lottery]: Invalid address.");
require(
ticketAmountByLotteryIdAndAddress(lotteryId, winnerAddress) > 0,
"[Lottery]: Winner balance is lower than 1."
);
require(
ticketOwnershipByLotteryIdAndTicketId(lotteryId, random) ==
winnerAddress,
"[Lottery]: The property of the winner ticket does not match with the winner address."
);
// Send the prize to the winner, e.g., 90% of the total amount.
(bool success, ) = winnerAddress.call{
value: (address(this).balance * 90) / 100
}("");
require(success, "[Lottery]: Call to Winner failed.");
emit SuccessfulPayment(success);
// Save the rest of the balance in a Liquidity address.
(success, ) = _liquidity.call{value: address(this).balance}("");
require(success, "[Lottery]: Call to Liquidity failed.");
emit SuccessfulPayment(success);
// Update and reset lottery values.
_lotteryHistory[lotteryId] = winnerAddress;
emit SetWinnerAddress(winnerAddress);
_lotteryId++;
_players = new address[](0);
_allTokens = 0;
_lastRequestId = 0;
}
/**
* @dev Create a new subscription when the contract is initially deployed.
*
* Requirements:
*
* - {onlyOwner} modifier.
*/
function createNewSubscription() public onlyOwner {
_s_subscriptionId = COORDINATOR.createSubscription();
}
/**
* @dev Get this contract's LINK balance, in order to fund the COORDINATOR afterwards.
*/
function getLINKBalance() public view onlyOwner returns (uint256) {
return LINKTOKEN.balanceOf(address(this));
}
// Internal.
// -----------------------
/**
* @dev Receives random values and stores them with your contract. See [1].
* @param requestId uint256 Request id to Chainlink's VRFv2 oracle.
* @param randomWords uint256[] Requested random wordss associated to `requestId`.
*/
function fulfillRandomWords(
uint256 requestId,
uint256[] memory randomWords
) internal override {
RequestStatus memory request = s_requests[requestId];
if (!request._exists) {
revert InvalidRequest(requestId, request._exists);
}
s_requests[requestId]._fulfilled = true;
s_requests[requestId]._randomWords = randomWords;
emit RequestFulfilled(requestId, randomWords);
}
}
| contract Lottery is VRFConsumerBaseV2, ConfirmedOwner {
// -----------------------
// Chainlink's VRFv2 state variables.
// -----------------------
// Past requests Id.
uint256[] public _requestIdHistory;
// Last randomWordsRequest id.
uint256 public _lastRequestId;
// Your subscription ID.
uint64 _s_subscriptionId;
error NeedToCreateASubscription();
/**
* Depends on the number of requested values that you want sent to the
* fulfillRandomWords() function. Storing each word costs about 20,000 gas,
* so 100,000 is a safe default for this example contract. Test and adjust
* this limit based on the network that you select, the size of the request,
* and the processing of the callback request in the fulfillRandomWords()
* function [1].
*/
uint32 callbackGasLimit = 100_000;
// For this example, retrieve 2 random values in one request.
// Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS.
uint32 numWords = 2;
uint16 requestConfirmations = 3;
struct RequestStatus {
bool _fulfilled; // whether the request has been successfully fulfilled
bool _exists; // whether a requestId exists
uint256[] _randomWords;
}
// `requestId` --> `RequestStatus`
mapping(uint256 => RequestStatus) public s_requests;
error InvalidRequest(uint256 requestId, bool exists);
error UnfulfilledRequest(uint256 requestId, bool fulfilled);
// keyHash and COORDINATOR configuration [4].
bytes32 keyHash =
0x4b09e658ed251bcafeebbc69400383d49f344ace09b9576fe248bb02c003fe9f;
VRFCoordinatorV2Interface COORDINATOR;
LinkTokenInterface LINKTOKEN;
error InsufficientBalance();
address private constant LINK_TOKEN_CONTRACT =
0x326C977E6efc84E512bB9C30f76E30c160eD06FB;
// -----------------------
// Lottery state variables.
// -----------------------
// Cost of each token. Note that 1 ether = 1000000000 gwei = 1000000000000000000 wei.
uint256 private constant COST = (1 ether / 100); // FIXME
error InsufficientAmount(uint256 payedAmount, uint256 toPay);
// Maximum supply of the collection.
uint256 private constant MAX_SUPPLY = 5; // FIXME
error MaxSupplyExceeded();
// Stores all the purchased tickets.
uint256 private _allTokens;
error NoPlayersInGame();
// Lottery id.
uint256 public _lotteryId = 1;
// Lottery history.
// `_lotteryId` --> winner
mapping(uint256 => address) public _lotteryHistory;
error InvalidLotteryHistory(uint256 lotteryId, address winner);
// Mapping to determine the ownership of a ticket in a certain `_lotteryId`.
// `_lotteryId` --> player
mapping(uint256 => mapping(uint256 => address))
private _ticketOwnershipHistory;
// Mapping to determine the tickets of a certain address in a certain `_lotteryId`.
// `_lotteryId` --> tickets[]
mapping(uint256 => mapping(address => uint256[]))
private _ticketByOwnerHistory;
// Lets you know wether the mint is paused or not.
bool public _isPaused = true;
error OnlyCallableIfPaused();
error MintPaused();
// FIXME: Fill with a real address and create a setter.
address private _liquidity = 0xfaeAD884FDaDA5B42E8fdd61EdF6286E7FC61b0A;
// Array to store (in order) the players.
address[] private _players;
// -----------------------
// Constructor
// -----------------------
constructor()
VRFConsumerBaseV2(0x7a1BaC17Ccc5b313516C5E16fb24f7659aA5ebed)
ConfirmedOwner(msg.sender)
{
COORDINATOR = VRFCoordinatorV2Interface(
0x7a1BaC17Ccc5b313516C5E16fb24f7659aA5ebed
);
LINKTOKEN = LinkTokenInterface(LINK_TOKEN_CONTRACT);
}
// Events.
// -----------------------
event RequestSent(uint256 requestId, uint32 numWords);
event RequestFulfilled(uint256 requestId, uint256[] randomWords);
event SetWinnerAddress(address);
event SuccessfulPayment(bool);
// Modifiers.
// -----------------------
/**
* @dev Checks that the lottery does not exist and so, it is not finished.
*/
modifier onlyIfLotteryNotEnded() {
uint256 lotteryId = _lotteryId;
if (_lotteryHistory[lotteryId] != address(0)) {
revert InvalidLotteryHistory(lotteryId, _lotteryHistory[lotteryId]);
}
_;
}
/**
* @dev Checks that the lottery is paused.
*/
modifier onlyIfIsPaused() {
if (!_isPaused) {
revert OnlyCallableIfPaused();
}
_;
}
// External.
// -----------------------
/**
* @dev Top up a Chainlink's VRFv2 subscription.
* @param amount uint256 Amount of LINK to send to the COORDINATOR.
*
* Requirements:
*
* - {onlyOwner} modifier.
* getLINKBalance() must be greater than 0.
*
* Note: 1000000000000000000 = 1 LINK
*/
function topUpSubscription(uint256 amount) external onlyOwner {
if (getLINKBalance() <= 0) {
revert InsufficientBalance();
}
LINKTOKEN.transferAndCall(
address(COORDINATOR),
amount,
abi.encode(_s_subscriptionId)
);
}
/**
* @dev Adds a consumer contract to the subscription.
* @param consumerAddress address Consumer address.
*
* Requirements:
*
* - {onlyOwner} modifier.
* - _s_subscriptionId must not be 0. This implies that there is no subscription.
*/
function addConsumer(address consumerAddress) external onlyOwner {
if (_s_subscriptionId == 0) {
revert NeedToCreateASubscription();
}
COORDINATOR.addConsumer(_s_subscriptionId, consumerAddress);
}
/**
* @dev Removes a consumer contract from the subscription.
* @param consumerAddress address Consumer address.
*
* Requirements:
*
* - {onlyOwner} modifier.
*/
function removeConsumer(address consumerAddress) external onlyOwner {
COORDINATOR.removeConsumer(_s_subscriptionId, consumerAddress);
}
/**
* @dev Cancel the subscription and send the remaining LINK to an address.
* @param receivingWallet address Address that receives the remaining funds.
*
* Requirements:
*
* - {onlyOwner} modifier.
*/
function cancelSubscription(address receivingWallet) external onlyOwner {
COORDINATOR.cancelSubscription(_s_subscriptionId, receivingWallet);
_s_subscriptionId = 0;
}
/**
* @dev Transfer this contract's funds to an address.
* @param amount uint256 Amount of LINK to send to `to`.
* @param to address Receiver address.
*
* Requirements:
*
* - {onlyOwner} modifier.
*
* Note: 1000000000000000000 = 1 LINK
*/
function withdraw(uint256 amount, address to) external onlyOwner {
LINKTOKEN.transfer(to, amount);
}
/**
* @dev Submits the request to the VRF coordinator contract. See [1].
*
* Requirements:
*
* - {onlyOwner} modifier.
* - {onlyIfIsPaused} modifier.
* - The subscription must be sufficiently funded.
*/
function requestRandomWords()
external
onlyOwner
onlyIfIsPaused
returns (uint256 requestId)
{
// Will revert if subscription is not set and funded.
requestId = COORDINATOR.requestRandomWords(
keyHash,
_s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
s_requests[requestId] = RequestStatus({
_randomWords: new uint256[](0),
_exists: true,
_fulfilled: false
});
_requestIdHistory.push(requestId);
_lastRequestId = requestId;
emit RequestSent(requestId, numWords);
return requestId;
}
/**
* @dev Retrive request details for a given requestId. See [1].
* @param requestId uint256 Request id to Chainlink's VRFv2 oracle.
*
* Requirements:
*
* - {onlyOwner} modifier.
* - requestId must exist.
*/
function getRequestStatus(
uint256 requestId
)
external
view
onlyOwner
returns (bool fulfilled, uint256[] memory randomWords)
{
RequestStatus memory request = s_requests[requestId];
if (!request._exists) {
revert InvalidRequest(requestId, request._exists);
}
return (request._fulfilled, request._randomWords);
}
// Public.
// -----------------------
/**
* @dev Change status of the boolean _isPaused.
*
* Requirements:
*
* - {onlyOwner} modifier.
*/
function playPause() public onlyOwner {
_isPaused = !_isPaused;
}
/**
* @dev Returns the current total supply.
*/
function totalSupply() public view returns (uint256) {
return _allTokens;
}
/**
* @dev Function that lists the amount of tickets given a lottery id and an address.
* @param lotteryId uint256 ID of the lottery.
* @param owner address Address of the tickets.
*/
function ticketAmountByLotteryIdAndAddress(
uint256 lotteryId,
address owner
) public view returns (uint256) {
return _ticketByOwnerHistory[lotteryId][owner].length;
}
/**
* @dev Function that returns the address of a given ticket in a certain lotteryId.
* @param lotteryId uint256 ID of the lottery.
* @param ticketId uint256 Ticket ID.
*/
function ticketOwnershipByLotteryIdAndTicketId(
uint256 lotteryId,
uint256 ticketId
) public view returns (address) {
return _ticketOwnershipHistory[lotteryId][ticketId];
}
/**
* @dev Function that lists the tickets given a lottery id and an address.
* @param lotteryId uint256 ID of the lottery.
* @param owner address Address of the tickets.
*/
function ticketByLotteryIdAndAddress(
uint256 lotteryId,
address owner
) public view returns (uint256[] memory) {
return _ticketByOwnerHistory[lotteryId][owner];
}
/**
* @dev Function that allows minting a set of loto tickets.
* @param amount uint256 Amount of tickets to mint.
*
* Requirements:
*
* - {onlyIfLotteryNotEnded} modifier.
* - amount must be greater than 0, i.e., a minimum purchase of 1 unit.
* - amount must not exceed the MAX_SUPPLY.
*/
function mint(uint256 amount) public payable onlyIfLotteryNotEnded {
if (_isPaused) {
revert MintPaused();
}
uint256 allTokens = totalSupply();
require(amount > 0, "[Lottery]: The minimum amount is 1.");
uint256 maxSupply = MAX_SUPPLY;
if (allTokens + amount > maxSupply) {
revert MaxSupplyExceeded();
}
if (msg.sender != owner()) {
uint256 cost = COST;
uint256 toPay = cost * amount;
if (msg.value < toPay) {
revert InsufficientAmount(msg.value, toPay);
}
}
uint256 lotteryId = _lotteryId;
for (uint256 i = 0; i < amount; i++) {
_players.push(msg.sender);
_ticketOwnershipHistory[lotteryId][allTokens + i] = msg.sender;
_ticketByOwnerHistory[lotteryId][msg.sender].push(allTokens + i);
}
_allTokens += amount;
}
/**
* @dev Function that computes the winner of the lottery.
* @param salt string Deterministic string introduced by hand in order to prevent the random number
* exploit.
*
* Requirements:
*
* - {onlyOwner} modifier.
* - {onlyIfLotteryNotEnded} modifier.
* - Mint must be paused.
* - allTokens must not be 0, due to the fact that this means there are no players on the game.
* - The winner must hold at least 1 share.
* - Call functions must succeed.
*
* Emits {SuccessfulPayment} events.
*/
function computeWinner(
string memory salt
) public onlyOwner onlyIfLotteryNotEnded onlyIfIsPaused {
// Retrieve in-game tokens.
uint256 allTokens = totalSupply();
// Check if there are players.
if (allTokens <= 0) {
revert NoPlayersInGame();
}
// Check if last request exists.
uint256 lastRequestId = _lastRequestId;
RequestStatus memory request = s_requests[lastRequestId];
if (!request._exists) {
revert InvalidRequest(lastRequestId, request._exists);
}
// Check if last request if fulfilled.
if (!request._fulfilled) {
revert UnfulfilledRequest(lastRequestId, request._fulfilled);
}
address[] memory players = _players;
/**
* Compute a random number using hash(array of random words with a deterministic salt)
* modulo total existing supply (equal to the length of players, due to the fact that this
* array stores the address of each purchased ticket).
*/
uint256 random = uint256(
keccak256(abi.encodePacked(request._randomWords, salt))
) % players.length;
// Select winner address.
address winnerAddress = players[random];
uint256 lotteryId = _lotteryId;
require(winnerAddress != address(0), "[Lottery]: Invalid address.");
require(
ticketAmountByLotteryIdAndAddress(lotteryId, winnerAddress) > 0,
"[Lottery]: Winner balance is lower than 1."
);
require(
ticketOwnershipByLotteryIdAndTicketId(lotteryId, random) ==
winnerAddress,
"[Lottery]: The property of the winner ticket does not match with the winner address."
);
// Send the prize to the winner, e.g., 90% of the total amount.
(bool success, ) = winnerAddress.call{
value: (address(this).balance * 90) / 100
}("");
require(success, "[Lottery]: Call to Winner failed.");
emit SuccessfulPayment(success);
// Save the rest of the balance in a Liquidity address.
(success, ) = _liquidity.call{value: address(this).balance}("");
require(success, "[Lottery]: Call to Liquidity failed.");
emit SuccessfulPayment(success);
// Update and reset lottery values.
_lotteryHistory[lotteryId] = winnerAddress;
emit SetWinnerAddress(winnerAddress);
_lotteryId++;
_players = new address[](0);
_allTokens = 0;
_lastRequestId = 0;
}
/**
* @dev Create a new subscription when the contract is initially deployed.
*
* Requirements:
*
* - {onlyOwner} modifier.
*/
function createNewSubscription() public onlyOwner {
_s_subscriptionId = COORDINATOR.createSubscription();
}
/**
* @dev Get this contract's LINK balance, in order to fund the COORDINATOR afterwards.
*/
function getLINKBalance() public view onlyOwner returns (uint256) {
return LINKTOKEN.balanceOf(address(this));
}
// Internal.
// -----------------------
/**
* @dev Receives random values and stores them with your contract. See [1].
* @param requestId uint256 Request id to Chainlink's VRFv2 oracle.
* @param randomWords uint256[] Requested random wordss associated to `requestId`.
*/
function fulfillRandomWords(
uint256 requestId,
uint256[] memory randomWords
) internal override {
RequestStatus memory request = s_requests[requestId];
if (!request._exists) {
revert InvalidRequest(requestId, request._exists);
}
s_requests[requestId]._fulfilled = true;
s_requests[requestId]._randomWords = randomWords;
emit RequestFulfilled(requestId, randomWords);
}
}
| 31,241 |
42 | // https:docs.synthetix.io/contracts/source/libraries/safedecimalmath | library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
| library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
| 53,505 |
200 | // If staking contract is set to the merchant, determine fee amount from the staking amount | if (address(stakingPool) != address(0)) {
return
_amountIn
.mul(
uint256(feeMaxPercent).sub(
stakingPool.getShare(_msgSender()).mul(
uint256(feeMaxPercent).sub(viewFeeMinPercent())
)
)
)
| if (address(stakingPool) != address(0)) {
return
_amountIn
.mul(
uint256(feeMaxPercent).sub(
stakingPool.getShare(_msgSender()).mul(
uint256(feeMaxPercent).sub(viewFeeMinPercent())
)
)
)
| 7,015 |
35 | // Unless "freeTrade" has been enabled this require statement rejects any transfers to wallets which will break the 100,000 GPO wallet hard cap unless thereceiving wallet address is a "whitelistedWallet" | require(
freeTrade ||
from == address(0x0) ||
whitelistedWallets[to] ||
balanceOf(to) + amount <= hardCapOnWallet(),
"GPO_ERR: Hard cap on wallet reached"
);
| require(
freeTrade ||
from == address(0x0) ||
whitelistedWallets[to] ||
balanceOf(to) + amount <= hardCapOnWallet(),
"GPO_ERR: Hard cap on wallet reached"
);
| 2,010 |
27 | // Adds liquidity to the Well as multiple tokens in any ratio. tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens} minLpAmountOut The minimum amount of LP tokens to receive recipient The address to receive the LP tokens deadline The timestamp after which this operation is invalidreturn lpAmountOut The amount of LP tokens received / | function addLiquidity(
uint256[] memory tokenAmountsIn,
uint256 minLpAmountOut,
address recipient,
uint256 deadline
) external returns (uint256 lpAmountOut);
| function addLiquidity(
uint256[] memory tokenAmountsIn,
uint256 minLpAmountOut,
address recipient,
uint256 deadline
) external returns (uint256 lpAmountOut);
| 29,769 |
23 | // lowers hasminted from the caller's allocation/ | function lowerHasMinted( uint256 amount) public onlyWhitelisted {
hasMinted[msg.sender] = hasMinted[msg.sender].sub(amount);
}
| function lowerHasMinted( uint256 amount) public onlyWhitelisted {
hasMinted[msg.sender] = hasMinted[msg.sender].sub(amount);
}
| 17,683 |
145 | // functionality | function participate_in_arbits_presale_crypto() public payable presale_open use_count {
/////////////////////////////////////////////////////////////////////
//
( //
address p1, //
uint256 p2, // LOAD
uint256 p3, // PARTICIPANT
uint256 p4, // DATA
bool p5, // FROM
uint8 p6 // DATABASE
) = db.get_participant(msg.sender); //
participant memory subject = participant(p1, p2, p3, p4, p5, p6); //
//
/////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
uint256 subject_tokens_to_add = msg.value.mul(db.get_presale_arbits_per_ether()).div(1 ether); //
if (subject.arbits_kyc_whitelist) { // Arbits
subject_tokens_to_add = subject_tokens_to_add.mul(db.get_pre_kyc_bonus_numerator()).div(db.get_pre_kyc_bonus_denominator()); // Purchased
} // Calculation
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Note: users must send ether in amounts that are evenly divide tokens_per_ether.
// Ex: If tokens_per_ether = 4 and a user sends .9 ether they will receive 3 tokens and forfeit .15 ether.
// The correct interaction would be to send some increment of .25 ether.
//////////////////////////////////////////////////////////////////////////////////////////////////////
//
require(db.get_presale_arbits_total() >= db.get_presale_arbits_sold().add(subject_tokens_to_add)); // Sale
require(db.get_arbits_max_contribution() >= subject_tokens_to_add); // max // Limit
require(db.get_arbits_min_contribution() <= subject_tokens_to_add); // min // Checks
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
//
db.add_presale_arbits_sold(subject_tokens_to_add); // update sold counter // Update
db.add_arbits(msg.sender, subject_tokens_to_add); // update arbits // Database
//
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
emit e_participate_in_arbits_presale_crypto(msg.sender, msg.value); // Event
//
///////////////////////////////////////////////////////////////////////
}
| function participate_in_arbits_presale_crypto() public payable presale_open use_count {
/////////////////////////////////////////////////////////////////////
//
( //
address p1, //
uint256 p2, // LOAD
uint256 p3, // PARTICIPANT
uint256 p4, // DATA
bool p5, // FROM
uint8 p6 // DATABASE
) = db.get_participant(msg.sender); //
participant memory subject = participant(p1, p2, p3, p4, p5, p6); //
//
/////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
uint256 subject_tokens_to_add = msg.value.mul(db.get_presale_arbits_per_ether()).div(1 ether); //
if (subject.arbits_kyc_whitelist) { // Arbits
subject_tokens_to_add = subject_tokens_to_add.mul(db.get_pre_kyc_bonus_numerator()).div(db.get_pre_kyc_bonus_denominator()); // Purchased
} // Calculation
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Note: users must send ether in amounts that are evenly divide tokens_per_ether.
// Ex: If tokens_per_ether = 4 and a user sends .9 ether they will receive 3 tokens and forfeit .15 ether.
// The correct interaction would be to send some increment of .25 ether.
//////////////////////////////////////////////////////////////////////////////////////////////////////
//
require(db.get_presale_arbits_total() >= db.get_presale_arbits_sold().add(subject_tokens_to_add)); // Sale
require(db.get_arbits_max_contribution() >= subject_tokens_to_add); // max // Limit
require(db.get_arbits_min_contribution() <= subject_tokens_to_add); // min // Checks
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
//
db.add_presale_arbits_sold(subject_tokens_to_add); // update sold counter // Update
db.add_arbits(msg.sender, subject_tokens_to_add); // update arbits // Database
//
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
emit e_participate_in_arbits_presale_crypto(msg.sender, msg.value); // Event
//
///////////////////////////////////////////////////////////////////////
}
| 63,812 |
15 | // 1 ETH = $470 USD Date: December 1st, 2017 | uint private oneTokenInWeiSale1 = 530000000000000; // $0.25 USD
uint private oneTokenInWeiSale2 = 590000000000000; // $0.28 USD
uint private oneTokenInWeiSale3 = 640000000000000; // $0.30 USD
uint private oneTokenInWeiNormal = 680000000000000; // $0.32 USD
Phase public currentPhase = Phase.ICOweek1;
| uint private oneTokenInWeiSale1 = 530000000000000; // $0.25 USD
uint private oneTokenInWeiSale2 = 590000000000000; // $0.28 USD
uint private oneTokenInWeiSale3 = 640000000000000; // $0.30 USD
uint private oneTokenInWeiNormal = 680000000000000; // $0.32 USD
Phase public currentPhase = Phase.ICOweek1;
| 33,524 |
3 | // must supply stake value | string private constant STK_AMT = "STK_AMT";
| string private constant STK_AMT = "STK_AMT";
| 41,128 |
20 | // initial mint | totalSupply = _supply * 10**uint256(decimals);
balances[msg.sender] = totalSupply;
| totalSupply = _supply * 10**uint256(decimals);
balances[msg.sender] = totalSupply;
| 55,665 |
99 | // Approve `spender` to transfer up to `value` dTokens on behalf of`msg.sender`. spender address The account to grant the allowance. value uint256 The size of the allowance to grant.return A boolean indicating whether the approval was successful. / | function approve(
address spender, uint256 value
| function approve(
address spender, uint256 value
| 67,194 |
11 | // Burns `tokenId`. See OpenZeppelin ERC721 _burn. Requirements: - The caller must own `tokenId` or be an approved operator. / | function burn(uint256 tokenId) public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
| function burn(uint256 tokenId) public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
| 5,594 |
2 | // Token小数位 | uint8 public override decimals = 18;
| uint8 public override decimals = 18;
| 31,373 |
813 | // ========== MODIFIERS ========== / Contracts directly interacting with multiCollateralSynth or wrapper to issue and burn | modifier onlyInternalContracts() {
bool isInternal = super._isInternalContract(msg.sender);
bool isEtherWrapper = msg.sender == address(etherWrapper());
bool isWrapper = wrapperFactory().isWrapper(msg.sender);
bool isMultiCollateral = collateralManager().hasCollateral(msg.sender);
require(isInternal || isWrapper || isMultiCollateral || isEtherWrapper, "Only internal contracts allowed");
_;
}
| modifier onlyInternalContracts() {
bool isInternal = super._isInternalContract(msg.sender);
bool isEtherWrapper = msg.sender == address(etherWrapper());
bool isWrapper = wrapperFactory().isWrapper(msg.sender);
bool isMultiCollateral = collateralManager().hasCollateral(msg.sender);
require(isInternal || isWrapper || isMultiCollateral || isEtherWrapper, "Only internal contracts allowed");
_;
}
| 34,383 |
2 | // Deposit tokens/deposit0 Amount of token0 transfered from sender to Hypervisor/deposit1 Amount of token1 transfered from sender to Hypervisor/to Address to which liquidity tokens are minted/from Address from which asset tokens are transferred/inMin min spend for directDeposit is true / return shares Quantity of liquidity tokens minted as a result of deposit | function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from,
uint256[4] memory inMin
| function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from,
uint256[4] memory inMin
| 68,616 |
199 | // Update tokenURI through baseURI. This function will be called when setting the initial tokenURI and revealing./ | function updateBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
| function updateBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
| 73,034 |
3 | // user structure | struct User {
address userAccountAddress;
string userName;
string userEmail;
string userPhone;
string userAddress;
string userCity;
string userState;
bool isValid;
}
| struct User {
address userAccountAddress;
string userName;
string userEmail;
string userPhone;
string userAddress;
string userCity;
string userState;
bool isValid;
}
| 8,012 |
312 | // Zeroize the slot after the string. | mstore(str, 0)
| mstore(str, 0)
| 27,416 |
5 | // function totalSupply() public constant returns (uint256); | function balanceOf(address tokenOwner) public constant returns (uint256 balance);
| function balanceOf(address tokenOwner) public constant returns (uint256 balance);
| 22,703 |
131 | // Returns address of current pool / | function pool() external view returns (address);
| function pool() external view returns (address);
| 76,201 |
57 | // require(!_isBlackListedBot[sender], "You have no power here!");require(!_isBlackListedBot[recipient], "You have no power here!");require(!_isBlackListedBot[tx.origin], "You have no power here!"); |
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
|
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
| 51,488 |
48 | // Find this id in the array, or throw. | uint _len = pendingRequestIds.length;
uint _foundIndex = MAX_PENDING_REQUESTS;
for (uint _i = 0; _i < _len; _i++) {
if (pendingRequestIds[_i] == _id) {
_foundIndex = _i;
break;
}
| uint _len = pendingRequestIds.length;
uint _foundIndex = MAX_PENDING_REQUESTS;
for (uint _i = 0; _i < _len; _i++) {
if (pendingRequestIds[_i] == _id) {
_foundIndex = _i;
break;
}
| 1,179 |
76 | // bronze card buy (user -> user) | function bronze_request_buy (uint card_id) public payable {
// require: card is placed on the sell list
require( bronze_list[card_id].price > 0 );
// require: request buy is greater than minimum price
require( msg.value == bronze_list[card_id].price );
// require : check if card owner approves the request
require( bronze_list[card_id].sell_approve == true );
// transfer ETH from new owner to old owner
bronze_list[card_id].owner.transfer(msg.value);
// move the card ownership from old owner to new owner
bronze_list[card_id].owner = msg.sender;
bronze_list[card_id].sell_approve = false;
bronze_list[card_id].price = 0;
emit BronzeBought(msg.sender, bronze_list[card_id].price, bronze_list[card_id].sell_approve);
}
| function bronze_request_buy (uint card_id) public payable {
// require: card is placed on the sell list
require( bronze_list[card_id].price > 0 );
// require: request buy is greater than minimum price
require( msg.value == bronze_list[card_id].price );
// require : check if card owner approves the request
require( bronze_list[card_id].sell_approve == true );
// transfer ETH from new owner to old owner
bronze_list[card_id].owner.transfer(msg.value);
// move the card ownership from old owner to new owner
bronze_list[card_id].owner = msg.sender;
bronze_list[card_id].sell_approve = false;
bronze_list[card_id].price = 0;
emit BronzeBought(msg.sender, bronze_list[card_id].price, bronze_list[card_id].sell_approve);
}
| 28,144 |
49 | // Check that tokenId was not minted by `_beforeTokenTransfer` hook | require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
| require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
| 13,247 |
125 | // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) | bytes memory tosign1 = new bytes(32 + 8 + 1 + 32);
copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) {
return false;
}
| bytes memory tosign1 = new bytes(32 + 8 + 1 + 32);
copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) {
return false;
}
| 6,759 |
21 | // Remove `_collateral.symbol(): string` as a whitelisted collateral token _collateral The address of the collateral token to be un-whitelisted / | function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
marketMaker.removeCollateralToken(_collateral);
// the token should still be tapped to avoid being locked
// the token should still be protected to avoid being spent
}
| function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
marketMaker.removeCollateralToken(_collateral);
// the token should still be tapped to avoid being locked
// the token should still be protected to avoid being spent
}
| 21,532 |
282 | // The inventory plus one | dataSource.addInventories(_vendorId, _rpid, _date, 1);
| dataSource.addInventories(_vendorId, _rpid, _date, 1);
| 68,158 |
128 | // 累计下一期分红金额 | function _AddNextDailyPrizePoolAmount(uint256 amount) private {
uint nextId = dailyPrizePoolId + 1;
dailyPrizePools[nextId].draw = false;
if (dailyPrizePools[nextId].date < 1) {
// 设置下一期开奖时间
dailyPrizePools[nextId].id = nextId;
dailyPrizePools[nextId].date = dailyPrizePools[dailyPrizePoolId].date + 1 days;
}
// 累计金额
if (amount > 0) {
dailyPrizePools[nextId].amount = dailyPrizePools[nextId].amount.add(amount);
}
}
| function _AddNextDailyPrizePoolAmount(uint256 amount) private {
uint nextId = dailyPrizePoolId + 1;
dailyPrizePools[nextId].draw = false;
if (dailyPrizePools[nextId].date < 1) {
// 设置下一期开奖时间
dailyPrizePools[nextId].id = nextId;
dailyPrizePools[nextId].date = dailyPrizePools[dailyPrizePoolId].date + 1 days;
}
// 累计金额
if (amount > 0) {
dailyPrizePools[nextId].amount = dailyPrizePools[nextId].amount.add(amount);
}
}
| 5,875 |
19 | // Owner is able to transfer allocation between any accounts in case special cases happened, e.g. someone lost their address/key. However, the vested tokens before transfer will remain in the account before transfer. Onwer transfer is not limited by the transfer pause status. | function transferAllocationFrom(address from, address recipient, uint amount) external onlyOwner updateVested(from) updateVested(recipient) returns (bool) {
require(from != address(0), "transfer from the zero address");
require(recipient != address(0), "transfer to the zero address");
accountAllocations[from] = accountAllocations[from].sub(amount, "transfer amount exceeds balance");
accountAllocations[recipient] = accountAllocations[recipient].add(amount);
emit TransferAllocation(from, recipient, amount);
return true;
}
| function transferAllocationFrom(address from, address recipient, uint amount) external onlyOwner updateVested(from) updateVested(recipient) returns (bool) {
require(from != address(0), "transfer from the zero address");
require(recipient != address(0), "transfer to the zero address");
accountAllocations[from] = accountAllocations[from].sub(amount, "transfer amount exceeds balance");
accountAllocations[recipient] = accountAllocations[recipient].add(amount);
emit TransferAllocation(from, recipient, amount);
return true;
}
| 12,844 |
7 | // APPROVE SPEND ALLOWANCE AND CALL SPENDER/ | bytes _extraData) external returns (bool success) {
tokenRecipient
spender = tokenRecipient(_spender);
if(approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
}
return true;
}
| bytes _extraData) external returns (bool success) {
tokenRecipient
spender = tokenRecipient(_spender);
if(approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
}
return true;
}
| 9,343 |
109 | // Send token reward to users, / | function _sendReward(uint256 _rewardLeft, uint256 _rewardWithRate) internal {
if (_rewardLeft >= _rewardWithRate) {
IERC20(tokenReward).safeTransfer(msg.sender, _rewardWithRate);
} else {
IERC20(tokenReward).safeTransfer(msg.sender, _rewardLeft);
}
}
| function _sendReward(uint256 _rewardLeft, uint256 _rewardWithRate) internal {
if (_rewardLeft >= _rewardWithRate) {
IERC20(tokenReward).safeTransfer(msg.sender, _rewardWithRate);
} else {
IERC20(tokenReward).safeTransfer(msg.sender, _rewardLeft);
}
}
| 34,955 |
25 | // Get the current issuer address from storage. / | function issuer() public view returns (address) {
return rocketStorage.getAddress(keccak256("token.issuer"));
}
| function issuer() public view returns (address) {
return rocketStorage.getAddress(keccak256("token.issuer"));
}
| 43,965 |
1 | // Common Errors | error AddressZero();
error NullAmount();
error IncorrectRewardToken();
error SameAddress();
error InequalArraySizes();
error EmptyArray();
error EmptyParameters();
error NotInitialized();
error AlreadyInitialized();
error CannotInitialize();
| error AddressZero();
error NullAmount();
error IncorrectRewardToken();
error SameAddress();
error InequalArraySizes();
error EmptyArray();
error EmptyParameters();
error NotInitialized();
error AlreadyInitialized();
error CannotInitialize();
| 28,623 |
181 | // Getter for the futureVault period state _futureVault the address of the futureVaultreturn true if the futureVault is set to be terminated at its expiration / | function isFutureSetToBeTerminated(address _futureVault) external view returns (bool);
| function isFutureSetToBeTerminated(address _futureVault) external view returns (bool);
| 25,720 |
224 | // nToken balance stored at the beginning of the transaction | int256 storedNTokenBalance;
| int256 storedNTokenBalance;
| 6,936 |
9 | // EVENTS // MODIFIERS // modifier to restrict a functionality only to Premium users / | modifier restrictToPremium{
require(
premiumUsers[msg.sender].isPremium &&
(premiumUsers[msg.sender].blockNum + premiumTime) > block.number,
"Access restricted to Premium accounts!"
);
_;
}
| modifier restrictToPremium{
require(
premiumUsers[msg.sender].isPremium &&
(premiumUsers[msg.sender].blockNum + premiumTime) > block.number,
"Access restricted to Premium accounts!"
);
_;
}
| 45,355 |
65 | // It's possible to have remove rights without having add rights | require(rights.canAddRemoveTokens,"ERR_CANNOT_ADD_REMOVE_TOKENS");
| require(rights.canAddRemoveTokens,"ERR_CANNOT_ADD_REMOVE_TOKENS");
| 5,410 |
98 | // INTERNAL NON-VIEW |
function _liquidate(address trader, address baseToken)
internal
returns (
uint256 base,
uint256 quote,
bool isPartialClose
)
|
function _liquidate(address trader, address baseToken)
internal
returns (
uint256 base,
uint256 quote,
bool isPartialClose
)
| 8,279 |
556 | // Update the given pool's NERDs allocation point. Can only be called by the owner. Note contract owner is meant to be a governance contract allowing NERD governance consensus |
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
|
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
| 33,270 |
10 | // Calculate the current price for buy in amount. / | function calculateTokenAmount(uint weiAmount) public constant returns (uint tokenAmount) {
uint bonusRate = 0;
if (weiAmount >= minimumWeiAmount) {
if (now < newRateTime) {
bonusRate = rate1;
} else {
bonusRate = rate2;
}
}
return weiAmount.mul(bonusRate);
}
| function calculateTokenAmount(uint weiAmount) public constant returns (uint tokenAmount) {
uint bonusRate = 0;
if (weiAmount >= minimumWeiAmount) {
if (now < newRateTime) {
bonusRate = rate1;
} else {
bonusRate = rate2;
}
}
return weiAmount.mul(bonusRate);
}
| 25,076 |
48 | // FlipNpik Airdrop Tool. / | contract FlipNpikAirdrop is Operable {
// FlipNpik token address
ERC20 public token;
/**
* @param _token Token address
* @param _owner Smart contract owner address
*/
constructor (ERC20 _token, address _owner) public {
require(_token != address(0), "Token address is invalid.");
token = _token;
require(_owner != address(0), "Owner address is invalid.");
owner = _owner;
}
/**
* @dev Distibutes tokens based on provided lists of wallets and values
* @param _wallets List of wallets
* @param _values List of values
*/
function distribute(address[] _wallets, uint256[] _values) external hasOwnerOrOperatePermission returns(bool) {
require(_wallets.length == _values.length, "Lists are of different length.");
for (uint256 j = 0; j < _wallets.length; ++j) {
token.transferFrom(msg.sender, _wallets[j], _values[j]);
}
return true;
}
} | contract FlipNpikAirdrop is Operable {
// FlipNpik token address
ERC20 public token;
/**
* @param _token Token address
* @param _owner Smart contract owner address
*/
constructor (ERC20 _token, address _owner) public {
require(_token != address(0), "Token address is invalid.");
token = _token;
require(_owner != address(0), "Owner address is invalid.");
owner = _owner;
}
/**
* @dev Distibutes tokens based on provided lists of wallets and values
* @param _wallets List of wallets
* @param _values List of values
*/
function distribute(address[] _wallets, uint256[] _values) external hasOwnerOrOperatePermission returns(bool) {
require(_wallets.length == _values.length, "Lists are of different length.");
for (uint256 j = 0; j < _wallets.length; ++j) {
token.transferFrom(msg.sender, _wallets[j], _values[j]);
}
return true;
}
} | 6,343 |
51 | // Deletes the channel and settles by transfering the balance to the receiver and the rest of the deposit back to the sender _sender address that want to send the micro-payment _receiver address that is to receive the micro-payment _openBlockNumber Block number at which the channel was created _balance The amount owed by the sender to the receiver / | function settleChannel(
address _sender,
address _receiver,
uint256 _openBlockNumber,
uint256 _balance)
| function settleChannel(
address _sender,
address _receiver,
uint256 _openBlockNumber,
uint256 _balance)
| 6,442 |
17 | // Save the new data | lastPricePerShare = _currentPricePerShare;
lastVirtualPrice = _currentVirtualPrice;
| lastPricePerShare = _currentPricePerShare;
lastVirtualPrice = _currentVirtualPrice;
| 73,214 |
2 | // to support backward compatible contract name -- so function signature remains same | abstract contract ERC20 is IERC20 {
}
| abstract contract ERC20 is IERC20 {
}
| 8,409 |
5 | // Gets the token symbol.return string representing the token symbol / | function symbol() external view returns (string memory) {
return _symbol;
}
| function symbol() external view returns (string memory) {
return _symbol;
}
| 52,017 |
512 | // if the point wasn't active yet, that means transferring itis part of the "spawn" flow, so we need to activate it | if ( !azimuth.isActive(_point) )
{
azimuth.activatePoint(_point);
}
| if ( !azimuth.isActive(_point) )
{
azimuth.activatePoint(_point);
}
| 37,140 |
47 | // The voter who voted for the "truth" level can receive the reward. The PROPORTIONAL_REWARD_RATE of the reward is distributed to the voters in proportion to the coins they deposited. This incentivizes voters who have more coins (and thus have more power on determining the "truth" level) to join the oracle. The rest of the reward is distributed to the voters evenly. This incentivizes more voters (including new voters) to join the oracle. | if (epoch.votes[oracle_level].deposit > 0) {
reward += (uint(PROPORTIONAL_REWARD_RATE) * epoch.reward_total *
deposit) / (uint(100) * epoch.votes[oracle_level].deposit);
}
| if (epoch.votes[oracle_level].deposit > 0) {
reward += (uint(PROPORTIONAL_REWARD_RATE) * epoch.reward_total *
deposit) / (uint(100) * epoch.votes[oracle_level].deposit);
}
| 13,802 |
30 | // allow the owner to revoke the vesting/ | function revoke(uint256 _option, address _wallet)
public
onlyOwner
userInWhitelist(_option, _wallet)
| function revoke(uint256 _option, address _wallet)
public
onlyOwner
userInWhitelist(_option, _wallet)
| 69,135 |
2 | // external functions |
function approve(
address spender,
uint256 value
)
external
returns (bool);
function transfer(
address to,
|
function approve(
address spender,
uint256 value
)
external
returns (bool);
function transfer(
address to,
| 13,790 |
24 | // Gets the active state of the reserve reserve The reservereturn The true or false state / | ) internal view returns (bool) {
return reserve.flags.isActive;
}
| ) internal view returns (bool) {
return reserve.flags.isActive;
}
| 13,085 |
46 | // Burn tokens rawAmount The number of tokens to be burned / | function burn(uint rawAmount) public {
uint96 amount = safe96(rawAmount, "Gain::mint: amount exceeds 96 bits");
require(balances[msg.sender] >= amount, "Gain::burn: insufficient balance");
totalSupply = safe96(SafeMath.sub(totalSupply, amount), "Gain::burn: insufficient balance");
balances[msg.sender] = safe96(SafeMath.sub(balances[msg.sender], amount), "Gain::burn: insufficient balance");
}
| function burn(uint rawAmount) public {
uint96 amount = safe96(rawAmount, "Gain::mint: amount exceeds 96 bits");
require(balances[msg.sender] >= amount, "Gain::burn: insufficient balance");
totalSupply = safe96(SafeMath.sub(totalSupply, amount), "Gain::burn: insufficient balance");
balances[msg.sender] = safe96(SafeMath.sub(balances[msg.sender], amount), "Gain::burn: insufficient balance");
}
| 28,564 |
25 | // / | revert("RPOWE_SLOW_CONVERGE");
| revert("RPOWE_SLOW_CONVERGE");
| 51,124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.