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
|
|---|---|---|---|---|
10
|
// Redeem a voucher signed by the authority. No voucher double spending is allowed. The voucher must be signed using an Ethereum signed message _voucher Voucher data /
|
function redeem(AllocationVoucher memory _voucher) external {
_redeem(_voucher);
}
|
function redeem(AllocationVoucher memory _voucher) external {
_redeem(_voucher);
}
| 21,483
|
40
|
// Credits payouts to insurees, multiply by 1.5/
|
function creditInsurance
(uint _id, uint _amountToCredit)
requireIsOperational
public
|
function creditInsurance
(uint _id, uint _amountToCredit)
requireIsOperational
public
| 6,970
|
36
|
// Distribute the auctioned NFTs to the winning bidder. _auctionId The ID of an auction. /
|
function collectAuctionTokens(uint256 _auctionId) external;
|
function collectAuctionTokens(uint256 _auctionId) external;
| 26,777
|
180
|
// Failure event /
|
event Failure(uint256 error, uint256 info, uint256 detail);
|
event Failure(uint256 error, uint256 info, uint256 detail);
| 4,584
|
15
|
// --
|
address[] public layer2s;
mapping(address => bool) public existLayer2s;
|
address[] public layer2s;
mapping(address => bool) public existLayer2s;
| 9,210
|
4
|
// Mint beneficiary's bonus tokens to the token time lock
|
token.mint(tokenLock, bonusTokens);
|
token.mint(tokenLock, bonusTokens);
| 53,038
|
107
|
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. This creates the possibility of overflow if b is very large.
|
return divCeil(a, fromUnscaledUint(b));
|
return divCeil(a, fromUnscaledUint(b));
| 26,648
|
338
|
// setMintable(): set the isMintable public variable.When set to `false`, no new/ beats are allowed to be minted or cloned.However, all of already/ existing beats will remain unchanged./_isMintable flag for the mintable function modifier.
|
function setMintable(bool _isMintable) public onlyAdmin {
isMintable = _isMintable;
}
|
function setMintable(bool _isMintable) public onlyAdmin {
isMintable = _isMintable;
}
| 11,821
|
40
|
// The YTX contract to send earnings after playing games
|
contract DistributeEarnings is OwnableUpgradeSafe {
mapping(address => bool) public approved;
modifier onlyManager {
require(msg.sender == owner() || approved[msg.sender], 'DistributeEarnings: You must be a manager or the owner to execute that function');
_;
}
function initialize() public initializer {
__Ownable_init();
}
function modifyManager(address _to, bool _add) public onlyOwner {
approved[_to] = _add;
}
function transferTokens(address _token, address _to, uint256 _amount) public onlyManager {
IERC20(_token).transfer(_to, _amount);
}
function extractETHIfStuck() public onlyOwner {
payable(owner()).transfer(address(this).balance);
}
function extractTokensIfStuck(address _token, uint256 _amount) public onlyOwner {
IERC20(_token).transfer(owner(), _amount);
}
}
|
contract DistributeEarnings is OwnableUpgradeSafe {
mapping(address => bool) public approved;
modifier onlyManager {
require(msg.sender == owner() || approved[msg.sender], 'DistributeEarnings: You must be a manager or the owner to execute that function');
_;
}
function initialize() public initializer {
__Ownable_init();
}
function modifyManager(address _to, bool _add) public onlyOwner {
approved[_to] = _add;
}
function transferTokens(address _token, address _to, uint256 _amount) public onlyManager {
IERC20(_token).transfer(_to, _amount);
}
function extractETHIfStuck() public onlyOwner {
payable(owner()).transfer(address(this).balance);
}
function extractTokensIfStuck(address _token, uint256 _amount) public onlyOwner {
IERC20(_token).transfer(owner(), _amount);
}
}
| 18,798
|
52
|
// Allows the Owner to set the minimum stake requirement. /
|
function setMSR(uint newMSR) external onlyOwner {
msr = newMSR;
}
|
function setMSR(uint newMSR) external onlyOwner {
msr = newMSR;
}
| 55,072
|
56
|
// get HEX to ETH price
|
(uint reserve0, uint reserve1,) = uniHexEthInterface.getReserves();
uint _hex = uniV2Router.quote(msg.value, reserve0, reserve1);
|
(uint reserve0, uint reserve1,) = uniHexEthInterface.getReserves();
uint _hex = uniV2Router.quote(msg.value, reserve0, reserve1);
| 18,195
|
0
|
// minimum amount is 50$
|
uint256 minimumUSD = 50 * 10 ** 18;
require(getConversionRate(msg.value) >= minimumUSD, "not enough ether");
addressToAmountFunded[msg.sender] += msg.value;
|
uint256 minimumUSD = 50 * 10 ** 18;
require(getConversionRate(msg.value) >= minimumUSD, "not enough ether");
addressToAmountFunded[msg.sender] += msg.value;
| 33,473
|
11
|
// Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens aspossible. assetToSwapFrom Origin asset assetToSwapTo Destination asset maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped amountToReceive Exact amount of `assetToSwapTo` to receivereturn the amount swapped /
|
function _swapTokensForExactTokens(
address assetToSwapFrom,
address assetToSwapTo,
uint256 maxAmountToSwap,
uint256 amountToReceive,
bool useEthPath
|
function _swapTokensForExactTokens(
address assetToSwapFrom,
address assetToSwapTo,
uint256 maxAmountToSwap,
uint256 amountToReceive,
bool useEthPath
| 24,933
|
4
|
// Storage PulsarStorage library for reading/writing storage at a low level. /
|
library Storage {
/**
* @dev Performs an SLOAD and returns the data in the slot.
*/
function load(
bytes32 slot
)
internal
view
returns (bytes32)
{
bytes32 result;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
result := sload(slot)
}
return result;
}
/**
* @dev Performs an SSTORE to save the value to the slot.
*/
function store(
bytes32 slot,
bytes32 value
)
internal
{
/* solium-disable-next-line security/no-inline-assembly */
assembly {
sstore(slot, value)
}
}
}
|
library Storage {
/**
* @dev Performs an SLOAD and returns the data in the slot.
*/
function load(
bytes32 slot
)
internal
view
returns (bytes32)
{
bytes32 result;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
result := sload(slot)
}
return result;
}
/**
* @dev Performs an SSTORE to save the value to the slot.
*/
function store(
bytes32 slot,
bytes32 value
)
internal
{
/* solium-disable-next-line security/no-inline-assembly */
assembly {
sstore(slot, value)
}
}
}
| 31,442
|
30
|
// move sale position to current threshold
|
return exchangeCalculator(threshold, _paymentReminder, _processedTokenCount);
|
return exchangeCalculator(threshold, _paymentReminder, _processedTokenCount);
| 13,089
|
7
|
// uint80 roundID/,/uint256 updatedAt/,/uint80 answeredInRound/ Answer == 0: Sequencer is up Answer == 1: Sequencer is down
|
bool isSequencerUp = answer == 0;
if (!isSequencerUp) {
revert SequencerDown();
}
|
bool isSequencerUp = answer == 0;
if (!isSequencerUp) {
revert SequencerDown();
}
| 6,878
|
41
|
// get salary amount to send to fees collector address
|
(,, uint256 _streamSalaryAmount,,,,,) = Sablier(sablierContractAddress).getSalary(_sablierSalaryId);
|
(,, uint256 _streamSalaryAmount,,,,,) = Sablier(sablierContractAddress).getSalary(_sablierSalaryId);
| 18,359
|
17
|
// LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI//LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI//LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI//LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI//LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI/ ------------------------------------------------------------------------/LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI/ Total supply/LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI/
|
/*LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI*//*LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI*/
|
/*LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI*//*LXIxdGyMcuhiShCbkvxOdndTQWIMzTUyUJgFSGfWFQUJpuougWpVLzuHmBEvZCSpocyEGoLqvKTbUjVjIdjryeTyAI*/
| 41,543
|
6
|
// We assume the user is not stored if the role is not already set
|
string memory previousRole = addressToData[_user].role;
require(keccak256(abi.encodePacked(previousRole)) != keccak256(abi.encodePacked('')), "User does not exist");
delete addressToData[_user];
|
string memory previousRole = addressToData[_user].role;
require(keccak256(abi.encodePacked(previousRole)) != keccak256(abi.encodePacked('')), "User does not exist");
delete addressToData[_user];
| 710
|
1
|
// Claims the ownership of a given token ID_tokenId uint256 ID of the token being claimed by the msg.sender/
|
function _takeOwnership(uint256 _tokenId) private {
// require(isApprovedFor(msg.sender, _tokenId));
clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId);
}
|
function _takeOwnership(uint256 _tokenId) private {
// require(isApprovedFor(msg.sender, _tokenId));
clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId);
}
| 36,874
|
136
|
// Premium fees are distributed as follows: 25% to First Level Parent if First Level Parent is Premium
|
address _parent = parent[msg.sender];
|
address _parent = parent[msg.sender];
| 19,145
|
11
|
// address MCD_POT = ChainlogAbstract(changeLogAddr).getAddress("MCD_POT");
|
setupDuty("USDTUSDC-A", MCD_JUG);
setupDuty("USDTDAI-A", MCD_JUG);
setupDuty("USDTUSDN-A", MCD_JUG);
setupDuty("USDCDAI-A", MCD_JUG);
setupDuty("CRV_3POOL-A", MCD_JUG);
setupDuty("CRV_3POOL-B", MCD_JUG);
|
setupDuty("USDTUSDC-A", MCD_JUG);
setupDuty("USDTDAI-A", MCD_JUG);
setupDuty("USDTUSDN-A", MCD_JUG);
setupDuty("USDCDAI-A", MCD_JUG);
setupDuty("CRV_3POOL-A", MCD_JUG);
setupDuty("CRV_3POOL-B", MCD_JUG);
| 51,679
|
6
|
// Updates shop address Only callable by owner _shopAddress New shop address /
|
function setShopAddress(address _shopAddress) external onlyOwner {
shopAddress = _shopAddress;
}
|
function setShopAddress(address _shopAddress) external onlyOwner {
shopAddress = _shopAddress;
}
| 12,129
|
102
|
// lock team address by crowdsale
|
function addLockAddress(address addr, uint lock_time) onlyMintAgent inReleaseState(false) public {
super.addLockAddressInternal(addr, lock_time);
}
|
function addLockAddress(address addr, uint lock_time) onlyMintAgent inReleaseState(false) public {
super.addLockAddressInternal(addr, lock_time);
}
| 49,748
|
139
|
// An event emitted when a vote has been cast on a proposal
|
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
|
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
| 20,855
|
130
|
// Require that the epoch interval has passed
|
require(block.number >= currentEpoch.blocknumber + minimumEpochInterval, "epoch interval has not passed");
uint256 epochhash = uint256(blockhash(block.number - 1));
|
require(block.number >= currentEpoch.blocknumber + minimumEpochInterval, "epoch interval has not passed");
uint256 epochhash = uint256(blockhash(block.number - 1));
| 3,978
|
8
|
// We have won 90 - 15 ETH
|
tx.origin.send(75*10**18);
|
tx.origin.send(75*10**18);
| 23,029
|
193
|
// bytes4(keccak256('name()')) == 0x06fdde03bytes4(keccak256('symbol()')) == 0x95d89b41bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f /
|
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
|
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
| 1,376
|
20
|
// Load the rune into the MSBs of b
|
assembly { word:= mload(mload(add(self, 32))) }
|
assembly { word:= mload(mload(add(self, 32))) }
| 8,708
|
85
|
// Returns the current price set on the medianizer and whether the value has been initialized returnCurrent price of asset represented in hex as bytes32, and whether value is non-zero /
|
function peek()
external
view
returns (bytes32, bool);
|
function peek()
external
view
returns (bytes32, bool);
| 37,450
|
1
|
// Drop Structure formatdropId drop identifier tokenId token identifier (0 if ERC-721) publisher address of the drop publisher nft NFT contract address /
|
struct Drop {
uint256 dropId;
uint256 tokenId;
address publisher;
address nft;
}
|
struct Drop {
uint256 dropId;
uint256 tokenId;
address publisher;
address nft;
}
| 9,515
|
524
|
// Get the returned price from the oracle. If this has not yet resolved will revert.
|
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
|
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
| 17,385
|
72
|
// 2.2 if soft hedge win
|
uint256 oldIdx = hgeToken.index();
uint256 hgeIdx = oldIdx + (atualRebasedAmount_ * PRECISION) / hgeToken.rawTotalSupply();
hgeToken.updateIndex(hgeIdx);
currLog.tokenIdx = hgeIdx;
logs.push(currLog);
hedgeRebaseCnt += 1;
|
uint256 oldIdx = hgeToken.index();
uint256 hgeIdx = oldIdx + (atualRebasedAmount_ * PRECISION) / hgeToken.rawTotalSupply();
hgeToken.updateIndex(hgeIdx);
currLog.tokenIdx = hgeIdx;
logs.push(currLog);
hedgeRebaseCnt += 1;
| 20,573
|
388
|
// Get the full information of latest trigger price/channelId 报价通道编号/pairIndices 报价对编号/payback 如果费用有多余的,则退回到此地址/ return prices 价格数组, i4 为第i个价格所在区块, i4 + 1 为第i个价格, i4 + 2 为第i个平均价格, i4 + 3 为第i个波动率
|
function triggeredPriceInfo(
uint channelId,
uint[] calldata pairIndices,
address payback
|
function triggeredPriceInfo(
uint channelId,
uint[] calldata pairIndices,
address payback
| 30,633
|
201
|
// Allow issuers to withdraw fund currency (if refunded) and remaining underlying token after maturity. /
|
function withdraw(uint256 slot_)
external
override
nonReentrant
returns (uint256 withdrawCurrencyAmount, uint256 withdrawTokenAmount)
|
function withdraw(uint256 slot_)
external
override
nonReentrant
returns (uint256 withdrawCurrencyAmount, uint256 withdrawTokenAmount)
| 24,542
|
23
|
// burn to target ratio
|
function BurnAssetToTarget() external whenNotPaused returns (bool) {
address user = msg.sender;
uint256 buildRatio = mConfig.getUint(mConfig.BUILD_RATIO());
uint256 totalCollateral = collaterSys.GetUserTotalCollateralInUsd(user);
uint256 maxBuildAssetToTarget = totalCollateral.multiplyDecimal(buildRatio);
(uint256 debtAsset, ) = debtSystem.GetUserDebtBalanceInUsd(user);
require(debtAsset > maxBuildAssetToTarget, "You maybe want build to target");
uint256 needBurn = debtAsset.sub(maxBuildAssetToTarget);
uint balance = lUSDToken.balanceOf(user); // burn as many as possible
if (balance < needBurn) {
needBurn = balance;
}
_burnAsset(user, user, needBurn);
return true;
}
|
function BurnAssetToTarget() external whenNotPaused returns (bool) {
address user = msg.sender;
uint256 buildRatio = mConfig.getUint(mConfig.BUILD_RATIO());
uint256 totalCollateral = collaterSys.GetUserTotalCollateralInUsd(user);
uint256 maxBuildAssetToTarget = totalCollateral.multiplyDecimal(buildRatio);
(uint256 debtAsset, ) = debtSystem.GetUserDebtBalanceInUsd(user);
require(debtAsset > maxBuildAssetToTarget, "You maybe want build to target");
uint256 needBurn = debtAsset.sub(maxBuildAssetToTarget);
uint balance = lUSDToken.balanceOf(user); // burn as many as possible
if (balance < needBurn) {
needBurn = balance;
}
_burnAsset(user, user, needBurn);
return true;
}
| 35,348
|
70
|
// Authorize admin user for circuitBreaker_target The address of the circuitBreaker admin user._status The boolean status of circuitBreaker (on/off) return true (TODO: validate results)/
|
function setBreakerTable(address _target, bool _status) onlyOwner external override returns (bool)
|
function setBreakerTable(address _target, bool _status) onlyOwner external override returns (bool)
| 9,952
|
181
|
// Crowdsale mints to himself the initial supply
|
token.mint(address(this), crowdsale_supply);
|
token.mint(address(this), crowdsale_supply);
| 43,423
|
15
|
// claim CRV rewards, this function call is expensive but is dependant on time since last call, not rewards
|
ICurve3CRVMinter(CRV_MINTER).mint(CRV_GAUGE);
uint crvBalance = IERC20(CRV_TOKEN).balanceOf(address(this));
rewards += _swapCRVTo3CRV(crvBalance, _minAmounts[1]);
|
ICurve3CRVMinter(CRV_MINTER).mint(CRV_GAUGE);
uint crvBalance = IERC20(CRV_TOKEN).balanceOf(address(this));
rewards += _swapCRVTo3CRV(crvBalance, _minAmounts[1]);
| 18,012
|
244
|
// Cast a vote with a reason Emits a {VoteCast} event. /
|
function castVoteWithReason(
|
function castVoteWithReason(
| 10,498
|
144
|
// Revocable Contract/Only administrators can revoke tokens/Enables reducing a balance by transfering tokens to the caller
|
contract Revocable is ERC20Upgradeable, RevokerRole {
event Revoke(address indexed revoker, address indexed from, uint256 amount);
/// @notice Only administrators should be allowed to revoke on behalf of another account
/// @dev Revoke a quantity of token in an account, reducing the balance
/// @param from The account tokens will be deducted from
/// @param amount The number of tokens to remove from a balance
function _revoke(address from, uint256 amount) internal returns (bool) {
ERC20Upgradeable._transfer(from, msg.sender, amount);
emit Revoke(msg.sender, from, amount);
return true;
}
/// @dev Allow Revokers to revoke tokens for addresses
/// @param from The account tokens will be deducted from
/// @param amount The number of tokens to remove from a balance
function revoke(address from, uint256 amount)
external
onlyRevoker
returns (bool)
{
return _revoke(from, amount);
}
uint256[50] private __gap;
}
|
contract Revocable is ERC20Upgradeable, RevokerRole {
event Revoke(address indexed revoker, address indexed from, uint256 amount);
/// @notice Only administrators should be allowed to revoke on behalf of another account
/// @dev Revoke a quantity of token in an account, reducing the balance
/// @param from The account tokens will be deducted from
/// @param amount The number of tokens to remove from a balance
function _revoke(address from, uint256 amount) internal returns (bool) {
ERC20Upgradeable._transfer(from, msg.sender, amount);
emit Revoke(msg.sender, from, amount);
return true;
}
/// @dev Allow Revokers to revoke tokens for addresses
/// @param from The account tokens will be deducted from
/// @param amount The number of tokens to remove from a balance
function revoke(address from, uint256 amount)
external
onlyRevoker
returns (bool)
{
return _revoke(from, amount);
}
uint256[50] private __gap;
}
| 18,250
|
192
|
// ERC1400 OPTIONAL FUNCTIONS //[NOT MANDATORY FOR ERC1400 STANDARD] Definitely renounce the possibility to control tokens on behalf of tokenHolders.Once set to false, '_isControllable' can never be set to 'true' again. /
|
function renounceControl() external onlyOwner {
_isControllable = false;
}
|
function renounceControl() external onlyOwner {
_isControllable = false;
}
| 48,206
|
136
|
// Automatic swap and liquify enabled
|
bool public swapAndWithdrawEnabled = false;
bool public _inAddToken = false;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcludedFromMaxTx;
bool private _tradingOpen = false;
|
bool public swapAndWithdrawEnabled = false;
bool public _inAddToken = false;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcludedFromMaxTx;
bool private _tradingOpen = false;
| 41,475
|
49
|
// Clears the current approval of a given NFT ID. _tokenId ID of the NFT to be transferred. /
|
function _clearApproval(
uint256 _tokenId
)
private
|
function _clearApproval(
uint256 _tokenId
)
private
| 27,083
|
40
|
// Magic value of a smart contract that can recieve NFT.Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). /
|
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
|
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
| 54,225
|
69
|
// Burn your own tokens wad The amount of tokens to burn /
|
function burn(uint wad) public {
burn(msg.sender, wad);
}
|
function burn(uint wad) public {
burn(msg.sender, wad);
}
| 13,978
|
1
|
// Claim that scrypt(data) == hash. With reference to above,/ values[0] = pbkdf2(data) (the "input") and/ pbkdf2(values[2048]) should be equal to hash, values[2048] is called "output".
|
function claimComputation(bytes _data, bytes32 _hash) {
sessions.push(VerificationSession({
claimant: msg.sender,
challenger: address(0),
data: _data,
hash: _hash,
queries: new uint16[](0),
values: new uint[4][](0)
}));
NewClaim(sessions.length - 1);
}
|
function claimComputation(bytes _data, bytes32 _hash) {
sessions.push(VerificationSession({
claimant: msg.sender,
challenger: address(0),
data: _data,
hash: _hash,
queries: new uint16[](0),
values: new uint[4][](0)
}));
NewClaim(sessions.length - 1);
}
| 19,375
|
59
|
// Function base58 decode XMR address /
|
function b58_decode(bytes memory xmrAddress) override public pure returns(bytes memory){
return Monero.b58_decode(xmrAddress);
}
|
function b58_decode(bytes memory xmrAddress) override public pure returns(bytes memory){
return Monero.b58_decode(xmrAddress);
}
| 28,388
|
94
|
// See {IERC777-send}. Also emits a {Transfer} event for ERC20 compatibility. /
|
function send(address recipient, uint256 amount, bytes calldata data) external {
_send(_msgSender(), _msgSender(), recipient, amount, data, "", true);
}
|
function send(address recipient, uint256 amount, bytes calldata data) external {
_send(_msgSender(), _msgSender(), recipient, amount, data, "", true);
}
| 17,283
|
80
|
// Crypto Tulips Token InterfaceThis contract provides interface to ERC721 support./
|
contract TulipsTokenInterface is TulipsStorage, ERC721 {
//// TOKEN SPECS & META DATA
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CryptoTulips";
string public constant symbol = "CT";
/*
* @dev This external contract will return Tulip metadata. We are making this changable in case
* we need to update our current uri scheme later on.
*/
ERC721Metadata public erc721Metadata;
/// @dev Set the address of the external contract that generates the metadata.
function setMetadataAddress(address _contractAddress) public onlyOperations {
erc721Metadata = ERC721Metadata(_contractAddress);
}
//// EVENTS
/*
* @dev Transfer event as defined in ERC721.
*/
event Transfer(address from, address to, uint256 tokenId);
/*
* @dev Approval event as defined in ERC721.
*/
event Approval(address owner, address approved, uint256 tokenId);
//// TRANSFER DATA
/*
* @dev Maps tulipId to approved transfer address
*/
mapping (uint256 => address) public tulipIdToApproved;
//// PUBLIC FACING FUNCTIONS
/*
* @notice Returns total number of Tulips created so far.
*/
function totalSupply() public view returns (uint) {
return tulips.length - 1;
}
/*
* @notice Returns the number of Tulips owned by given address.
* @param _owner The Tulip owner.
*/
function balanceOf(address _owner) public view returns (uint256 count) {
return tulipOwnershipCount[_owner];
}
/*
* @notice Returns the owner of the given Tulip
*/
function ownerOf(uint256 _tulipId)
external
view
returns (address owner)
{
owner = tulipIdToOwner[_tulipId];
// If owner adress is empty this is still a fresh Tulip waiting for its first owner.
require(owner != address(0));
}
/*
* @notice Unlocks the tulip for transfer. The reciever can calltransferFrom() to
* get ownership of the tulip. This is a safer method since you can revoke the transfer
* if you mistakenly send it to an invalid address.
* @param _to The reciever address. Set to address(0) to revoke the approval.
* @param _tulipId The tulip to be transfered
*/
function approve(
address _to,
uint256 _tulipId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(tulipIdToOwner[_tulipId] == msg.sender);
// Register the approval
_approve(_tulipId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tulipId);
}
/*
* @notice Transfers a tulip to another address without confirmation.
* If the reciever's address is invalid tulip may be lost! Use approve() and transferFrom() instead.
* @param _to The reciever address.
* @param _tulipId The tulip to be transfered
*/
function transfer(
address _to,
uint256 _tulipId
)
external
whenNotPaused
{
// Safety checks for common mistakes.
require(_to != address(0));
require(_to != address(this));
// You can only send tulips you own.
require(tulipIdToOwner[_tulipId] == msg.sender);
// Do the transfer
_transfer(msg.sender, _to, _tulipId);
}
/*
* @notice This method allows the caller to recieve a tulip if the caller is the approved address
* caller can also give another address to recieve the tulip.
* @param _from Current owner of the tulip.
* @param _to New owner of the tulip
* @param _tulipId The tulip to be transfered
*/
function transferFrom(
address _from,
address _to,
uint256 _tulipId
)
external
whenNotPaused
{
// Safety checks for common mistakes.
require(_to != address(0));
require(_to != address(this));
// Check for approval and valid ownership
require(tulipIdToApproved[_tulipId] == msg.sender);
require(tulipIdToOwner[_tulipId] == _from);
// Do the transfer
_transfer(_from, _to, _tulipId);
}
/// @notice Returns metadata for the tulip.
/// @param _tulipId The tulip to recieve information on
function tokenMetadata(uint256 _tulipId, string _preferredTransport) external view returns (string infoUrl) {
// We will set the meta data scheme in an external contract
require(erc721Metadata != address(0));
// Contracts cannot return string to each other so we do this
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tulipId, _preferredTransport);
return _toString(buffer, count);
}
//// INTERNAL FUNCTIONS THAT ACTUALLY DO STUFF
// These are called by public facing functions after sanity checks
function _transfer(address _from, address _to, uint256 _tulipId) internal {
// Increase total Tulips owned by _to address
tulipOwnershipCount[_to]++;
// Decrease total Tulips owned by _from address, if _from address is not empty
if (_from != address(0)) {
tulipOwnershipCount[_from]--;
}
// Update mapping of tulipID -> ownerAddress
tulipIdToOwner[_tulipId] = _to;
// Emit the transfer event.
Transfer(_from, _to, _tulipId);
}
function _approve(uint256 _tulipId, address _approved) internal{
tulipIdToApproved[_tulipId] = _approved;
// Approve event is only sent on public facing function
}
//// UTILITY FUNCTIONS
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength)private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
function _memcpy(uint dest, uint src, uint len) private view {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
|
contract TulipsTokenInterface is TulipsStorage, ERC721 {
//// TOKEN SPECS & META DATA
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CryptoTulips";
string public constant symbol = "CT";
/*
* @dev This external contract will return Tulip metadata. We are making this changable in case
* we need to update our current uri scheme later on.
*/
ERC721Metadata public erc721Metadata;
/// @dev Set the address of the external contract that generates the metadata.
function setMetadataAddress(address _contractAddress) public onlyOperations {
erc721Metadata = ERC721Metadata(_contractAddress);
}
//// EVENTS
/*
* @dev Transfer event as defined in ERC721.
*/
event Transfer(address from, address to, uint256 tokenId);
/*
* @dev Approval event as defined in ERC721.
*/
event Approval(address owner, address approved, uint256 tokenId);
//// TRANSFER DATA
/*
* @dev Maps tulipId to approved transfer address
*/
mapping (uint256 => address) public tulipIdToApproved;
//// PUBLIC FACING FUNCTIONS
/*
* @notice Returns total number of Tulips created so far.
*/
function totalSupply() public view returns (uint) {
return tulips.length - 1;
}
/*
* @notice Returns the number of Tulips owned by given address.
* @param _owner The Tulip owner.
*/
function balanceOf(address _owner) public view returns (uint256 count) {
return tulipOwnershipCount[_owner];
}
/*
* @notice Returns the owner of the given Tulip
*/
function ownerOf(uint256 _tulipId)
external
view
returns (address owner)
{
owner = tulipIdToOwner[_tulipId];
// If owner adress is empty this is still a fresh Tulip waiting for its first owner.
require(owner != address(0));
}
/*
* @notice Unlocks the tulip for transfer. The reciever can calltransferFrom() to
* get ownership of the tulip. This is a safer method since you can revoke the transfer
* if you mistakenly send it to an invalid address.
* @param _to The reciever address. Set to address(0) to revoke the approval.
* @param _tulipId The tulip to be transfered
*/
function approve(
address _to,
uint256 _tulipId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(tulipIdToOwner[_tulipId] == msg.sender);
// Register the approval
_approve(_tulipId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tulipId);
}
/*
* @notice Transfers a tulip to another address without confirmation.
* If the reciever's address is invalid tulip may be lost! Use approve() and transferFrom() instead.
* @param _to The reciever address.
* @param _tulipId The tulip to be transfered
*/
function transfer(
address _to,
uint256 _tulipId
)
external
whenNotPaused
{
// Safety checks for common mistakes.
require(_to != address(0));
require(_to != address(this));
// You can only send tulips you own.
require(tulipIdToOwner[_tulipId] == msg.sender);
// Do the transfer
_transfer(msg.sender, _to, _tulipId);
}
/*
* @notice This method allows the caller to recieve a tulip if the caller is the approved address
* caller can also give another address to recieve the tulip.
* @param _from Current owner of the tulip.
* @param _to New owner of the tulip
* @param _tulipId The tulip to be transfered
*/
function transferFrom(
address _from,
address _to,
uint256 _tulipId
)
external
whenNotPaused
{
// Safety checks for common mistakes.
require(_to != address(0));
require(_to != address(this));
// Check for approval and valid ownership
require(tulipIdToApproved[_tulipId] == msg.sender);
require(tulipIdToOwner[_tulipId] == _from);
// Do the transfer
_transfer(_from, _to, _tulipId);
}
/// @notice Returns metadata for the tulip.
/// @param _tulipId The tulip to recieve information on
function tokenMetadata(uint256 _tulipId, string _preferredTransport) external view returns (string infoUrl) {
// We will set the meta data scheme in an external contract
require(erc721Metadata != address(0));
// Contracts cannot return string to each other so we do this
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tulipId, _preferredTransport);
return _toString(buffer, count);
}
//// INTERNAL FUNCTIONS THAT ACTUALLY DO STUFF
// These are called by public facing functions after sanity checks
function _transfer(address _from, address _to, uint256 _tulipId) internal {
// Increase total Tulips owned by _to address
tulipOwnershipCount[_to]++;
// Decrease total Tulips owned by _from address, if _from address is not empty
if (_from != address(0)) {
tulipOwnershipCount[_from]--;
}
// Update mapping of tulipID -> ownerAddress
tulipIdToOwner[_tulipId] = _to;
// Emit the transfer event.
Transfer(_from, _to, _tulipId);
}
function _approve(uint256 _tulipId, address _approved) internal{
tulipIdToApproved[_tulipId] = _approved;
// Approve event is only sent on public facing function
}
//// UTILITY FUNCTIONS
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength)private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
function _memcpy(uint dest, uint src, uint len) private view {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
| 46,932
|
17
|
// emergency rescue to allow unstaking without any checks but without $WOOL
|
bool public rescueEnabled = false;
|
bool public rescueEnabled = false;
| 30,189
|
162
|
// DEX Lottery. It is a contract for a lottery system usingrandomness provided externally. /
|
contract DEXLottery is ReentrancyGuard, IDEXLottery, Ownable {
using SafeERC20 for IERC20;
address public injectorAddress;
address public operatorAddress;
address public treasuryAddress;
uint256 public currentLotteryId;
uint256 public currentTicketId;
uint256 public maxNumberTicketsPerBuyOrClaim = 100;
uint256 public maxPriceTicketInDexToken = 500000000 ether;
uint256 public minPriceTicketInDexToken = 0.00005 ether;
uint256 public pendingInjectionNextLottery;
uint256 public constant MIN_DISCOUNT_DIVISOR = 100;
uint256 public constant MIN_LENGTH_LOTTERY = 1 hours - 5 minutes; // 1 hours
uint256 public constant MAX_LENGTH_LOTTERY = 30 days + 5 minutes; // 30 days
uint256 public constant MAX_TREASURY_FEE = 9000; // 90%
IERC20 public dexTokenToken;
IRandomNumberGenerator public randomGenerator;
enum Status {
Pending,
Open,
Close,
Claimable
}
struct Lottery {
Status status;
uint256 startTime;
uint256 endTime;
uint256 priceTicketInDexToken;
uint256 discountDivisor;
uint256[6] rewardsBreakdown; // 0: 1 matching number // 5: 6 matching numbers
uint256 treasuryFee; // 500: 5% // 200: 2% // 50: 0.5%
uint256[6] dexTokenPerBracket;
uint256[6] countWinnersPerBracket;
uint256 firstTicketId;
uint256 firstTicketIdNextLottery;
uint256 amountCollectedInDexToken;
uint32 finalNumber;
}
struct Ticket {
uint32 number;
address owner;
}
// Mapping are cheaper than arrays
mapping(uint256 => Lottery) private _lotteries;
mapping(uint256 => Ticket) private _tickets;
// Bracket calculator is used for verifying claims for ticket prizes
mapping(uint32 => uint32) private _bracketCalculator;
// Keeps track of number of ticket per unique combination for each lotteryId
mapping(uint256 => mapping(uint32 => uint256)) private _numberTicketsPerLotteryId;
// Keep track of user ticket ids for a given lotteryId
mapping(address => mapping(uint256 => uint256[])) private _userTicketIdsPerLotteryId;
modifier notContract() {
require(!_isContract(msg.sender), "Contract not allowed");
require(msg.sender == tx.origin, "Proxy contract not allowed");
_;
}
modifier onlyOperator() {
require(msg.sender == operatorAddress, "Not operator");
_;
}
modifier onlyOwnerOrInjector() {
require((msg.sender == owner()) || (msg.sender == injectorAddress), "Not owner or injector");
_;
}
event AdminTokenRecovery(address token, uint256 amount);
event LotteryClose(uint256 indexed lotteryId, uint256 firstTicketIdNextLottery);
event LotteryInjection(uint256 indexed lotteryId, uint256 injectedAmount);
event LotteryOpen(
uint256 indexed lotteryId,
uint256 startTime,
uint256 endTime,
uint256 priceTicketInDexToken,
uint256 firstTicketId,
uint256 injectedAmount
);
event LotteryNumberDrawn(uint256 indexed lotteryId, uint256 finalNumber, uint256 countWinningTickets);
event NewOperatorAndTreasuryAndInjectorAddresses(address operator, address treasury, address injector);
event NewRandomGenerator(address indexed randomGenerator);
event TicketsPurchase(address indexed buyer, uint256 indexed lotteryId, uint256 numberTickets);
event TicketsClaim(address indexed claimer, uint256 amount, uint256 indexed lotteryId, uint256 numberTickets);
/**
* @notice Constructor
* @dev RandomNumberGenerator must be deployed prior to this contract
* @param _dexTokenTokenAddress: address of the DEXToken token
* @param _randomGeneratorAddress: address of the RandomGenerator contract used to work with ChainLink VRF
*/
constructor(address _dexTokenTokenAddress, address _randomGeneratorAddress) {
dexTokenToken = IERC20(_dexTokenTokenAddress);
randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress);
// Initializes a mapping
_bracketCalculator[0] = 1;
_bracketCalculator[1] = 11;
_bracketCalculator[2] = 111;
_bracketCalculator[3] = 1111;
_bracketCalculator[4] = 11111;
_bracketCalculator[5] = 111111;
}
/**
* @notice Buy tickets for the current lottery
* @param _lotteryId: lotteryId
* @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999
* @dev Callable by users
*/
function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers)
external
override
notContract
nonReentrant
{
require(_ticketNumbers.length != 0, "No ticket specified");
require(_ticketNumbers.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets");
require(_lotteries[_lotteryId].status == Status.Open, "Lottery is not open");
require(block.timestamp < _lotteries[_lotteryId].endTime, "Lottery is over");
// Calculate number of DEXToken to this contract
uint256 amountDexTokenToTransfer = _calculateTotalPriceForBulkTickets(
_lotteries[_lotteryId].discountDivisor,
_lotteries[_lotteryId].priceTicketInDexToken,
_ticketNumbers.length
);
// Transfer dexToken tokens to this contract
dexTokenToken.safeTransferFrom(address(msg.sender), address(this), amountDexTokenToTransfer);
// Increment the total amount collected for the lottery round
_lotteries[_lotteryId].amountCollectedInDexToken += amountDexTokenToTransfer;
for (uint256 i = 0; i < _ticketNumbers.length; i++) {
uint32 thisTicketNumber = _ticketNumbers[i];
require((thisTicketNumber >= 1000000) && (thisTicketNumber <= 1999999), "Outside range");
_numberTicketsPerLotteryId[_lotteryId][1 + (thisTicketNumber % 10)]++;
_numberTicketsPerLotteryId[_lotteryId][11 + (thisTicketNumber % 100)]++;
_numberTicketsPerLotteryId[_lotteryId][111 + (thisTicketNumber % 1000)]++;
_numberTicketsPerLotteryId[_lotteryId][1111 + (thisTicketNumber % 10000)]++;
_numberTicketsPerLotteryId[_lotteryId][11111 + (thisTicketNumber % 100000)]++;
_numberTicketsPerLotteryId[_lotteryId][111111 + (thisTicketNumber % 1000000)]++;
_userTicketIdsPerLotteryId[msg.sender][_lotteryId].push(currentTicketId);
_tickets[currentTicketId] = Ticket({number: thisTicketNumber, owner: msg.sender});
// Increase lottery ticket number
currentTicketId++;
}
emit TicketsPurchase(msg.sender, _lotteryId, _ticketNumbers.length);
}
/**
* @notice Claim a set of winning tickets for a lottery
* @param _lotteryId: lottery id
* @param _ticketIds: array of ticket ids
* @param _brackets: array of brackets for the ticket ids
* @dev Callable by users only, not contract!
*/
function claimTickets(
uint256 _lotteryId,
uint256[] calldata _ticketIds,
uint32[] calldata _brackets
) external override notContract nonReentrant {
require(_ticketIds.length == _brackets.length, "Not same length");
require(_ticketIds.length != 0, "Length must be >0");
require(_ticketIds.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets");
require(_lotteries[_lotteryId].status == Status.Claimable, "Lottery not claimable");
// Initializes the rewardInDexTokenToTransfer
uint256 rewardInDexTokenToTransfer;
for (uint256 i = 0; i < _ticketIds.length; i++) {
require(_brackets[i] < 6, "Bracket out of range"); // Must be between 0 and 5
uint256 thisTicketId = _ticketIds[i];
require(_lotteries[_lotteryId].firstTicketIdNextLottery > thisTicketId, "TicketId too high");
require(_lotteries[_lotteryId].firstTicketId <= thisTicketId, "TicketId too low");
require(msg.sender == _tickets[thisTicketId].owner, "Not the owner");
// Update the lottery ticket owner to 0x address
_tickets[thisTicketId].owner = address(0);
uint256 rewardForTicketId = _calculateRewardsForTicketId(_lotteryId, thisTicketId, _brackets[i]);
// Check user is claiming the correct bracket
require(rewardForTicketId != 0, "No prize for this bracket");
if (_brackets[i] != 5) {
require(
_calculateRewardsForTicketId(_lotteryId, thisTicketId, _brackets[i] + 1) == 0,
"Bracket must be higher"
);
}
// Increment the reward to transfer
rewardInDexTokenToTransfer += rewardForTicketId;
}
// Transfer money to msg.sender
dexTokenToken.safeTransfer(msg.sender, rewardInDexTokenToTransfer);
emit TicketsClaim(msg.sender, rewardInDexTokenToTransfer, _lotteryId, _ticketIds.length);
}
/**
* @notice Close lottery
* @param _lotteryId: lottery id
* @dev Callable by operator
*/
function closeLottery(uint256 _lotteryId) external override onlyOperator nonReentrant {
require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open");
require(block.timestamp > _lotteries[_lotteryId].endTime, "Lottery not over");
_lotteries[_lotteryId].firstTicketIdNextLottery = currentTicketId;
// Request a random number from the generator based on a seed
randomGenerator.getRandomNumber(uint256(keccak256(abi.encodePacked(_lotteryId, currentTicketId))));
_lotteries[_lotteryId].status = Status.Close;
emit LotteryClose(_lotteryId, currentTicketId);
}
/**
* @notice Draw the final number, calculate reward in DEXToken per group, and make lottery claimable
* @param _lotteryId: lottery id
* @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all)
* @dev Callable by operator
*/
function drawFinalNumberAndMakeLotteryClaimable(uint256 _lotteryId, bool _autoInjection)
external
override
onlyOperator
nonReentrant
{
require(_lotteries[_lotteryId].status == Status.Close, "Lottery not close");
require(_lotteryId == randomGenerator.viewLatestLotteryId(), "Numbers not drawn");
// Calculate the finalNumber based on the randomResult generated by ChainLink's fallback
uint32 finalNumber = randomGenerator.viewRandomResult();
// Initialize a number to count addresses in the previous bracket
uint256 numberAddressesInPreviousBracket;
// Calculate the amount to share post-treasury fee
uint256 amountToShareToWinners = (
((_lotteries[_lotteryId].amountCollectedInDexToken) * (10000 - _lotteries[_lotteryId].treasuryFee))
) / 10000;
// Initializes the amount to withdraw to treasury
uint256 amountToWithdrawToTreasury;
// Calculate prizes in DEXToken for each bracket by starting from the highest one
for (uint32 i = 0; i < 6; i++) {
uint32 j = 5 - i;
uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1)));
_lotteries[_lotteryId].countWinnersPerBracket[j] =
_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] -
numberAddressesInPreviousBracket;
// A. If number of users for this _bracket number is superior to 0
if (
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket) !=
0
) {
// B. If rewards at this bracket are > 0, calculate, else, report the numberAddresses from previous bracket
if (_lotteries[_lotteryId].rewardsBreakdown[j] != 0) {
_lotteries[_lotteryId].dexTokenPerBracket[j] =
((_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) /
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] -
numberAddressesInPreviousBracket)) /
10000;
// Update numberAddressesInPreviousBracket
numberAddressesInPreviousBracket = _numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber];
}
// A. No DEXToken to distribute, they are added to the amount to withdraw to treasury address
} else {
_lotteries[_lotteryId].dexTokenPerBracket[j] = 0;
amountToWithdrawToTreasury +=
(_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) /
10000;
}
}
// Update internal statuses for lottery
_lotteries[_lotteryId].finalNumber = finalNumber;
_lotteries[_lotteryId].status = Status.Claimable;
if (_autoInjection) {
pendingInjectionNextLottery = amountToWithdrawToTreasury;
amountToWithdrawToTreasury = 0;
}
amountToWithdrawToTreasury += (_lotteries[_lotteryId].amountCollectedInDexToken - amountToShareToWinners);
// Transfer DEXToken to treasury address
dexTokenToken.safeTransfer(treasuryAddress, amountToWithdrawToTreasury);
emit LotteryNumberDrawn(currentLotteryId, finalNumber, numberAddressesInPreviousBracket);
}
/**
* @notice Change the random generator
* @dev The calls to functions are used to verify the new generator implements them properly.
* It is necessary to wait for the VRF response before starting a round.
* Callable only by the contract owner
* @param _randomGeneratorAddress: address of the random generator
*/
function changeRandomGenerator(address _randomGeneratorAddress) external onlyOwner {
require(_lotteries[currentLotteryId].status == Status.Claimable, "Lottery not in claimable");
// Request a random number from the generator based on a seed
IRandomNumberGenerator(_randomGeneratorAddress).getRandomNumber(
uint256(keccak256(abi.encodePacked(currentLotteryId, currentTicketId)))
);
// Calculate the finalNumber based on the randomResult generated by ChainLink's fallback
IRandomNumberGenerator(_randomGeneratorAddress).viewRandomResult();
randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress);
emit NewRandomGenerator(_randomGeneratorAddress);
}
/**
* @notice Inject funds
* @param _lotteryId: lottery id
* @param _amount: amount to inject in DEXToken token
* @dev Callable by owner or injector address
*/
function injectFunds(uint256 _lotteryId, uint256 _amount) external override onlyOwnerOrInjector {
require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open");
dexTokenToken.safeTransferFrom(address(msg.sender), address(this), _amount);
_lotteries[_lotteryId].amountCollectedInDexToken += _amount;
emit LotteryInjection(_lotteryId, _amount);
}
/**
* @notice Start the lottery
* @dev Callable by operator
* @param _endTime: endTime of the lottery
* @param _priceTicketInDexToken: price of a ticket in DEXToken
* @param _discountDivisor: the divisor to calculate the discount magnitude for bulks
* @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000)
* @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%)
*/
function startLottery(
uint256 _endTime,
uint256 _priceTicketInDexToken,
uint256 _discountDivisor,
uint256[6] calldata _rewardsBreakdown,
uint256 _treasuryFee
) external override onlyOperator {
require(
(currentLotteryId == 0) || (_lotteries[currentLotteryId].status == Status.Claimable),
"Not time to start lottery"
);
require(
((_endTime - block.timestamp) > MIN_LENGTH_LOTTERY) && ((_endTime - block.timestamp) < MAX_LENGTH_LOTTERY),
"Lottery length outside of range"
);
require(
(_priceTicketInDexToken >= minPriceTicketInDexToken) && (_priceTicketInDexToken <= maxPriceTicketInDexToken),
"Outside of limits"
);
require(_discountDivisor >= MIN_DISCOUNT_DIVISOR, "Discount divisor too low");
require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high");
require(
(_rewardsBreakdown[0] +
_rewardsBreakdown[1] +
_rewardsBreakdown[2] +
_rewardsBreakdown[3] +
_rewardsBreakdown[4] +
_rewardsBreakdown[5]) == 10000,
"Rewards must equal 10000"
);
currentLotteryId++;
_lotteries[currentLotteryId] = Lottery({
status: Status.Open,
startTime: block.timestamp,
endTime: _endTime,
priceTicketInDexToken: _priceTicketInDexToken,
discountDivisor: _discountDivisor,
rewardsBreakdown: _rewardsBreakdown,
treasuryFee: _treasuryFee,
dexTokenPerBracket: [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)],
countWinnersPerBracket: [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)],
firstTicketId: currentTicketId,
firstTicketIdNextLottery: currentTicketId,
amountCollectedInDexToken: pendingInjectionNextLottery,
finalNumber: 0
});
emit LotteryOpen(
currentLotteryId,
block.timestamp,
_endTime,
_priceTicketInDexToken,
currentTicketId,
pendingInjectionNextLottery
);
pendingInjectionNextLottery = 0;
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of token amount to withdraw
* @dev Only callable by owner.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(dexTokenToken), "Cannot be DEXToken token");
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/**
* @notice Set DEXToken price ticket upper/lower limit
* @dev Only callable by owner
* @param _minPriceTicketInDexToken: minimum price of a ticket in DEXToken
* @param _maxPriceTicketInDexToken: maximum price of a ticket in DEXToken
*/
function setMinAndMaxTicketPriceInDexToken(uint256 _minPriceTicketInDexToken, uint256 _maxPriceTicketInDexToken)
external
onlyOwner
{
minPriceTicketInDexToken = _minPriceTicketInDexToken;
maxPriceTicketInDexToken = _maxPriceTicketInDexToken;
}
/**
* @notice Set max number of tickets
* @dev Only callable by owner
*/
function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner {
require(_maxNumberTicketsPerBuy != 0, "Must be > 0");
maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy;
}
/**
* @notice Set operator, treasury, and injector addresses
* @dev Only callable by owner
* @param _operatorAddress: address of the operator
* @param _treasuryAddress: address of the treasury
* @param _injectorAddress: address of the injector
*/
function setOperatorAndTreasuryAndInjectorAddresses(
address _operatorAddress,
address _treasuryAddress,
address _injectorAddress
) external onlyOwner {
require(_operatorAddress != address(0), "Cannot be zero address");
require(_treasuryAddress != address(0), "Cannot be zero address");
require(_injectorAddress != address(0), "Cannot be zero address");
operatorAddress = _operatorAddress;
treasuryAddress = _treasuryAddress;
injectorAddress = _injectorAddress;
emit NewOperatorAndTreasuryAndInjectorAddresses(_operatorAddress, _treasuryAddress, _injectorAddress);
}
/**
* @notice Calculate price of a set of tickets
* @param _discountDivisor: divisor for the discount
* @param _priceTicket price of a ticket (in DEXToken)
* @param _numberTickets number of tickets to buy
*/
function calculateTotalPriceForBulkTickets(
uint256 _discountDivisor,
uint256 _priceTicket,
uint256 _numberTickets
) external pure returns (uint256) {
require(_discountDivisor >= MIN_DISCOUNT_DIVISOR, "Must be >= MIN_DISCOUNT_DIVISOR");
require(_numberTickets != 0, "Number of tickets must be > 0");
return _calculateTotalPriceForBulkTickets(_discountDivisor, _priceTicket, _numberTickets);
}
/**
* @notice View current lottery id
*/
function viewCurrentLotteryId() external view override returns (uint256) {
return currentLotteryId;
}
/**
* @notice View lottery information
* @param _lotteryId: lottery id
*/
function viewLottery(uint256 _lotteryId) external view returns (Lottery memory) {
return _lotteries[_lotteryId];
}
/**
* @notice View ticker statuses and numbers for an array of ticket ids
* @param _ticketIds: array of _ticketId
*/
function viewNumbersAndStatusesForTicketIds(uint256[] calldata _ticketIds)
external
view
returns (uint32[] memory, bool[] memory)
{
uint256 length = _ticketIds.length;
uint32[] memory ticketNumbers = new uint32[](length);
bool[] memory ticketStatuses = new bool[](length);
for (uint256 i = 0; i < length; i++) {
ticketNumbers[i] = _tickets[_ticketIds[i]].number;
if (_tickets[_ticketIds[i]].owner == address(0)) {
ticketStatuses[i] = true;
} else {
ticketStatuses[i] = false;
}
}
return (ticketNumbers, ticketStatuses);
}
/**
* @notice View rewards for a given ticket, providing a bracket, and lottery id
* @dev Computations are mostly offchain. This is used to verify a ticket!
* @param _lotteryId: lottery id
* @param _ticketId: ticket id
* @param _bracket: bracket for the ticketId to verify the claim and calculate rewards
*/
function viewRewardsForTicketId(
uint256 _lotteryId,
uint256 _ticketId,
uint32 _bracket
) external view returns (uint256) {
// Check lottery is in claimable status
if (_lotteries[_lotteryId].status != Status.Claimable) {
return 0;
}
// Check ticketId is within range
if (
(_lotteries[_lotteryId].firstTicketIdNextLottery < _ticketId) &&
(_lotteries[_lotteryId].firstTicketId >= _ticketId)
) {
return 0;
}
return _calculateRewardsForTicketId(_lotteryId, _ticketId, _bracket);
}
/**
* @notice View user ticket ids, numbers, and statuses of user for a given lottery
* @param _user: user address
* @param _lotteryId: lottery id
* @param _cursor: cursor to start where to retrieve the tickets
* @param _size: the number of tickets to retrieve
*/
function viewUserInfoForLotteryId(
address _user,
uint256 _lotteryId,
uint256 _cursor,
uint256 _size
)
external
view
returns (
uint256[] memory,
uint32[] memory,
bool[] memory,
uint256
)
{
uint256 length = _size;
uint256 numberTicketsBoughtAtLotteryId = _userTicketIdsPerLotteryId[_user][_lotteryId].length;
if (length > (numberTicketsBoughtAtLotteryId - _cursor)) {
length = numberTicketsBoughtAtLotteryId - _cursor;
}
uint256[] memory lotteryTicketIds = new uint256[](length);
uint32[] memory ticketNumbers = new uint32[](length);
bool[] memory ticketStatuses = new bool[](length);
for (uint256 i = 0; i < length; i++) {
lotteryTicketIds[i] = _userTicketIdsPerLotteryId[_user][_lotteryId][i + _cursor];
ticketNumbers[i] = _tickets[lotteryTicketIds[i]].number;
// True = ticket claimed
if (_tickets[lotteryTicketIds[i]].owner == address(0)) {
ticketStatuses[i] = true;
} else {
// ticket not claimed (includes the ones that cannot be claimed)
ticketStatuses[i] = false;
}
}
return (lotteryTicketIds, ticketNumbers, ticketStatuses, _cursor + length);
}
/**
* @notice Calculate rewards for a given ticket
* @param _lotteryId: lottery id
* @param _ticketId: ticket id
* @param _bracket: bracket for the ticketId to verify the claim and calculate rewards
*/
function _calculateRewardsForTicketId(
uint256 _lotteryId,
uint256 _ticketId,
uint32 _bracket
) internal view returns (uint256) {
// Retrieve the winning number combination
uint32 userNumber = _lotteries[_lotteryId].finalNumber;
// Retrieve the user number combination from the ticketId
uint32 winningTicketNumber = _tickets[_ticketId].number;
// Apply transformation to verify the claim provided by the user is true
uint32 transformedWinningNumber = _bracketCalculator[_bracket] +
(winningTicketNumber % (uint32(10)**(_bracket + 1)));
uint32 transformedUserNumber = _bracketCalculator[_bracket] + (userNumber % (uint32(10)**(_bracket + 1)));
// Confirm that the two transformed numbers are the same, if not throw
if (transformedWinningNumber == transformedUserNumber) {
return _lotteries[_lotteryId].dexTokenPerBracket[_bracket];
} else {
return 0;
}
}
/**
* @notice Calculate final price for bulk of tickets
* @param _discountDivisor: divisor for the discount (the smaller it is, the greater the discount is)
* @param _priceTicket: price of a ticket
* @param _numberTickets: number of tickets purchased
*/
function _calculateTotalPriceForBulkTickets(
uint256 _discountDivisor,
uint256 _priceTicket,
uint256 _numberTickets
) internal pure returns (uint256) {
return (_priceTicket * _numberTickets * (_discountDivisor + 1 - _numberTickets)) / _discountDivisor;
}
/**
* @notice Check if an address is a contract
*/
function _isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
}
|
contract DEXLottery is ReentrancyGuard, IDEXLottery, Ownable {
using SafeERC20 for IERC20;
address public injectorAddress;
address public operatorAddress;
address public treasuryAddress;
uint256 public currentLotteryId;
uint256 public currentTicketId;
uint256 public maxNumberTicketsPerBuyOrClaim = 100;
uint256 public maxPriceTicketInDexToken = 500000000 ether;
uint256 public minPriceTicketInDexToken = 0.00005 ether;
uint256 public pendingInjectionNextLottery;
uint256 public constant MIN_DISCOUNT_DIVISOR = 100;
uint256 public constant MIN_LENGTH_LOTTERY = 1 hours - 5 minutes; // 1 hours
uint256 public constant MAX_LENGTH_LOTTERY = 30 days + 5 minutes; // 30 days
uint256 public constant MAX_TREASURY_FEE = 9000; // 90%
IERC20 public dexTokenToken;
IRandomNumberGenerator public randomGenerator;
enum Status {
Pending,
Open,
Close,
Claimable
}
struct Lottery {
Status status;
uint256 startTime;
uint256 endTime;
uint256 priceTicketInDexToken;
uint256 discountDivisor;
uint256[6] rewardsBreakdown; // 0: 1 matching number // 5: 6 matching numbers
uint256 treasuryFee; // 500: 5% // 200: 2% // 50: 0.5%
uint256[6] dexTokenPerBracket;
uint256[6] countWinnersPerBracket;
uint256 firstTicketId;
uint256 firstTicketIdNextLottery;
uint256 amountCollectedInDexToken;
uint32 finalNumber;
}
struct Ticket {
uint32 number;
address owner;
}
// Mapping are cheaper than arrays
mapping(uint256 => Lottery) private _lotteries;
mapping(uint256 => Ticket) private _tickets;
// Bracket calculator is used for verifying claims for ticket prizes
mapping(uint32 => uint32) private _bracketCalculator;
// Keeps track of number of ticket per unique combination for each lotteryId
mapping(uint256 => mapping(uint32 => uint256)) private _numberTicketsPerLotteryId;
// Keep track of user ticket ids for a given lotteryId
mapping(address => mapping(uint256 => uint256[])) private _userTicketIdsPerLotteryId;
modifier notContract() {
require(!_isContract(msg.sender), "Contract not allowed");
require(msg.sender == tx.origin, "Proxy contract not allowed");
_;
}
modifier onlyOperator() {
require(msg.sender == operatorAddress, "Not operator");
_;
}
modifier onlyOwnerOrInjector() {
require((msg.sender == owner()) || (msg.sender == injectorAddress), "Not owner or injector");
_;
}
event AdminTokenRecovery(address token, uint256 amount);
event LotteryClose(uint256 indexed lotteryId, uint256 firstTicketIdNextLottery);
event LotteryInjection(uint256 indexed lotteryId, uint256 injectedAmount);
event LotteryOpen(
uint256 indexed lotteryId,
uint256 startTime,
uint256 endTime,
uint256 priceTicketInDexToken,
uint256 firstTicketId,
uint256 injectedAmount
);
event LotteryNumberDrawn(uint256 indexed lotteryId, uint256 finalNumber, uint256 countWinningTickets);
event NewOperatorAndTreasuryAndInjectorAddresses(address operator, address treasury, address injector);
event NewRandomGenerator(address indexed randomGenerator);
event TicketsPurchase(address indexed buyer, uint256 indexed lotteryId, uint256 numberTickets);
event TicketsClaim(address indexed claimer, uint256 amount, uint256 indexed lotteryId, uint256 numberTickets);
/**
* @notice Constructor
* @dev RandomNumberGenerator must be deployed prior to this contract
* @param _dexTokenTokenAddress: address of the DEXToken token
* @param _randomGeneratorAddress: address of the RandomGenerator contract used to work with ChainLink VRF
*/
constructor(address _dexTokenTokenAddress, address _randomGeneratorAddress) {
dexTokenToken = IERC20(_dexTokenTokenAddress);
randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress);
// Initializes a mapping
_bracketCalculator[0] = 1;
_bracketCalculator[1] = 11;
_bracketCalculator[2] = 111;
_bracketCalculator[3] = 1111;
_bracketCalculator[4] = 11111;
_bracketCalculator[5] = 111111;
}
/**
* @notice Buy tickets for the current lottery
* @param _lotteryId: lotteryId
* @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999
* @dev Callable by users
*/
function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers)
external
override
notContract
nonReentrant
{
require(_ticketNumbers.length != 0, "No ticket specified");
require(_ticketNumbers.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets");
require(_lotteries[_lotteryId].status == Status.Open, "Lottery is not open");
require(block.timestamp < _lotteries[_lotteryId].endTime, "Lottery is over");
// Calculate number of DEXToken to this contract
uint256 amountDexTokenToTransfer = _calculateTotalPriceForBulkTickets(
_lotteries[_lotteryId].discountDivisor,
_lotteries[_lotteryId].priceTicketInDexToken,
_ticketNumbers.length
);
// Transfer dexToken tokens to this contract
dexTokenToken.safeTransferFrom(address(msg.sender), address(this), amountDexTokenToTransfer);
// Increment the total amount collected for the lottery round
_lotteries[_lotteryId].amountCollectedInDexToken += amountDexTokenToTransfer;
for (uint256 i = 0; i < _ticketNumbers.length; i++) {
uint32 thisTicketNumber = _ticketNumbers[i];
require((thisTicketNumber >= 1000000) && (thisTicketNumber <= 1999999), "Outside range");
_numberTicketsPerLotteryId[_lotteryId][1 + (thisTicketNumber % 10)]++;
_numberTicketsPerLotteryId[_lotteryId][11 + (thisTicketNumber % 100)]++;
_numberTicketsPerLotteryId[_lotteryId][111 + (thisTicketNumber % 1000)]++;
_numberTicketsPerLotteryId[_lotteryId][1111 + (thisTicketNumber % 10000)]++;
_numberTicketsPerLotteryId[_lotteryId][11111 + (thisTicketNumber % 100000)]++;
_numberTicketsPerLotteryId[_lotteryId][111111 + (thisTicketNumber % 1000000)]++;
_userTicketIdsPerLotteryId[msg.sender][_lotteryId].push(currentTicketId);
_tickets[currentTicketId] = Ticket({number: thisTicketNumber, owner: msg.sender});
// Increase lottery ticket number
currentTicketId++;
}
emit TicketsPurchase(msg.sender, _lotteryId, _ticketNumbers.length);
}
/**
* @notice Claim a set of winning tickets for a lottery
* @param _lotteryId: lottery id
* @param _ticketIds: array of ticket ids
* @param _brackets: array of brackets for the ticket ids
* @dev Callable by users only, not contract!
*/
function claimTickets(
uint256 _lotteryId,
uint256[] calldata _ticketIds,
uint32[] calldata _brackets
) external override notContract nonReentrant {
require(_ticketIds.length == _brackets.length, "Not same length");
require(_ticketIds.length != 0, "Length must be >0");
require(_ticketIds.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets");
require(_lotteries[_lotteryId].status == Status.Claimable, "Lottery not claimable");
// Initializes the rewardInDexTokenToTransfer
uint256 rewardInDexTokenToTransfer;
for (uint256 i = 0; i < _ticketIds.length; i++) {
require(_brackets[i] < 6, "Bracket out of range"); // Must be between 0 and 5
uint256 thisTicketId = _ticketIds[i];
require(_lotteries[_lotteryId].firstTicketIdNextLottery > thisTicketId, "TicketId too high");
require(_lotteries[_lotteryId].firstTicketId <= thisTicketId, "TicketId too low");
require(msg.sender == _tickets[thisTicketId].owner, "Not the owner");
// Update the lottery ticket owner to 0x address
_tickets[thisTicketId].owner = address(0);
uint256 rewardForTicketId = _calculateRewardsForTicketId(_lotteryId, thisTicketId, _brackets[i]);
// Check user is claiming the correct bracket
require(rewardForTicketId != 0, "No prize for this bracket");
if (_brackets[i] != 5) {
require(
_calculateRewardsForTicketId(_lotteryId, thisTicketId, _brackets[i] + 1) == 0,
"Bracket must be higher"
);
}
// Increment the reward to transfer
rewardInDexTokenToTransfer += rewardForTicketId;
}
// Transfer money to msg.sender
dexTokenToken.safeTransfer(msg.sender, rewardInDexTokenToTransfer);
emit TicketsClaim(msg.sender, rewardInDexTokenToTransfer, _lotteryId, _ticketIds.length);
}
/**
* @notice Close lottery
* @param _lotteryId: lottery id
* @dev Callable by operator
*/
function closeLottery(uint256 _lotteryId) external override onlyOperator nonReentrant {
require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open");
require(block.timestamp > _lotteries[_lotteryId].endTime, "Lottery not over");
_lotteries[_lotteryId].firstTicketIdNextLottery = currentTicketId;
// Request a random number from the generator based on a seed
randomGenerator.getRandomNumber(uint256(keccak256(abi.encodePacked(_lotteryId, currentTicketId))));
_lotteries[_lotteryId].status = Status.Close;
emit LotteryClose(_lotteryId, currentTicketId);
}
/**
* @notice Draw the final number, calculate reward in DEXToken per group, and make lottery claimable
* @param _lotteryId: lottery id
* @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all)
* @dev Callable by operator
*/
function drawFinalNumberAndMakeLotteryClaimable(uint256 _lotteryId, bool _autoInjection)
external
override
onlyOperator
nonReentrant
{
require(_lotteries[_lotteryId].status == Status.Close, "Lottery not close");
require(_lotteryId == randomGenerator.viewLatestLotteryId(), "Numbers not drawn");
// Calculate the finalNumber based on the randomResult generated by ChainLink's fallback
uint32 finalNumber = randomGenerator.viewRandomResult();
// Initialize a number to count addresses in the previous bracket
uint256 numberAddressesInPreviousBracket;
// Calculate the amount to share post-treasury fee
uint256 amountToShareToWinners = (
((_lotteries[_lotteryId].amountCollectedInDexToken) * (10000 - _lotteries[_lotteryId].treasuryFee))
) / 10000;
// Initializes the amount to withdraw to treasury
uint256 amountToWithdrawToTreasury;
// Calculate prizes in DEXToken for each bracket by starting from the highest one
for (uint32 i = 0; i < 6; i++) {
uint32 j = 5 - i;
uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1)));
_lotteries[_lotteryId].countWinnersPerBracket[j] =
_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] -
numberAddressesInPreviousBracket;
// A. If number of users for this _bracket number is superior to 0
if (
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket) !=
0
) {
// B. If rewards at this bracket are > 0, calculate, else, report the numberAddresses from previous bracket
if (_lotteries[_lotteryId].rewardsBreakdown[j] != 0) {
_lotteries[_lotteryId].dexTokenPerBracket[j] =
((_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) /
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] -
numberAddressesInPreviousBracket)) /
10000;
// Update numberAddressesInPreviousBracket
numberAddressesInPreviousBracket = _numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber];
}
// A. No DEXToken to distribute, they are added to the amount to withdraw to treasury address
} else {
_lotteries[_lotteryId].dexTokenPerBracket[j] = 0;
amountToWithdrawToTreasury +=
(_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) /
10000;
}
}
// Update internal statuses for lottery
_lotteries[_lotteryId].finalNumber = finalNumber;
_lotteries[_lotteryId].status = Status.Claimable;
if (_autoInjection) {
pendingInjectionNextLottery = amountToWithdrawToTreasury;
amountToWithdrawToTreasury = 0;
}
amountToWithdrawToTreasury += (_lotteries[_lotteryId].amountCollectedInDexToken - amountToShareToWinners);
// Transfer DEXToken to treasury address
dexTokenToken.safeTransfer(treasuryAddress, amountToWithdrawToTreasury);
emit LotteryNumberDrawn(currentLotteryId, finalNumber, numberAddressesInPreviousBracket);
}
/**
* @notice Change the random generator
* @dev The calls to functions are used to verify the new generator implements them properly.
* It is necessary to wait for the VRF response before starting a round.
* Callable only by the contract owner
* @param _randomGeneratorAddress: address of the random generator
*/
function changeRandomGenerator(address _randomGeneratorAddress) external onlyOwner {
require(_lotteries[currentLotteryId].status == Status.Claimable, "Lottery not in claimable");
// Request a random number from the generator based on a seed
IRandomNumberGenerator(_randomGeneratorAddress).getRandomNumber(
uint256(keccak256(abi.encodePacked(currentLotteryId, currentTicketId)))
);
// Calculate the finalNumber based on the randomResult generated by ChainLink's fallback
IRandomNumberGenerator(_randomGeneratorAddress).viewRandomResult();
randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress);
emit NewRandomGenerator(_randomGeneratorAddress);
}
/**
* @notice Inject funds
* @param _lotteryId: lottery id
* @param _amount: amount to inject in DEXToken token
* @dev Callable by owner or injector address
*/
function injectFunds(uint256 _lotteryId, uint256 _amount) external override onlyOwnerOrInjector {
require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open");
dexTokenToken.safeTransferFrom(address(msg.sender), address(this), _amount);
_lotteries[_lotteryId].amountCollectedInDexToken += _amount;
emit LotteryInjection(_lotteryId, _amount);
}
/**
* @notice Start the lottery
* @dev Callable by operator
* @param _endTime: endTime of the lottery
* @param _priceTicketInDexToken: price of a ticket in DEXToken
* @param _discountDivisor: the divisor to calculate the discount magnitude for bulks
* @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000)
* @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%)
*/
function startLottery(
uint256 _endTime,
uint256 _priceTicketInDexToken,
uint256 _discountDivisor,
uint256[6] calldata _rewardsBreakdown,
uint256 _treasuryFee
) external override onlyOperator {
require(
(currentLotteryId == 0) || (_lotteries[currentLotteryId].status == Status.Claimable),
"Not time to start lottery"
);
require(
((_endTime - block.timestamp) > MIN_LENGTH_LOTTERY) && ((_endTime - block.timestamp) < MAX_LENGTH_LOTTERY),
"Lottery length outside of range"
);
require(
(_priceTicketInDexToken >= minPriceTicketInDexToken) && (_priceTicketInDexToken <= maxPriceTicketInDexToken),
"Outside of limits"
);
require(_discountDivisor >= MIN_DISCOUNT_DIVISOR, "Discount divisor too low");
require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high");
require(
(_rewardsBreakdown[0] +
_rewardsBreakdown[1] +
_rewardsBreakdown[2] +
_rewardsBreakdown[3] +
_rewardsBreakdown[4] +
_rewardsBreakdown[5]) == 10000,
"Rewards must equal 10000"
);
currentLotteryId++;
_lotteries[currentLotteryId] = Lottery({
status: Status.Open,
startTime: block.timestamp,
endTime: _endTime,
priceTicketInDexToken: _priceTicketInDexToken,
discountDivisor: _discountDivisor,
rewardsBreakdown: _rewardsBreakdown,
treasuryFee: _treasuryFee,
dexTokenPerBracket: [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)],
countWinnersPerBracket: [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)],
firstTicketId: currentTicketId,
firstTicketIdNextLottery: currentTicketId,
amountCollectedInDexToken: pendingInjectionNextLottery,
finalNumber: 0
});
emit LotteryOpen(
currentLotteryId,
block.timestamp,
_endTime,
_priceTicketInDexToken,
currentTicketId,
pendingInjectionNextLottery
);
pendingInjectionNextLottery = 0;
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of token amount to withdraw
* @dev Only callable by owner.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(dexTokenToken), "Cannot be DEXToken token");
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/**
* @notice Set DEXToken price ticket upper/lower limit
* @dev Only callable by owner
* @param _minPriceTicketInDexToken: minimum price of a ticket in DEXToken
* @param _maxPriceTicketInDexToken: maximum price of a ticket in DEXToken
*/
function setMinAndMaxTicketPriceInDexToken(uint256 _minPriceTicketInDexToken, uint256 _maxPriceTicketInDexToken)
external
onlyOwner
{
minPriceTicketInDexToken = _minPriceTicketInDexToken;
maxPriceTicketInDexToken = _maxPriceTicketInDexToken;
}
/**
* @notice Set max number of tickets
* @dev Only callable by owner
*/
function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner {
require(_maxNumberTicketsPerBuy != 0, "Must be > 0");
maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy;
}
/**
* @notice Set operator, treasury, and injector addresses
* @dev Only callable by owner
* @param _operatorAddress: address of the operator
* @param _treasuryAddress: address of the treasury
* @param _injectorAddress: address of the injector
*/
function setOperatorAndTreasuryAndInjectorAddresses(
address _operatorAddress,
address _treasuryAddress,
address _injectorAddress
) external onlyOwner {
require(_operatorAddress != address(0), "Cannot be zero address");
require(_treasuryAddress != address(0), "Cannot be zero address");
require(_injectorAddress != address(0), "Cannot be zero address");
operatorAddress = _operatorAddress;
treasuryAddress = _treasuryAddress;
injectorAddress = _injectorAddress;
emit NewOperatorAndTreasuryAndInjectorAddresses(_operatorAddress, _treasuryAddress, _injectorAddress);
}
/**
* @notice Calculate price of a set of tickets
* @param _discountDivisor: divisor for the discount
* @param _priceTicket price of a ticket (in DEXToken)
* @param _numberTickets number of tickets to buy
*/
function calculateTotalPriceForBulkTickets(
uint256 _discountDivisor,
uint256 _priceTicket,
uint256 _numberTickets
) external pure returns (uint256) {
require(_discountDivisor >= MIN_DISCOUNT_DIVISOR, "Must be >= MIN_DISCOUNT_DIVISOR");
require(_numberTickets != 0, "Number of tickets must be > 0");
return _calculateTotalPriceForBulkTickets(_discountDivisor, _priceTicket, _numberTickets);
}
/**
* @notice View current lottery id
*/
function viewCurrentLotteryId() external view override returns (uint256) {
return currentLotteryId;
}
/**
* @notice View lottery information
* @param _lotteryId: lottery id
*/
function viewLottery(uint256 _lotteryId) external view returns (Lottery memory) {
return _lotteries[_lotteryId];
}
/**
* @notice View ticker statuses and numbers for an array of ticket ids
* @param _ticketIds: array of _ticketId
*/
function viewNumbersAndStatusesForTicketIds(uint256[] calldata _ticketIds)
external
view
returns (uint32[] memory, bool[] memory)
{
uint256 length = _ticketIds.length;
uint32[] memory ticketNumbers = new uint32[](length);
bool[] memory ticketStatuses = new bool[](length);
for (uint256 i = 0; i < length; i++) {
ticketNumbers[i] = _tickets[_ticketIds[i]].number;
if (_tickets[_ticketIds[i]].owner == address(0)) {
ticketStatuses[i] = true;
} else {
ticketStatuses[i] = false;
}
}
return (ticketNumbers, ticketStatuses);
}
/**
* @notice View rewards for a given ticket, providing a bracket, and lottery id
* @dev Computations are mostly offchain. This is used to verify a ticket!
* @param _lotteryId: lottery id
* @param _ticketId: ticket id
* @param _bracket: bracket for the ticketId to verify the claim and calculate rewards
*/
function viewRewardsForTicketId(
uint256 _lotteryId,
uint256 _ticketId,
uint32 _bracket
) external view returns (uint256) {
// Check lottery is in claimable status
if (_lotteries[_lotteryId].status != Status.Claimable) {
return 0;
}
// Check ticketId is within range
if (
(_lotteries[_lotteryId].firstTicketIdNextLottery < _ticketId) &&
(_lotteries[_lotteryId].firstTicketId >= _ticketId)
) {
return 0;
}
return _calculateRewardsForTicketId(_lotteryId, _ticketId, _bracket);
}
/**
* @notice View user ticket ids, numbers, and statuses of user for a given lottery
* @param _user: user address
* @param _lotteryId: lottery id
* @param _cursor: cursor to start where to retrieve the tickets
* @param _size: the number of tickets to retrieve
*/
function viewUserInfoForLotteryId(
address _user,
uint256 _lotteryId,
uint256 _cursor,
uint256 _size
)
external
view
returns (
uint256[] memory,
uint32[] memory,
bool[] memory,
uint256
)
{
uint256 length = _size;
uint256 numberTicketsBoughtAtLotteryId = _userTicketIdsPerLotteryId[_user][_lotteryId].length;
if (length > (numberTicketsBoughtAtLotteryId - _cursor)) {
length = numberTicketsBoughtAtLotteryId - _cursor;
}
uint256[] memory lotteryTicketIds = new uint256[](length);
uint32[] memory ticketNumbers = new uint32[](length);
bool[] memory ticketStatuses = new bool[](length);
for (uint256 i = 0; i < length; i++) {
lotteryTicketIds[i] = _userTicketIdsPerLotteryId[_user][_lotteryId][i + _cursor];
ticketNumbers[i] = _tickets[lotteryTicketIds[i]].number;
// True = ticket claimed
if (_tickets[lotteryTicketIds[i]].owner == address(0)) {
ticketStatuses[i] = true;
} else {
// ticket not claimed (includes the ones that cannot be claimed)
ticketStatuses[i] = false;
}
}
return (lotteryTicketIds, ticketNumbers, ticketStatuses, _cursor + length);
}
/**
* @notice Calculate rewards for a given ticket
* @param _lotteryId: lottery id
* @param _ticketId: ticket id
* @param _bracket: bracket for the ticketId to verify the claim and calculate rewards
*/
function _calculateRewardsForTicketId(
uint256 _lotteryId,
uint256 _ticketId,
uint32 _bracket
) internal view returns (uint256) {
// Retrieve the winning number combination
uint32 userNumber = _lotteries[_lotteryId].finalNumber;
// Retrieve the user number combination from the ticketId
uint32 winningTicketNumber = _tickets[_ticketId].number;
// Apply transformation to verify the claim provided by the user is true
uint32 transformedWinningNumber = _bracketCalculator[_bracket] +
(winningTicketNumber % (uint32(10)**(_bracket + 1)));
uint32 transformedUserNumber = _bracketCalculator[_bracket] + (userNumber % (uint32(10)**(_bracket + 1)));
// Confirm that the two transformed numbers are the same, if not throw
if (transformedWinningNumber == transformedUserNumber) {
return _lotteries[_lotteryId].dexTokenPerBracket[_bracket];
} else {
return 0;
}
}
/**
* @notice Calculate final price for bulk of tickets
* @param _discountDivisor: divisor for the discount (the smaller it is, the greater the discount is)
* @param _priceTicket: price of a ticket
* @param _numberTickets: number of tickets purchased
*/
function _calculateTotalPriceForBulkTickets(
uint256 _discountDivisor,
uint256 _priceTicket,
uint256 _numberTickets
) internal pure returns (uint256) {
return (_priceTicket * _numberTickets * (_discountDivisor + 1 - _numberTickets)) / _discountDivisor;
}
/**
* @notice Check if an address is a contract
*/
function _isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
}
| 33,974
|
83
|
// effects emit event for off-chain indexing note: always emit a proposal event, even in the pathway of automatic approval, to simplify indexing expectations
|
emit ProposedArtistAddressesAndSplits(
_projectId,
_artistAddress,
_additionalPayeePrimarySales,
_additionalPayeePrimarySalesPercentage,
_additionalPayeeSecondarySales,
_additionalPayeeSecondarySalesPercentage
);
|
emit ProposedArtistAddressesAndSplits(
_projectId,
_artistAddress,
_additionalPayeePrimarySales,
_additionalPayeePrimarySalesPercentage,
_additionalPayeeSecondarySales,
_additionalPayeeSecondarySalesPercentage
);
| 20,292
|
4
|
// PrivateSale receive directly the tokens
|
AWN.transferFrom(tokOwner, buyerAddress, amount);
emit LockInvestor( buyerAddress, amount);
|
AWN.transferFrom(tokOwner, buyerAddress, amount);
emit LockInvestor( buyerAddress, amount);
| 18,026
|
154
|
// Current locked tokenAmount must always be > _splitAmount as (lockedERC20.tokenAmount - _splitAmount) will be the number of tokens retained in the original lock, while splitAmount will be the amount of tokenstransferred to the new lock
|
require(lockedERC20Amount > _splitAmount, "Insufficient balance to split");
require(_splitUnlockTime >= lockedERC20.unlockTime, "Smaller unlock time than existing");
|
require(lockedERC20Amount > _splitAmount, "Insufficient balance to split");
require(_splitUnlockTime >= lockedERC20.unlockTime, "Smaller unlock time than existing");
| 26,337
|
25
|
// Returns the downcasted uint40 from uint256, reverting onoverflow (when the input is greater than largest uint40). Counterpart to Solidity's `uint32` operator. Requirements: - input must fit into 40 bits /
|
function toUint40(uint256 value) internal pure returns (uint40) {
require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits");
return uint40(value);
}
|
function toUint40(uint256 value) internal pure returns (uint40) {
require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits");
return uint40(value);
}
| 25,550
|
15
|
// update older blocks in "backwards" direction, anchoring on more recent trusted blockhash must be batch of NUM_LEAVES blocks
|
function updateOld(bytes32 nextRoot, uint32 nextNumFinal, bytes calldata proofData) external {
(bytes32 prevHash, bytes32 endHash, uint32 startBlockNumber, uint32 endBlockNumber, bytes32 root) =
getBoundaryBlockData(proofData);
require(startBlockNumber % NUM_LEAVES == 0, "startBlockNumber not a multiple of NUM_LEAVES");
require(endBlockNumber - startBlockNumber == NUM_LEAVES - 1, "Updating with incorrect number of blocks");
require(
historicalRoots[endBlockNumber + 1] == keccak256(abi.encodePacked(endHash, nextRoot, nextNumFinal)),
"endHash does not match"
);
require(verifyRaw(proofData), "ZKP does not verify");
historicalRoots[startBlockNumber] = keccak256(abi.encodePacked(prevHash, root, NUM_LEAVES));
emit UpdateEvent(startBlockNumber, prevHash, root, NUM_LEAVES);
}
|
function updateOld(bytes32 nextRoot, uint32 nextNumFinal, bytes calldata proofData) external {
(bytes32 prevHash, bytes32 endHash, uint32 startBlockNumber, uint32 endBlockNumber, bytes32 root) =
getBoundaryBlockData(proofData);
require(startBlockNumber % NUM_LEAVES == 0, "startBlockNumber not a multiple of NUM_LEAVES");
require(endBlockNumber - startBlockNumber == NUM_LEAVES - 1, "Updating with incorrect number of blocks");
require(
historicalRoots[endBlockNumber + 1] == keccak256(abi.encodePacked(endHash, nextRoot, nextNumFinal)),
"endHash does not match"
);
require(verifyRaw(proofData), "ZKP does not verify");
historicalRoots[startBlockNumber] = keccak256(abi.encodePacked(prevHash, root, NUM_LEAVES));
emit UpdateEvent(startBlockNumber, prevHash, root, NUM_LEAVES);
}
| 5,947
|
68
|
// Decreases the allowance of spender to spend _msgSender() tokens spender The user allowed to spend on behalf of _msgSender() subtractedValue The amount being subtracted to the allowancereturn `true` /
|
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
|
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
| 37,719
|
45
|
// Given the list of versions, fetches all production vaults
|
function getProductionVaults() public view returns (VaultData[] memory) {
uint256 versionsCount = versions.length;
VaultData[] memory data = new VaultData[](versionsCount * VAULT_STATUS_LENGTH);
for (uint256 x = 0; x < versionsCount; x++) {
for (uint256 y = 0; y < VAULT_STATUS_LENGTH; y++) {
uint256 length = productionVaults[versions[x]][VaultStatus(y)].length();
VaultMetadata[] memory list = new VaultMetadata[](length);
for (uint256 z = 0; z < length; z++) {
VaultInfo storage vaultInfo = productionVaultInfoByVault[productionVaults[versions[x]][VaultStatus(y)].at(z)];
list[z] = VaultMetadata({vault: vaultInfo.vault, metadata: vaultInfo.metadata});
}
data[x * VAULT_STATUS_LENGTH + y] = VaultData({version: versions[x], status: VaultStatus(y), list: list});
}
}
return data;
}
|
function getProductionVaults() public view returns (VaultData[] memory) {
uint256 versionsCount = versions.length;
VaultData[] memory data = new VaultData[](versionsCount * VAULT_STATUS_LENGTH);
for (uint256 x = 0; x < versionsCount; x++) {
for (uint256 y = 0; y < VAULT_STATUS_LENGTH; y++) {
uint256 length = productionVaults[versions[x]][VaultStatus(y)].length();
VaultMetadata[] memory list = new VaultMetadata[](length);
for (uint256 z = 0; z < length; z++) {
VaultInfo storage vaultInfo = productionVaultInfoByVault[productionVaults[versions[x]][VaultStatus(y)].at(z)];
list[z] = VaultMetadata({vault: vaultInfo.vault, metadata: vaultInfo.metadata});
}
data[x * VAULT_STATUS_LENGTH + y] = VaultData({version: versions[x], status: VaultStatus(y), list: list});
}
}
return data;
}
| 41,577
|
129
|
// UserContractThis contracts creates for easy integration to the Tellor Systemby allowing smart contracts to read data off Tellor /
|
contract UsingTellor {
ITellor private tellor;
/*Constructor*/
/**
* @dev the constructor sets the storage address and owner
* @param _tellor is the TellorMaster address
*/
constructor(address payable _tellor) {
tellor = ITellor(_tellor);
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return uint value for requestId/timestamp submitted
*/
function retrieveData(uint256 _requestId, uint256 _timestamp)
public
view
returns (uint256)
{
return tellor.retrieveData(_requestId, _timestamp);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to looku p
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(uint256 _requestId, uint256 _timestamp)
public
view
returns (bool)
{
return tellor.isInDispute(_requestId, _timestamp);
}
/**
* @dev Counts the number of values that have been submited for the request
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(uint256 _requestId)
public
view
returns (uint256)
{
return tellor.getNewValueCountbyRequestId(_requestId);
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestId is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(uint256 _requestId, uint256 _index)
public
view
returns (uint256)
{
return tellor.getTimestampbyRequestIDandIndex(_requestId, _index);
}
/**
* @dev Allows the user to get the latest value for the requestId specified
* @param _requestId is the requestId to look up the value for
* @return ifRetrieve bool true if it is able to retreive a value, the value, and the value's timestamp
* @return value the value retrieved
* @return _timestampRetrieved the value's timestamp
*/
function getCurrentValue(uint256 _requestId)
public
view
returns (
bool ifRetrieve,
uint256 value,
uint256 _timestampRetrieved
)
{
uint256 _count = tellor.getNewValueCountbyRequestId(_requestId);
uint256 _time =
tellor.getTimestampbyRequestIDandIndex(_requestId, _count - 1);
uint256 _value = tellor.retrieveData(_requestId, _time);
if (_value > 0) return (true, _value, _time);
return (false, 0, _time);
}
// slither-disable-next-line calls-loop
function getIndexForDataBefore(uint256 _requestId, uint256 _timestamp)
public
view
returns (bool found, uint256 index)
{
uint256 _count = tellor.getNewValueCountbyRequestId(_requestId);
if (_count > 0) {
uint256 middle;
uint256 start = 0;
uint256 end = _count - 1;
uint256 _time;
//Checking Boundaries to short-circuit the algorithm
_time = tellor.getTimestampbyRequestIDandIndex(_requestId, start);
if (_time >= _timestamp) return (false, 0);
_time = tellor.getTimestampbyRequestIDandIndex(_requestId, end);
if (_time < _timestamp) return (true, end);
//Since the value is within our boundaries, do a binary search
while (true) {
middle = (end - start) / 2 + 1 + start;
_time = tellor.getTimestampbyRequestIDandIndex(
_requestId,
middle
);
if (_time < _timestamp) {
//get imeadiate next value
uint256 _nextTime =
tellor.getTimestampbyRequestIDandIndex(
_requestId,
middle + 1
);
if (_nextTime >= _timestamp) {
//_time is correct
return (true, middle);
} else {
//look from middle + 1(next value) to end
start = middle + 1;
}
} else {
uint256 _prevTime =
tellor.getTimestampbyRequestIDandIndex(
_requestId,
middle - 1
);
if (_prevTime < _timestamp) {
// _prevtime is correct
return (true, middle - 1);
} else {
//look from start to middle -1(prev value)
end = middle - 1;
}
}
//We couldn't found a value
//if(middle - 1 == start || middle == _count) return (false, 0);
}
}
return (false, 0);
}
/**
* @dev Allows the user to get the first value for the requestId before the specified timestamp
* @param _requestId is the requestId to look up the value for
* @param _timestamp before which to search for first verified value
* @return _ifRetrieve bool true if it is able to retreive a value, the value, and the value's timestamp
* @return _value the value retrieved
* @return _timestampRetrieved the value's timestamp
*/
function getDataBefore(uint256 _requestId, uint256 _timestamp)
public
view
returns (
bool _ifRetrieve,
uint256 _value,
uint256 _timestampRetrieved
)
{
(bool _found, uint256 _index) =
getIndexForDataBefore(_requestId, _timestamp);
if (!_found) return (false, 0, 0);
uint256 _time =
tellor.getTimestampbyRequestIDandIndex(_requestId, _index);
_value = tellor.retrieveData(_requestId, _time);
//If value is diputed it'll return zero
if (_value > 0) return (true, _value, _time);
return (false, 0, 0);
}
}
|
contract UsingTellor {
ITellor private tellor;
/*Constructor*/
/**
* @dev the constructor sets the storage address and owner
* @param _tellor is the TellorMaster address
*/
constructor(address payable _tellor) {
tellor = ITellor(_tellor);
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return uint value for requestId/timestamp submitted
*/
function retrieveData(uint256 _requestId, uint256 _timestamp)
public
view
returns (uint256)
{
return tellor.retrieveData(_requestId, _timestamp);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to looku p
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(uint256 _requestId, uint256 _timestamp)
public
view
returns (bool)
{
return tellor.isInDispute(_requestId, _timestamp);
}
/**
* @dev Counts the number of values that have been submited for the request
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(uint256 _requestId)
public
view
returns (uint256)
{
return tellor.getNewValueCountbyRequestId(_requestId);
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestId is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(uint256 _requestId, uint256 _index)
public
view
returns (uint256)
{
return tellor.getTimestampbyRequestIDandIndex(_requestId, _index);
}
/**
* @dev Allows the user to get the latest value for the requestId specified
* @param _requestId is the requestId to look up the value for
* @return ifRetrieve bool true if it is able to retreive a value, the value, and the value's timestamp
* @return value the value retrieved
* @return _timestampRetrieved the value's timestamp
*/
function getCurrentValue(uint256 _requestId)
public
view
returns (
bool ifRetrieve,
uint256 value,
uint256 _timestampRetrieved
)
{
uint256 _count = tellor.getNewValueCountbyRequestId(_requestId);
uint256 _time =
tellor.getTimestampbyRequestIDandIndex(_requestId, _count - 1);
uint256 _value = tellor.retrieveData(_requestId, _time);
if (_value > 0) return (true, _value, _time);
return (false, 0, _time);
}
// slither-disable-next-line calls-loop
function getIndexForDataBefore(uint256 _requestId, uint256 _timestamp)
public
view
returns (bool found, uint256 index)
{
uint256 _count = tellor.getNewValueCountbyRequestId(_requestId);
if (_count > 0) {
uint256 middle;
uint256 start = 0;
uint256 end = _count - 1;
uint256 _time;
//Checking Boundaries to short-circuit the algorithm
_time = tellor.getTimestampbyRequestIDandIndex(_requestId, start);
if (_time >= _timestamp) return (false, 0);
_time = tellor.getTimestampbyRequestIDandIndex(_requestId, end);
if (_time < _timestamp) return (true, end);
//Since the value is within our boundaries, do a binary search
while (true) {
middle = (end - start) / 2 + 1 + start;
_time = tellor.getTimestampbyRequestIDandIndex(
_requestId,
middle
);
if (_time < _timestamp) {
//get imeadiate next value
uint256 _nextTime =
tellor.getTimestampbyRequestIDandIndex(
_requestId,
middle + 1
);
if (_nextTime >= _timestamp) {
//_time is correct
return (true, middle);
} else {
//look from middle + 1(next value) to end
start = middle + 1;
}
} else {
uint256 _prevTime =
tellor.getTimestampbyRequestIDandIndex(
_requestId,
middle - 1
);
if (_prevTime < _timestamp) {
// _prevtime is correct
return (true, middle - 1);
} else {
//look from start to middle -1(prev value)
end = middle - 1;
}
}
//We couldn't found a value
//if(middle - 1 == start || middle == _count) return (false, 0);
}
}
return (false, 0);
}
/**
* @dev Allows the user to get the first value for the requestId before the specified timestamp
* @param _requestId is the requestId to look up the value for
* @param _timestamp before which to search for first verified value
* @return _ifRetrieve bool true if it is able to retreive a value, the value, and the value's timestamp
* @return _value the value retrieved
* @return _timestampRetrieved the value's timestamp
*/
function getDataBefore(uint256 _requestId, uint256 _timestamp)
public
view
returns (
bool _ifRetrieve,
uint256 _value,
uint256 _timestampRetrieved
)
{
(bool _found, uint256 _index) =
getIndexForDataBefore(_requestId, _timestamp);
if (!_found) return (false, 0, 0);
uint256 _time =
tellor.getTimestampbyRequestIDandIndex(_requestId, _index);
_value = tellor.retrieveData(_requestId, _time);
//If value is diputed it'll return zero
if (_value > 0) return (true, _value, _time);
return (false, 0, 0);
}
}
| 18,383
|
34
|
// Initializes the contract by setting a `name` and a `symbol` to the token collection. /
|
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
|
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
| 10,865
|
2
|
// Inbox represents minimum data availability to maintain incremental merkle tree. Supports a max of 2^64 - 1 messages. See merkle tree docs for more details on inbox data management.
|
bytes32[64] public inbox; // stores minimal set of complete subtree roots of the merkle tree to increment.
uint64 public count; // count of messages in the merkle tree
|
bytes32[64] public inbox; // stores minimal set of complete subtree roots of the merkle tree to increment.
uint64 public count; // count of messages in the merkle tree
| 22,719
|
187
|
// Raise event
|
contractTerminated(contracts[keccak256(Guid)]._Id, Guid, contracts[keccak256(Guid)]._State);
|
contractTerminated(contracts[keccak256(Guid)]._Id, Guid, contracts[keccak256(Guid)]._State);
| 42,171
|
73
|
// Returns an array of the Vault's providers /
|
function getProviders() external view override returns (address[] memory) {
return providers;
}
|
function getProviders() external view override returns (address[] memory) {
return providers;
}
| 37,784
|
11
|
// Mock contract to test Kyber Network proxy interface //Kerman Kohli - <kerman@8xprotocol.com> /
|
contract MockKyberNetwork is KyberNetworkInterface, Ownable {
uint256 public EXPECTED_RATE = 2*10**15;
function setExpectedRate(uint256 _rate) public onlyOwner {
EXPECTED_RATE = _rate;
}
/**
* KYBER NETWORK INTERFACE FUNCTIONS
*/
function getExpectedRate(
ERC20 src,
ERC20 dest,
uint256 srcQty
)
public
view
returns (uint256 expectedRate, uint256 slippageRate)
{
// 0.002 ETH/USD is the exchange rate we want. Assuming $500 USD/ETH.
return (EXPECTED_RATE, EXPECTED_RATE);
}
function maxGasPrice()
public
view
returns(uint256)
{
return 0;
}
function getUserCapInWei(address user)
public
view
returns(uint256)
{
return 0;
}
function getUserCapInTokenWei(address user, ERC20 token)
public
view
returns(uint256)
{
return 0;
}
function enabled()
public
view
returns(bool)
{
return true;
}
function info(bytes32 id)
public
view
returns(uint256)
{
return 0;
}
function swapEtherToToken(
ERC20 token,
uint256 minConversionRate
)
public
payable
{
token.transfer(msg.sender, minConversionRate * msg.value);
}
function swapTokenToTokenWithChange (
ERC20 srcToken,
uint256 srcQty,
ERC20 destToken,
address destAddress,
address user,
uint256 maxDestQty,
uint256 minRate
)
public
{
require(srcToken.balanceOf(user) >= srcQty);
srcToken.transferFrom(user, address(this), srcQty);
destToken.transfer(destAddress, maxDestQty);
}
}
|
contract MockKyberNetwork is KyberNetworkInterface, Ownable {
uint256 public EXPECTED_RATE = 2*10**15;
function setExpectedRate(uint256 _rate) public onlyOwner {
EXPECTED_RATE = _rate;
}
/**
* KYBER NETWORK INTERFACE FUNCTIONS
*/
function getExpectedRate(
ERC20 src,
ERC20 dest,
uint256 srcQty
)
public
view
returns (uint256 expectedRate, uint256 slippageRate)
{
// 0.002 ETH/USD is the exchange rate we want. Assuming $500 USD/ETH.
return (EXPECTED_RATE, EXPECTED_RATE);
}
function maxGasPrice()
public
view
returns(uint256)
{
return 0;
}
function getUserCapInWei(address user)
public
view
returns(uint256)
{
return 0;
}
function getUserCapInTokenWei(address user, ERC20 token)
public
view
returns(uint256)
{
return 0;
}
function enabled()
public
view
returns(bool)
{
return true;
}
function info(bytes32 id)
public
view
returns(uint256)
{
return 0;
}
function swapEtherToToken(
ERC20 token,
uint256 minConversionRate
)
public
payable
{
token.transfer(msg.sender, minConversionRate * msg.value);
}
function swapTokenToTokenWithChange (
ERC20 srcToken,
uint256 srcQty,
ERC20 destToken,
address destAddress,
address user,
uint256 maxDestQty,
uint256 minRate
)
public
{
require(srcToken.balanceOf(user) >= srcQty);
srcToken.transferFrom(user, address(this), srcQty);
destToken.transfer(destAddress, maxDestQty);
}
}
| 52,789
|
58
|
// Upgrade the implementation of the proxy.
|
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
|
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
| 25,693
|
10
|
// What's my balance?
|
function balance() constant public returns (uint256) {
return balances[msg.sender];
}
|
function balance() constant public returns (uint256) {
return balances[msg.sender];
}
| 17,724
|
258
|
// Cache the new total boosted against the Vault's collateral.
|
uint256 newTotalBoostedAgainstCollateral;
|
uint256 newTotalBoostedAgainstCollateral;
| 80,717
|
166
|
// Private function to set the allowance for `spender` to transfer upto `value` tokens on behalf of `owner`. owner address The account that has granted the allowance. spender address The account to grant the allowance. value uint256 The size of the allowance to grant. /
|
function _approve(address owner, address spender, uint256 value) private {
require(owner != address(0), "ERC20: approve for the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
|
function _approve(address owner, address spender, uint256 value) private {
require(owner != address(0), "ERC20: approve for the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
| 3,601
|
27
|
// Withdraw all ERC20 compatible tokens token ERC20 The address of the token contract /
|
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
TokenWithdraw(token, amount, sendTo);
}
|
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
TokenWithdraw(token, amount, sendTo);
}
| 51,142
|
2
|
// _context BrightID context used for verifying users _verifier BrightID verifier address that signs BrightID verifications /
|
constructor(bytes32 _context, address _verifier) public {
// ecrecover returns zero on error
require(_verifier != address(0), ERROR_INVALID_VERIFIER);
context = _context;
verifier = _verifier;
}
|
constructor(bytes32 _context, address _verifier) public {
// ecrecover returns zero on error
require(_verifier != address(0), ERROR_INVALID_VERIFIER);
context = _context;
verifier = _verifier;
}
| 53,195
|
2
|
// Compresses and encodes an array of pixels into an canvas of uint256s that can be rendered.For example, a 3x3 image with a plus sign would be: [0, 1, 0, 1, 1, 1, 0, 1, 0]Numbers are indexes into a palette, so say each pixel was a different color: [0, 1, 0, 2, 3, 4, 0, 5, 0]Supplied palette would then match the indexes.For example, each of these hex grey colors would correspond to the respective number 0x555555444444333333222222111111So 5 would be 0x555555, 4 0x444444, etc. pixelCompression indicates the max number of pixels in a block. So pixelCompression 4 means you can
|
function encodeColorArray(
|
function encodeColorArray(
| 5,919
|
6
|
// token addresses
|
address internal constant WETH =
address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address internal constant USDC =
address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address internal constant GRO =
address(0x3Ec8798B81485A254928B70CDA1cf0A2BB0B74D7);
address internal constant CRV_3POOL =
address(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
ERC20 internal constant CRV_3POOL_TOKEN =
ERC20(address(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490));
|
address internal constant WETH =
address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address internal constant USDC =
address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address internal constant GRO =
address(0x3Ec8798B81485A254928B70CDA1cf0A2BB0B74D7);
address internal constant CRV_3POOL =
address(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
ERC20 internal constant CRV_3POOL_TOKEN =
ERC20(address(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490));
| 48,542
|
13
|
// Public Function: Open a stake.uint256 stakedPrinciple Number of Stars to stakeuint256 stakedDays length of days in the stake
|
function startStake(uint256 stakedPrinciple, uint256 stakedDays)
external
|
function startStake(uint256 stakedPrinciple, uint256 stakedDays)
external
| 5,752
|
119
|
// calc vesting number/
|
function unlocked_investors_vesting(address user) public view returns(uint256) {
return _investors.calcvesting(user);
}
|
function unlocked_investors_vesting(address user) public view returns(uint256) {
return _investors.calcvesting(user);
}
| 44,118
|
78
|
// ========== STATE VARIABLES ========== // ========== CONSTRUCTOR ========== /
|
) public OwnedV2(_owner) {
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
}
|
) public OwnedV2(_owner) {
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
}
| 6,011
|
14
|
// start with base rate
|
rate = tokenData[token].baseBuyRate;
|
rate = tokenData[token].baseBuyRate;
| 34,277
|
115
|
// USER GAS FUNCTIONS / Pay out the holder can only be called after lastUpdate[user] > 0, and NFT token IDs have been proved (call startEarningRent)
|
function claimReward() external whenNotPaused {
require(totalSupply() < MAX_SUPPLY, "RENT collection is over"); // RENT earned will not be claimable after max RENT has been minted
require(lastUpdate[msg.sender] != 0, "If you have a LAND token, call startEarningRent");
uint256 currentReward = getPendingReward(msg.sender);
pay(msg.sender, currentReward);
lastUpdate[msg.sender] = block.timestamp;
}
|
function claimReward() external whenNotPaused {
require(totalSupply() < MAX_SUPPLY, "RENT collection is over"); // RENT earned will not be claimable after max RENT has been minted
require(lastUpdate[msg.sender] != 0, "If you have a LAND token, call startEarningRent");
uint256 currentReward = getPendingReward(msg.sender);
pay(msg.sender, currentReward);
lastUpdate[msg.sender] = block.timestamp;
}
| 19,359
|
53
|
// Max wallet holding (% at launch)
|
uint256 public _maxWalletToken = _tTotal.mul(2).div(100);
uint256 private _previousMaxWalletToken = _maxWalletToken;
|
uint256 public _maxWalletToken = _tTotal.mul(2).div(100);
uint256 private _previousMaxWalletToken = _maxWalletToken;
| 27,519
|
59
|
// Referral amount
|
uint256 private _referralAmount = 0;
|
uint256 private _referralAmount = 0;
| 14,608
|
8
|
// Write 32-byte encrypted chunk
|
mstore (add (result, add (i, 32)), chunk)
|
mstore (add (result, add (i, 32)), chunk)
| 13,711
|
113
|
// module:user-config delay, in number of block, between the proposal is created and the vote starts. This can be increassed toleave time for users to buy voting power, of delegate it, before the voting of a proposal starts. /
|
function votingDelay() public view virtual returns (uint256);
|
function votingDelay() public view virtual returns (uint256);
| 40,570
|
6
|
// Make a payment in ERC20 to the recipient _recipient The address of the recipient of the payment _paymentERC20 The address of the ERC20 to take _price The amount of the ERC20 to take /
|
function makeStaticERC20Payment(address _recipient, address _paymentERC20, uint256 _price) external;
|
function makeStaticERC20Payment(address _recipient, address _paymentERC20, uint256 _price) external;
| 19,502
|
32
|
// Call function IngestTelemetry of RefrigeratedTransportation
|
RefrigeratedTransportation.IngestTelemetry(humidity, temperature, timestamp);
|
RefrigeratedTransportation.IngestTelemetry(humidity, temperature, timestamp);
| 47,880
|
44
|
// uint borrowAmount = ERC20(borrowToken).balanceOf(address(this));
|
if (hedgeType == 1) {
|
if (hedgeType == 1) {
| 21,104
|
340
|
// If collateral factor != 0, fail if price == 0
|
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
|
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
| 7,531
|
51
|
// allows non-oracles to request a new round /
|
function requestNewRound()
external
returns (uint80)
|
function requestNewRound()
external
returns (uint80)
| 5,080
|
8
|
// Toggle a Chief. Enable if disable & vice versa _chiefAddress Chief Address./
|
function toggleChief(address _chiefAddress) external {
require(msg.sender == IndexInterface(instaIndex).master(), "toggleChief: not-master");
chief[_chiefAddress] = !chief[_chiefAddress];
emit LogController(_chiefAddress, chief[_chiefAddress]);
}
|
function toggleChief(address _chiefAddress) external {
require(msg.sender == IndexInterface(instaIndex).master(), "toggleChief: not-master");
chief[_chiefAddress] = !chief[_chiefAddress];
emit LogController(_chiefAddress, chief[_chiefAddress]);
}
| 81,250
|
169
|
// We optimize ERC721 take orders by not increasing the nonce, because every ERC721 is unique - trying to replay the transaction will always fail, since once taken - the target order doesn't exist anymore and thus cannot be filled ever again.
|
if (takerCurrencyType == DubiexLib.CurrencyType.ERC721) {
_verifyBoostWithoutNonce(
order.taker,
hashBoostedTakeOrder(order, msg.sender),
order.boosterPayload,
signature
);
} else {
|
if (takerCurrencyType == DubiexLib.CurrencyType.ERC721) {
_verifyBoostWithoutNonce(
order.taker,
hashBoostedTakeOrder(order, msg.sender),
order.boosterPayload,
signature
);
} else {
| 13,920
|
25
|
// Create token and store all tokens in token address
|
function getTokenAddress(address tokenAddress) external onlyOwner returns (bool){
require(ownerCanOperate == true, "Token address is already set and cannot change.");
ownerCanOperate = false; // lock down to make sure the contract owner canNOT change token address to token holder's address.
_tokenAddress = tokenAddress;
return true;
}
|
function getTokenAddress(address tokenAddress) external onlyOwner returns (bool){
require(ownerCanOperate == true, "Token address is already set and cannot change.");
ownerCanOperate = false; // lock down to make sure the contract owner canNOT change token address to token holder's address.
_tokenAddress = tokenAddress;
return true;
}
| 10,370
|
0
|
// ! "name": "one",! "input": [
|
//! {
//! "entry": "main",
//! "calldata": [
//! "84", "21"
//! ]
//! }
|
//! {
//! "entry": "main",
//! "calldata": [
//! "84", "21"
//! ]
//! }
| 7,922
|
26
|
// Don't care about rewards and stats (emergency only, in case if unexpected error occurs) Since this breaks contract stats only owner (governance contract can call) can call this function
|
function emergencyWithdraw(address payable _user, uint256 _amount) public onlyOwner returns (uint256) {
_users[msg.sender].investment = _users[_user].investment.sub(_amount);
uint256 fee = _amount.mul(UNSTAKE_FEE).div(100);
return safeSendValue(_user, _amount.sub(fee));
}
|
function emergencyWithdraw(address payable _user, uint256 _amount) public onlyOwner returns (uint256) {
_users[msg.sender].investment = _users[_user].investment.sub(_amount);
uint256 fee = _amount.mul(UNSTAKE_FEE).div(100);
return safeSendValue(_user, _amount.sub(fee));
}
| 41,235
|
7
|
// Triggered whenever approve is called.
|
event Approval(
address indexed owner,
address indexed spender,
uint256 amount);
|
event Approval(
address indexed owner,
address indexed spender,
uint256 amount);
| 23,616
|
237
|
// Sets the performance fee for the vault newPerformanceFee is the performance fee (6 decimals). ex: 20106 = 20% /
|
function setPerformanceFee(uint256 newPerformanceFee) external onlyOwner {
require(
newPerformanceFee < 100 * Vault.FEE_MULTIPLIER,
"Invalid performance fee"
);
emit PerformanceFeeSet(performanceFee, newPerformanceFee);
performanceFee = newPerformanceFee;
}
|
function setPerformanceFee(uint256 newPerformanceFee) external onlyOwner {
require(
newPerformanceFee < 100 * Vault.FEE_MULTIPLIER,
"Invalid performance fee"
);
emit PerformanceFeeSet(performanceFee, newPerformanceFee);
performanceFee = newPerformanceFee;
}
| 17,348
|
436
|
// Same as `_downscaleUp`, but for an entire array. This function does not return anything, but insteadmutates the `amounts` array. /
|
function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = Math.divUp(amounts[i], scalingFactors[i]);
}
}
|
function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view {
for (uint256 i = 0; i < _getTotalTokens(); ++i) {
amounts[i] = Math.divUp(amounts[i], scalingFactors[i]);
}
}
| 1,749
|
144
|
// Only allows approved admins to call the specified function /
|
modifier adminRequired() {
require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin");
_;
}
|
modifier adminRequired() {
require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin");
_;
}
| 25,055
|
16
|
// Creates `amount` tokens and assigns them to `account`, increasingthe total supply without vesting.
|
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
* - Caller must have minter role.
* - `account` cannot be the zero address.
*/
function mintWithoutVesting(address account, uint256 amount) external override returns (bool) {
require(hasRole(MINTER_ROLE, msg.sender), 'XFIToken: sender is not minter');
_mintWithoutVesting(account, amount);
return true;
}
|
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
* - Caller must have minter role.
* - `account` cannot be the zero address.
*/
function mintWithoutVesting(address account, uint256 amount) external override returns (bool) {
require(hasRole(MINTER_ROLE, msg.sender), 'XFIToken: sender is not minter');
_mintWithoutVesting(account, amount);
return true;
}
| 47,233
|
31
|
// Enables or disables trading on Uniswap
|
function setTradingActive(bool _tradingActive) external onlyOwner {
tradingActive = _tradingActive;
tradingBlock = block.number;
emit TradingActiveChanged(_tradingActive);
}
|
function setTradingActive(bool _tradingActive) external onlyOwner {
tradingActive = _tradingActive;
tradingBlock = block.number;
emit TradingActiveChanged(_tradingActive);
}
| 25,871
|
31
|
// Tile successfully attacked!
|
if (_useBattleValue) {
if (_autoFortify) {
|
if (_useBattleValue) {
if (_autoFortify) {
| 59,391
|
19
|
// how many token units a buyer gets per ether
|
uint256 rate = 500;
|
uint256 rate = 500;
| 16,708
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.