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
91
// Approve the passed address to spend the specified amount of tokens on behalf of msg.senderand then call `onApprovalReceived` on spender.Beware that changing an allowance with this method brings the risk that someone may use both the oldand the new allowance by unfortunate transaction ordering. One possible solution to mitigate thisrace condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: spender address The address which will spend the funds value uint256 The amount of tokens to be spent /
function approveAndCall(address spender, uint256 value) external returns (bool);
function approveAndCall(address spender, uint256 value) external returns (bool);
21,719
174
// MINT
function mintKITTEN(uint256 _mintAmount) public payable notPaused saleStarted minimumMintAmount(_mintAmount)
function mintKITTEN(uint256 _mintAmount) public payable notPaused saleStarted minimumMintAmount(_mintAmount)
8,483
3
// Return a `wei` value in units of Gwei and serialize as a (LE) `bytes8`.
function serializeAmount(uint amount) private pure returns (bytes memory) { uint depositAmount = amount / WEI_PER_GWEI; bytes memory encodedAmount = new bytes(8); for (uint i = 0; i < 8; i++) { encodedAmount[i] = byte(uint8(depositAmount / (2**(8*i)))); } return encodedAmount; }
function serializeAmount(uint amount) private pure returns (bytes memory) { uint depositAmount = amount / WEI_PER_GWEI; bytes memory encodedAmount = new bytes(8); for (uint i = 0; i < 8; i++) { encodedAmount[i] = byte(uint8(depositAmount / (2**(8*i)))); } return encodedAmount; }
31,407
54
// If Chainlink is live but deviated >50% from it's previous price and Tellor is still untrusted, switch to bothOraclesUntrusted and return last good price
if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; }
if (_chainlinkPriceChangeAboveMax(chainlinkResponse, prevChainlinkResponse)) { _changeStatus(Status.bothOraclesUntrusted); return lastGoodPrice; }
18,719
92
// val
uint8(state.stack.pop()) );
uint8(state.stack.pop()) );
40,004
20
// Total length of the auction
uint48 public totalAuctionLength = 2 days; // [seconds]
uint48 public totalAuctionLength = 2 days; // [seconds]
54,229
176
// sends eth from contract balance to specified address sendTo address to send amount amount - amount to send (should be less than current balance) /
function withdraw( address payable sendTo, uint256 amount ) external onlyOwner
function withdraw( address payable sendTo, uint256 amount ) external onlyOwner
31,713
188
// Record referral. /
function recordReferral(address user, address referrer) external;
function recordReferral(address user, address referrer) external;
10,078
12
// This creates an array with all balances // This generates a public event on the blockchain that will notify clients // notify about transfer to client// notify about approval to client// notify about basisPointsRate to client/ Called when new token are issued
event Issue( uint amount );
event Issue( uint amount );
29,375
228
// start with the mythical CobeFriend 0 - so we don't have generation-0 parent issues
_createCobeFriend(0, 0, 0, uint256(-1), address(0));
_createCobeFriend(0, 0, 0, uint256(-1), address(0));
26,493
83
// The account bundles of locked tokens grouped by release date
mapping (uint8 => AccountsBundle) public bundles;
mapping (uint8 => AccountsBundle) public bundles;
48,337
191
// Change guardian address/Can only be changed by governance
function setGuardian(address _guardian) external whenNotPaused { _onlyGovernance(); guardian = _guardian; }
function setGuardian(address _guardian) external whenNotPaused { _onlyGovernance(); guardian = _guardian; }
41,564
209
// getBid get bid for specific bidder and _auctionId _bidder the bidder _auctionId auction idreturn uint /
function getBid(address _bidder, uint256 _auctionId) public view returns(uint256) { return auctions[_auctionId].bids[_bidder]; }
function getBid(address _bidder, uint256 _auctionId) public view returns(uint256) { return auctions[_auctionId].bids[_bidder]; }
13,126
289
// ========== VIEWS ========== // Retrieve the length of the debt ledger array /
function debtLedgerLength() external view returns (uint)
function debtLedgerLength() external view returns (uint)
22,778
1
// Team mint max 100
uint256 private PRICE_GOLDENPASS = 0.079 ether; uint256 private PRICE_MERCENARIES = 0.049 ether; address public teamAddress; bytes32 private clutchMerkleRoot; bytes32 private mercenariesMerkleRoot; bytes32 private goldenPassMerkleRoot; mapping(address => uint256) public amountperWallet;
uint256 private PRICE_GOLDENPASS = 0.079 ether; uint256 private PRICE_MERCENARIES = 0.049 ether; address public teamAddress; bytes32 private clutchMerkleRoot; bytes32 private mercenariesMerkleRoot; bytes32 private goldenPassMerkleRoot; mapping(address => uint256) public amountperWallet;
36,891
99
// Returns the reward token balance left in the pool /
function rewardBalance() public view returns (uint256) { return rewardToken.balanceOf(address(this)); }
function rewardBalance() public view returns (uint256) { return rewardToken.balanceOf(address(this)); }
2,324
7
// Send value to address/
function sendValueTo(address to_, uint256 value) internal { address payable to = payable(to_); (bool success, ) = to.call{value: value}(""); require(success, "Transfer failed."); }
function sendValueTo(address to_, uint256 value) internal { address payable to = payable(to_); (bool success, ) = to.call{value: value}(""); require(success, "Transfer failed."); }
7,954
4
// Add tokens into the billing contract _amountAmount of tokens to add /
function add(uint256 _amount) external;
function add(uint256 _amount) external;
35,052
1
// event Print(string message);
function getRs1Rs2(MemoryInteractor mi, uint32 insn) internal returns(uint64 rs1, uint64 rs2)
function getRs1Rs2(MemoryInteractor mi, uint32 insn) internal returns(uint64 rs1, uint64 rs2)
11,997
2
// Consturctor of teaching_professor address of the professor._name name of the teaching./
constructor(address _professor, bytes _name) public { professor = _professor; name = _name; }
constructor(address _professor, bytes _name) public { professor = _professor; name = _name; }
6,575
45
// Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see{TransparentUpgradeableProxy}./ Initializes the upgradeable proxy with an initial implementation specified by `_logic`. If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encodedfunction call, and allows initializating the storage of the proxy like a Solidity constructor. /
constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); }
constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); }
21,903
10
// Mapping to check keepers
mapping(address => bool) public keeperList;
mapping(address => bool) public keeperList;
72,350
13
// ERC165 interface ID of ERC721Metadata
bytes4 internal constant ERC721_METADATA_INTERFACE_ID = 0x5b5e139f;
bytes4 internal constant ERC721_METADATA_INTERFACE_ID = 0x5b5e139f;
12,079
4
// owner set etherwow contract address new etherwow address /
function ownerSetEtherwowAddress(address newEtherwowAddress) public onlyOwner
function ownerSetEtherwowAddress(address newEtherwowAddress) public onlyOwner
64,708
125
// Community Multisig
rewardDistribution[0xF49440C1F012d041802b25A73e5B0B9166a75c02] = true; for(uint256 i = 0; i < _rewardDistributions.length; i++) { rewardDistribution[_rewardDistributions[i]] = true; }
rewardDistribution[0xF49440C1F012d041802b25A73e5B0B9166a75c02] = true; for(uint256 i = 0; i < _rewardDistributions.length; i++) { rewardDistribution[_rewardDistributions[i]] = true; }
24,290
10
// Set the new index based on how much accrued
return savingsIndex.add(totalInterestAccumulated);
return savingsIndex.add(totalInterestAccumulated);
18,025
211
// Rescue tokens
function rescueTokens( address token, address to, uint256 amount ) external onlyGov returns (bool)
function rescueTokens( address token, address to, uint256 amount ) external onlyGov returns (bool)
87,500
62
// Allows the pendingGDPOracle_ address to finalize the transfer. /
function claimOracle() onlyPendingGDPOracle public { emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_); GDPOracle_ = pendingGDPOracle_; pendingGDPOracle_ = address(0); }
function claimOracle() onlyPendingGDPOracle public { emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_); GDPOracle_ = pendingGDPOracle_; pendingGDPOracle_ = address(0); }
24,441
160
// Allow option token holders to use them to exercise the amount of unitsof the locked tokens for the equivalent amount of the exercisable assets.It presumes the caller has already called IERC20.approve() exercisable assetto move caller funds. On American options, this function can only called anytime before expiration.For European options, this function can only be called during the exerciseWindow.Meaning, after expiration and before the end of exercise window.amountOfOptions The amount option tokens to be exercised /
function exercise(uint256 amountOfOptions) external;
function exercise(uint256 amountOfOptions) external;
36,076
125
// calculate actual rate
int imbalanceQty; int extraBps; int8 rateUpdate; uint rate; if (buy) {
int imbalanceQty; int extraBps; int8 rateUpdate; uint rate; if (buy) {
4,708
294
// halting //halt the app. this action is irreversible./ (the only option at this point is have a proposal that will get to approval, then activated.)/ should be called by an app-owner when the app has been compromised.// Note the constraint that all apps but Registry & Stake must be halted first!
function switchOff() external onlyOwner { uint32 totalAppsCount = gluon.totalAppsCount(); for (uint32 appId = 2; appId < totalAppsCount; appId++) { AppState appState = AppState(gluon.current(appId)); require(!appState.isOn(), "One of the apps is still ON"); } switchOff_(); }
function switchOff() external onlyOwner { uint32 totalAppsCount = gluon.totalAppsCount(); for (uint32 appId = 2; appId < totalAppsCount; appId++) { AppState appState = AppState(gluon.current(appId)); require(!appState.isOn(), "One of the apps is still ON"); } switchOff_(); }
58,943
167
// Simple constructor that stores the parent address /
constructor(IERC20 _platformToken) public { parentStakingContract = msg.sender; platformToken = _platformToken; MassetHelpers.safeInfiniteApprove(address(_platformToken), msg.sender); }
constructor(IERC20 _platformToken) public { parentStakingContract = msg.sender; platformToken = _platformToken; MassetHelpers.safeInfiniteApprove(address(_platformToken), msg.sender); }
46,683
1
// Emitted once a stake is scheduled for withdrawal
event StakeUnlocked( address indexed relayManager, address indexed owner, uint256 withdrawBlock );
event StakeUnlocked( address indexed relayManager, address indexed owner, uint256 withdrawBlock );
28,729
41
// return true if presale event has ended
function hasEnded() public constant returns (bool) { return now > endTime; }
function hasEnded() public constant returns (bool) { return now > endTime; }
44,516
88
// Removes a NFT from owner. Use and override this function with caution. Wrong usage can have serious consequences. _from Address from wich we want to remove the NFT. _tokenId Which NFT we want to remove. /
function _removeNFToken( address _from, uint256 _tokenId ) internal
function _removeNFToken( address _from, uint256 _tokenId ) internal
3,793
4
// ecrecover returns zero on error
require(signature_address != 0x0); return signature_address;
require(signature_address != 0x0); return signature_address;
32,408
1
// Length of array.
function length(Data storage self) internal view returns (uint256) { return self._raw[0] >> 160; }
function length(Data storage self) internal view returns (uint256) { return self._raw[0] >> 160; }
44,478
47
// Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.Calling this in the constructor of a contract will prevent that contract from being initialized or reinitializedto any version. It is recommended to use this to lock implementation contracts that are designed to be calledthrough proxies.
* Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } }
* Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } }
13,180
39
// Grantable the pre-grant is token to addr, and can be viewed in contractwhen grant, give token to addr in the real authorization /
contract Grantable is BasicToken { using SafeMath for uint256; mapping(address => uint256) grants; event PreGrant(address indexed from, address indexed to, uint256 value); event Grant(address indexed from, address indexed to, uint256 value); function preGrant(address _to, uint256 _value) onlyOwner whenNotPaused public returns (bool success) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender grants[_to] = grants[_to].add(_value); emit PreGrant(msg.sender, _to, _value); return true; } function grant(address _to, uint256 _value) onlyOwner whenNotPaused public returns (bool success) { require(_to != address(0)); require(_value <= grants[_to]); require(_value > 0); grants[_to] = grants[_to].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); emit Grant(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return true; } function grantOf(address _owner) public view returns (uint256) { return grants[_owner]; } }
contract Grantable is BasicToken { using SafeMath for uint256; mapping(address => uint256) grants; event PreGrant(address indexed from, address indexed to, uint256 value); event Grant(address indexed from, address indexed to, uint256 value); function preGrant(address _to, uint256 _value) onlyOwner whenNotPaused public returns (bool success) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender grants[_to] = grants[_to].add(_value); emit PreGrant(msg.sender, _to, _value); return true; } function grant(address _to, uint256 _value) onlyOwner whenNotPaused public returns (bool success) { require(_to != address(0)); require(_value <= grants[_to]); require(_value > 0); grants[_to] = grants[_to].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); emit Grant(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return true; } function grantOf(address _owner) public view returns (uint256) { return grants[_owner]; } }
39,762
21
// Gets the exchange rate. I.e how much collateral to buy 1e18 asset./ This function is supposed to be invoked if needed because Oracle queries can be expensive./ return updated True if `exchangeRate` was updated./ return rate The new exchange rate.
function updateExchangeRate() public returns (bool updated, uint256 rate) { (updated, rate) = oracle.get(oracleData); if (updated) { exchangeRate = rate; emit LogExchangeRate(rate); } else { // Return the old rate if fetching wasn't successful rate = exchangeRate; } }
function updateExchangeRate() public returns (bool updated, uint256 rate) { (updated, rate) = oracle.get(oracleData); if (updated) { exchangeRate = rate; emit LogExchangeRate(rate); } else { // Return the old rate if fetching wasn't successful rate = exchangeRate; } }
52,271
132
// The quantity of tokens minted must be more than zero. /
error MintZeroQuantity();
error MintZeroQuantity();
75,157
1,190
// Returns current config or pending config if pending liveness has expired.return ConfigSettings config settings that calling financial contract should view as "live". /
function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory)
function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory)
10,361
15
// Administrator violated consensus
event Violated(string action, address sender);
event Violated(string action, address sender);
46,742
39
// Transition batch status to updated status
ICarbonOffsetBatches(batchNFT) .setStatusForDetokenizationOrRetirement(tokenId, status); unchecked { ++i; }
ICarbonOffsetBatches(batchNFT) .setStatusForDetokenizationOrRetirement(tokenId, status); unchecked { ++i; }
31,217
51
// VIEW FUNCTIONS
function mintingAllowedAfter() external view returns (uint256) { return BETHToken.mintingAllowedAfter(); }
function mintingAllowedAfter() external view returns (uint256) { return BETHToken.mintingAllowedAfter(); }
39,933
11
// / minted through elite whitelist
uint256 public numEliteWhitelists = 0;
uint256 public numEliteWhitelists = 0;
1,620
16
// return amount of ZMN token derive from price band and current exchange rate _weiAmount purchase amount of ETH /
function getTokenAmount(uint256 _weiAmount) public view returns (uint256){ // US cost for 10,000 tokens uint256 cost = 550; if(_weiAmount < 10 ether){ cost = 550; }else if(_weiAmount < 25 ether){ cost = 545; }else if(_weiAmount < 50 ether){ cost = 540; }else if(_weiAmount < 250 ether){ cost = 530; }else if(_weiAmount < 500 ether){ cost = 520; }else if(_weiAmount < 1000 ether){ cost = 510; }else{ cost = 500; } return _weiAmount.mul(rate).mul(10000).div(cost); }
function getTokenAmount(uint256 _weiAmount) public view returns (uint256){ // US cost for 10,000 tokens uint256 cost = 550; if(_weiAmount < 10 ether){ cost = 550; }else if(_weiAmount < 25 ether){ cost = 545; }else if(_weiAmount < 50 ether){ cost = 540; }else if(_weiAmount < 250 ether){ cost = 530; }else if(_weiAmount < 500 ether){ cost = 520; }else if(_weiAmount < 1000 ether){ cost = 510; }else{ cost = 500; } return _weiAmount.mul(rate).mul(10000).div(cost); }
41,957
207
// For holders to destroy tokens in return for ether during a redeeming round
function redeem(uint _amount) public canEnter isHolder(msg.sender) returns (bool)
function redeem(uint _amount) public canEnter isHolder(msg.sender) returns (bool)
45,749
23
// replace
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function"); removeSelector(oldFacetAddress, selector); addSelector(_newFacetAddress, selector);
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function"); removeSelector(oldFacetAddress, selector); addSelector(_newFacetAddress, selector);
38,974
300
// Retrieve and store the underlying price from the oracle This method can be called by anyone after expiration but cannot be calledmore than once. In practice it should be called as soon as possible after theexpiration time. /
function settle() external nonReentrant { require(isExpired(), "Cannot be called before expiry"); require(!isSettled, "Already settled"); // fetch expiry price from oracle isSettled = true; expiryPrice = oracle.getPrice(); require(expiryPrice > 0, "Price from oracle must be > 0"); // update cached payoff and pool value lastPayoff = getCurrentPayoff(); poolValue = baseToken.uniBalanceOf(address(this)).sub(lastPayoff); emit Settle(expiryPrice); }
function settle() external nonReentrant { require(isExpired(), "Cannot be called before expiry"); require(!isSettled, "Already settled"); // fetch expiry price from oracle isSettled = true; expiryPrice = oracle.getPrice(); require(expiryPrice > 0, "Price from oracle must be > 0"); // update cached payoff and pool value lastPayoff = getCurrentPayoff(); poolValue = baseToken.uniBalanceOf(address(this)).sub(lastPayoff); emit Settle(expiryPrice); }
29,898
207
// Returns the message sender (defaults to `msg.sender`). If you are writing GSN compatible contracts, you need to override this function. /
function _msgSenderERC721A() internal view virtual returns (address) { return msg.sender; }
function _msgSenderERC721A() internal view virtual returns (address) { return msg.sender; }
1,607
221
// ERC1400ERC20 OPTIONAL FUNCTIONS //[NOT MANDATORY FOR ERC1400ERC20 STANDARD] Get whitelisted status for a tokenHolder. tokenHolder Address whom to check the whitelisted status for.return bool 'true' if tokenHolder is whitelisted, 'false' if not. /
function whitelisted(address tokenHolder) external view returns (bool) { return _whitelisted[tokenHolder]; }
function whitelisted(address tokenHolder) external view returns (bool) { return _whitelisted[tokenHolder]; }
48,226
0
// The addresses of the current yearn vault
IYearnVault public vault;
IYearnVault public vault;
74,464
4
// Atomic ERC20 Swap nonce uint256 Unique and should be sequential expiry uint256 Expiry in seconds since 1 January 1970 signerWallet address Wallet of the signer signerToken address ERC20 token transferred from the signer signerAmount uint256 Amount transferred from the signer senderToken address ERC20 token transferred from the sender senderAmount uint256 Amount transferred from the sender v uint8 "v" value of the ECDSA signature r bytes32 "r" value of the ECDSA signature s bytes32 "s" value of the ECDSA signature /
function swap( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r,
function swap( uint256 nonce, uint256 expiry, address signerWallet, address signerToken, uint256 signerAmount, address senderToken, uint256 senderAmount, uint8 v, bytes32 r,
45,061
9
// the current maximum number of observations that are being stored
uint16 observationCardinality;
uint16 observationCardinality;
4,239
9
// A distinct URI (RFC 3986) for a given NFT. _tokenId Id for which we want uri.return URI of _tokenId. /
function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory)
function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory)
3,679
0
// @inheritdoc ISwapHatV3Factory
address public override owner;
address public override owner;
25,047
24
// Increment the total amount of tokens staked across all stakers
totalStaked++;
totalStaked++;
26,774
35
// Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but also transferring `value` wei to `target`. Requirements: - the calling contract must have an ETH balance of at least `value`. - the called Solidity function must be `payable`. _Available since v3.1._/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); }
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); }
999
173
// Tellor Oracle System Library Contains the functions' logic for the Tellor contract where miners can submit the proof of workalong with the value and smart contracts can requestData and tip miners. /
library TellorLibrary { using SafeMath for uint256; bytes32 public constant requestCount = 0x05de9147d05477c0a5dc675aeea733157f5092f82add148cf39d579cafe3dc98; //keccak256("requestCount") bytes32 public constant totalTip = 0x2a9e355a92978430eca9c1aa3a9ba590094bac282594bccf82de16b83046e2c3; //keccak256("totalTip") bytes32 public constant _tBlock = 0x969ea04b74d02bb4d9e6e8e57236e1b9ca31627139ae9f0e465249932e824502; //keccak256("_tBlock") bytes32 public constant timeOfLastNewValue = 0x97e6eb29f6a85471f7cc9b57f9e4c3deaf398cfc9798673160d7798baf0b13a4; //keccak256("timeOfLastNewValue") bytes32 public constant difficulty = 0xb12aff7664b16cb99339be399b863feecd64d14817be7e1f042f97e3f358e64e; //keccak256("difficulty") bytes32 public constant timeTarget = 0xad16221efc80aaf1b7e69bd3ecb61ba5ffa539adf129c3b4ffff769c9b5bbc33; //keccak256("timeTarget") bytes32 public constant runningTips = 0xdb21f0c4accc4f2f5f1045353763a9ffe7091ceaf0fcceb5831858d96cf84631; //keccak256("runningTips") bytes32 public constant currentReward = 0x9b6853911475b07474368644a0d922ee13bc76a15cd3e97d3e334326424a47d4; //keccak256("currentReward") bytes32 public constant total_supply = 0xb1557182e4359a1f0c6301278e8f5b35a776ab58d39892581e357578fb287836; //keccak256("total_supply") bytes32 public constant devShare = 0x8fe9ded8d7c08f720cf0340699024f83522ea66b2bbfb8f557851cb9ee63b54c; //keccak256("devShare") bytes32 public constant _owner = 0x9dbc393ddc18fd27b1d9b1b129059925688d2f2d5818a5ec3ebb750b7c286ea6; //keccak256("_owner") bytes32 public constant requestQPosition = 0x1e344bd070f05f1c5b3f0b1266f4f20d837a0a8190a3a2da8b0375eac2ba86ea; //keccak256("requestQPosition") bytes32 public constant currentTotalTips = 0xd26d9834adf5a73309c4974bf654850bb699df8505e70d4cfde365c417b19dfc; //keccak256("currentTotalTips") bytes32 public constant slotProgress =0x6c505cb2db6644f57b42d87bd9407b0f66788b07d0617a2bc1356a0e69e66f9a; //keccak256("slotProgress") bytes32 public constant pending_owner = 0x44b2657a0f8a90ed8e62f4c4cceca06eacaa9b4b25751ae1ebca9280a70abd68; //keccak256("pending_owner") bytes32 public constant currentRequestId = 0x7584d7d8701714da9c117f5bf30af73b0b88aca5338a84a21eb28de2fe0d93b8; //keccak256("currentRequestId") event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 indexed _currentChallenge, uint256[5] _currentRequestId, uint256 _difficulty, uint256 _totalTips ); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted(address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId != 0, "RequestId is 0"); require(_tip != 0, "Tip should be greater than 0"); uint256 _count =self.uintVars[requestCount] + 1; if(_requestId == _count){ self.uintVars[requestCount] = _count; } else{ require(_requestId < _count, "RequestId is not less than count"); } TellorTransfer.doTransfer(self, msg.sender, address(this), _tip); //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[totalTip]); } /** * @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256[5] memory _requestId) public { TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the previous challenge //otherwise it sets it to 1 uint timeDiff = now - self.uintVars[timeOfLastNewValue]; int256 _change = int256(SafeMath.min(1200, timeDiff)); int256 _diff = int256(self.uintVars[difficulty]); _change = (_diff * (int256(self.uintVars[timeTarget]) - _change)) / 4000; if (_change == 0) { _change = 1; } self.uintVars[difficulty] = uint256(SafeMath.max(_diff + _change,1)); //Sets time of value submission rounded to 1 minute bytes32 _currChallenge = self.currentChallenge; uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[timeOfLastNewValue] = _timeOfLastNewValue; uint[5] memory a; for (uint k = 0; k < 5; k++) { for (uint i = 1; i < 5; i++) { uint256 temp = _tblock.valuesByTimestamp[k][i]; address temp2 = _tblock.minersByValue[k][i]; uint256 j = i; while (j > 0 && temp < _tblock.valuesByTimestamp[k][j - 1]) { _tblock.valuesByTimestamp[k][j] = _tblock.valuesByTimestamp[k][j - 1]; _tblock.minersByValue[k][j] = _tblock.minersByValue[k][j - 1]; j--; } if (j < i) { _tblock.valuesByTimestamp[k][j] = temp; _tblock.minersByValue[k][j] = temp2; } } TellorStorage.Request storage _request = self.requestDetails[_requestId[k]]; //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number a = _tblock.valuesByTimestamp[k]; _request.finalValues[_timeOfLastNewValue] = a[2]; _request.minersByValue[_timeOfLastNewValue] = _tblock.minersByValue[k]; _request.valuesByTimestamp[_timeOfLastNewValue] = _tblock.valuesByTimestamp[k]; delete _tblock.minersByValue[k]; delete _tblock.valuesByTimestamp[k]; _request.requestTimestamps.push(_timeOfLastNewValue); _request.minedBlockNum[_timeOfLastNewValue] = block.number; _request.apiUintVars[totalTip] = 0; } emit NewValue( _requestId, _timeOfLastNewValue, a, self.uintVars[runningTips], _currChallenge ); //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId[0]; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); address[5] memory miners = self.requestDetails[_requestId[0]].minersByValue[_timeOfLastNewValue]; //payMinersRewards _payReward(self, timeDiff, miners); self.uintVars[_tBlock] ++; uint256[5] memory _topId = TellorStake.getTopRequestIDs(self); for(uint i = 0; i< 5;i++){ self.currentMiners[i].value = _topId[i]; self.requestQ[self.requestDetails[_topId[i]].apiUintVars[requestQPosition]] = 0; self.uintVars[currentTotalTips] += self.requestDetails[_topId[i]].apiUintVars[totalTip]; } //Issue the the next challenge _currChallenge = keccak256(abi.encode(_nonce, _currChallenge, blockhash(block.number - 1))); self.currentChallenge = _currChallenge; // Save hash for next proof emit NewChallenge( _currChallenge, _topId, self.uintVars[difficulty], self.uintVars[currentTotalTips] ); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { _verifyNonce(self, _nonce); _submitMiningSolution(self, _nonce, _requestId, _value); } function _submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value) internal { //Verifying Miner Eligibility bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender)); require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); require(now - self.uintVars[_hashMsgSender] > 15 minutes, "Miner can only win rewards once per 15 min"); require(_requestId[0] == self.currentMiners[0].value,"Request ID is wrong"); require(_requestId[1] == self.currentMiners[1].value,"Request ID is wrong"); require(_requestId[2] == self.currentMiners[2].value,"Request ID is wrong"); require(_requestId[3] == self.currentMiners[3].value,"Request ID is wrong"); require(_requestId[4] == self.currentMiners[4].value,"Request ID is wrong"); self.uintVars[_hashMsgSender] = now; bytes32 _currChallenge = self.currentChallenge; uint256 _slotProgress = self.uintVars[slotProgress]; //Saving the challenge information as unique by using the msg.sender //Checking and updating Miner Status require(self.minersByChallenge[_currChallenge][msg.sender] == false, "Miner already submitted the value"); //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[_currChallenge][msg.sender] = true; //Updating Request TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; _tblock.minersByValue[1][_slotProgress]= msg.sender; //Assigng directly is cheaper than using a for loop _tblock.valuesByTimestamp[0][_slotProgress] = _value[0]; _tblock.valuesByTimestamp[1][_slotProgress] = _value[1]; _tblock.valuesByTimestamp[2][_slotProgress] = _value[2]; _tblock.valuesByTimestamp[3][_slotProgress] = _value[3]; _tblock.valuesByTimestamp[4][_slotProgress] = _value[4]; _tblock.minersByValue[0][_slotProgress]= msg.sender; _tblock.minersByValue[1][_slotProgress]= msg.sender; _tblock.minersByValue[2][_slotProgress]= msg.sender; _tblock.minersByValue[3][_slotProgress]= msg.sender; _tblock.minersByValue[4][_slotProgress]= msg.sender; //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received if (_slotProgress + 1 == 5) { //slotProgress has been incremented, but we're using the variable on stack to save gas newBlock(self, _nonce, _requestId); self.uintVars[slotProgress] = 0; } else{ self.uintVars[slotProgress]++; } emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, _currChallenge); } function _verifyNonce(TellorStorage.TellorStorageStruct storage self,string memory _nonce ) view internal { require(uint256( sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) ) % self.uintVars[difficulty] == 0 || (now - (now % 1 minutes)) - self.uintVars[timeOfLastNewValue] >= 15 minutes, "Incorrect nonce for current challenge" ); } /** * @dev Internal function to calculate and pay rewards to miners * */ function _payReward(TellorStorage.TellorStorageStruct storage self, uint _timeDiff, address[5] memory miners) internal { //_timeDiff is how many minutes passed since last block uint _currReward = 1e18; uint reward = _timeDiff* _currReward / 300; //each miner get's uint _tip = self.uintVars[currentTotalTips] / 10; uint _devShare = reward / 2; TellorTransfer.doTransfer(self, address(this), miners[0], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[1], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[2], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[3], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[4], reward + _tip); //update the total supply self.uintVars[total_supply] += _devShare + reward * 5 - (self.uintVars[currentTotalTips] / 2); TellorTransfer.doTransfer(self, address(this), self.addressVars[_owner], _devShare); self.uintVars[currentTotalTips] = 0; } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) public { require(msg.sender == self.addressVars[_owner], "Sender is not owner"); emit OwnershipProposed(self.addressVars[_owner], _pendingOwner); self.addressVars[pending_owner] = _pendingOwner; } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership(TellorStorage.TellorStorageStruct storage self) public { require(msg.sender == self.addressVars[pending_owner], "Sender is not pending owner"); emit OwnershipTransferred(self.addressVars[_owner], self.addressVars[pending_owner]); self.addressVars[_owner] = self.addressVars[pending_owner]; } /** * @dev This function updates APIonQ and the requestQ when requestData or addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; _request.apiUintVars[totalTip] = _request.apiUintVars[totalTip].add(_tip); if(self.currentMiners[0].value == _requestId || self.currentMiners[1].value== _requestId ||self.currentMiners[2].value == _requestId||self.currentMiners[3].value== _requestId || self.currentMiners[4].value== _requestId ){ self.uintVars[currentTotalTips] += _tip; } else { //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[requestQPosition] == 0) { uint256 _min; uint256 _index; (_min, _index) = Utilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_request.apiUintVars[totalTip] > _min || _min == 0) { self.requestQ[_index] = _request.apiUintVars[totalTip]; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[requestQPosition] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[requestQPosition] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else{ self.requestQ[_request.apiUintVars[requestQPosition]] += _tip; } } } }
library TellorLibrary { using SafeMath for uint256; bytes32 public constant requestCount = 0x05de9147d05477c0a5dc675aeea733157f5092f82add148cf39d579cafe3dc98; //keccak256("requestCount") bytes32 public constant totalTip = 0x2a9e355a92978430eca9c1aa3a9ba590094bac282594bccf82de16b83046e2c3; //keccak256("totalTip") bytes32 public constant _tBlock = 0x969ea04b74d02bb4d9e6e8e57236e1b9ca31627139ae9f0e465249932e824502; //keccak256("_tBlock") bytes32 public constant timeOfLastNewValue = 0x97e6eb29f6a85471f7cc9b57f9e4c3deaf398cfc9798673160d7798baf0b13a4; //keccak256("timeOfLastNewValue") bytes32 public constant difficulty = 0xb12aff7664b16cb99339be399b863feecd64d14817be7e1f042f97e3f358e64e; //keccak256("difficulty") bytes32 public constant timeTarget = 0xad16221efc80aaf1b7e69bd3ecb61ba5ffa539adf129c3b4ffff769c9b5bbc33; //keccak256("timeTarget") bytes32 public constant runningTips = 0xdb21f0c4accc4f2f5f1045353763a9ffe7091ceaf0fcceb5831858d96cf84631; //keccak256("runningTips") bytes32 public constant currentReward = 0x9b6853911475b07474368644a0d922ee13bc76a15cd3e97d3e334326424a47d4; //keccak256("currentReward") bytes32 public constant total_supply = 0xb1557182e4359a1f0c6301278e8f5b35a776ab58d39892581e357578fb287836; //keccak256("total_supply") bytes32 public constant devShare = 0x8fe9ded8d7c08f720cf0340699024f83522ea66b2bbfb8f557851cb9ee63b54c; //keccak256("devShare") bytes32 public constant _owner = 0x9dbc393ddc18fd27b1d9b1b129059925688d2f2d5818a5ec3ebb750b7c286ea6; //keccak256("_owner") bytes32 public constant requestQPosition = 0x1e344bd070f05f1c5b3f0b1266f4f20d837a0a8190a3a2da8b0375eac2ba86ea; //keccak256("requestQPosition") bytes32 public constant currentTotalTips = 0xd26d9834adf5a73309c4974bf654850bb699df8505e70d4cfde365c417b19dfc; //keccak256("currentTotalTips") bytes32 public constant slotProgress =0x6c505cb2db6644f57b42d87bd9407b0f66788b07d0617a2bc1356a0e69e66f9a; //keccak256("slotProgress") bytes32 public constant pending_owner = 0x44b2657a0f8a90ed8e62f4c4cceca06eacaa9b4b25751ae1ebca9280a70abd68; //keccak256("pending_owner") bytes32 public constant currentRequestId = 0x7584d7d8701714da9c117f5bf30af73b0b88aca5338a84a21eb28de2fe0d93b8; //keccak256("currentRequestId") event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 indexed _currentChallenge, uint256[5] _currentRequestId, uint256 _difficulty, uint256 _totalTips ); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted(address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId != 0, "RequestId is 0"); require(_tip != 0, "Tip should be greater than 0"); uint256 _count =self.uintVars[requestCount] + 1; if(_requestId == _count){ self.uintVars[requestCount] = _count; } else{ require(_requestId < _count, "RequestId is not less than count"); } TellorTransfer.doTransfer(self, msg.sender, address(this), _tip); //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[totalTip]); } /** * @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256[5] memory _requestId) public { TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the previous challenge //otherwise it sets it to 1 uint timeDiff = now - self.uintVars[timeOfLastNewValue]; int256 _change = int256(SafeMath.min(1200, timeDiff)); int256 _diff = int256(self.uintVars[difficulty]); _change = (_diff * (int256(self.uintVars[timeTarget]) - _change)) / 4000; if (_change == 0) { _change = 1; } self.uintVars[difficulty] = uint256(SafeMath.max(_diff + _change,1)); //Sets time of value submission rounded to 1 minute bytes32 _currChallenge = self.currentChallenge; uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[timeOfLastNewValue] = _timeOfLastNewValue; uint[5] memory a; for (uint k = 0; k < 5; k++) { for (uint i = 1; i < 5; i++) { uint256 temp = _tblock.valuesByTimestamp[k][i]; address temp2 = _tblock.minersByValue[k][i]; uint256 j = i; while (j > 0 && temp < _tblock.valuesByTimestamp[k][j - 1]) { _tblock.valuesByTimestamp[k][j] = _tblock.valuesByTimestamp[k][j - 1]; _tblock.minersByValue[k][j] = _tblock.minersByValue[k][j - 1]; j--; } if (j < i) { _tblock.valuesByTimestamp[k][j] = temp; _tblock.minersByValue[k][j] = temp2; } } TellorStorage.Request storage _request = self.requestDetails[_requestId[k]]; //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number a = _tblock.valuesByTimestamp[k]; _request.finalValues[_timeOfLastNewValue] = a[2]; _request.minersByValue[_timeOfLastNewValue] = _tblock.minersByValue[k]; _request.valuesByTimestamp[_timeOfLastNewValue] = _tblock.valuesByTimestamp[k]; delete _tblock.minersByValue[k]; delete _tblock.valuesByTimestamp[k]; _request.requestTimestamps.push(_timeOfLastNewValue); _request.minedBlockNum[_timeOfLastNewValue] = block.number; _request.apiUintVars[totalTip] = 0; } emit NewValue( _requestId, _timeOfLastNewValue, a, self.uintVars[runningTips], _currChallenge ); //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId[0]; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); address[5] memory miners = self.requestDetails[_requestId[0]].minersByValue[_timeOfLastNewValue]; //payMinersRewards _payReward(self, timeDiff, miners); self.uintVars[_tBlock] ++; uint256[5] memory _topId = TellorStake.getTopRequestIDs(self); for(uint i = 0; i< 5;i++){ self.currentMiners[i].value = _topId[i]; self.requestQ[self.requestDetails[_topId[i]].apiUintVars[requestQPosition]] = 0; self.uintVars[currentTotalTips] += self.requestDetails[_topId[i]].apiUintVars[totalTip]; } //Issue the the next challenge _currChallenge = keccak256(abi.encode(_nonce, _currChallenge, blockhash(block.number - 1))); self.currentChallenge = _currChallenge; // Save hash for next proof emit NewChallenge( _currChallenge, _topId, self.uintVars[difficulty], self.uintVars[currentTotalTips] ); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { _verifyNonce(self, _nonce); _submitMiningSolution(self, _nonce, _requestId, _value); } function _submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value) internal { //Verifying Miner Eligibility bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender)); require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); require(now - self.uintVars[_hashMsgSender] > 15 minutes, "Miner can only win rewards once per 15 min"); require(_requestId[0] == self.currentMiners[0].value,"Request ID is wrong"); require(_requestId[1] == self.currentMiners[1].value,"Request ID is wrong"); require(_requestId[2] == self.currentMiners[2].value,"Request ID is wrong"); require(_requestId[3] == self.currentMiners[3].value,"Request ID is wrong"); require(_requestId[4] == self.currentMiners[4].value,"Request ID is wrong"); self.uintVars[_hashMsgSender] = now; bytes32 _currChallenge = self.currentChallenge; uint256 _slotProgress = self.uintVars[slotProgress]; //Saving the challenge information as unique by using the msg.sender //Checking and updating Miner Status require(self.minersByChallenge[_currChallenge][msg.sender] == false, "Miner already submitted the value"); //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[_currChallenge][msg.sender] = true; //Updating Request TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; _tblock.minersByValue[1][_slotProgress]= msg.sender; //Assigng directly is cheaper than using a for loop _tblock.valuesByTimestamp[0][_slotProgress] = _value[0]; _tblock.valuesByTimestamp[1][_slotProgress] = _value[1]; _tblock.valuesByTimestamp[2][_slotProgress] = _value[2]; _tblock.valuesByTimestamp[3][_slotProgress] = _value[3]; _tblock.valuesByTimestamp[4][_slotProgress] = _value[4]; _tblock.minersByValue[0][_slotProgress]= msg.sender; _tblock.minersByValue[1][_slotProgress]= msg.sender; _tblock.minersByValue[2][_slotProgress]= msg.sender; _tblock.minersByValue[3][_slotProgress]= msg.sender; _tblock.minersByValue[4][_slotProgress]= msg.sender; //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received if (_slotProgress + 1 == 5) { //slotProgress has been incremented, but we're using the variable on stack to save gas newBlock(self, _nonce, _requestId); self.uintVars[slotProgress] = 0; } else{ self.uintVars[slotProgress]++; } emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, _currChallenge); } function _verifyNonce(TellorStorage.TellorStorageStruct storage self,string memory _nonce ) view internal { require(uint256( sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) ) % self.uintVars[difficulty] == 0 || (now - (now % 1 minutes)) - self.uintVars[timeOfLastNewValue] >= 15 minutes, "Incorrect nonce for current challenge" ); } /** * @dev Internal function to calculate and pay rewards to miners * */ function _payReward(TellorStorage.TellorStorageStruct storage self, uint _timeDiff, address[5] memory miners) internal { //_timeDiff is how many minutes passed since last block uint _currReward = 1e18; uint reward = _timeDiff* _currReward / 300; //each miner get's uint _tip = self.uintVars[currentTotalTips] / 10; uint _devShare = reward / 2; TellorTransfer.doTransfer(self, address(this), miners[0], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[1], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[2], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[3], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[4], reward + _tip); //update the total supply self.uintVars[total_supply] += _devShare + reward * 5 - (self.uintVars[currentTotalTips] / 2); TellorTransfer.doTransfer(self, address(this), self.addressVars[_owner], _devShare); self.uintVars[currentTotalTips] = 0; } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) public { require(msg.sender == self.addressVars[_owner], "Sender is not owner"); emit OwnershipProposed(self.addressVars[_owner], _pendingOwner); self.addressVars[pending_owner] = _pendingOwner; } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership(TellorStorage.TellorStorageStruct storage self) public { require(msg.sender == self.addressVars[pending_owner], "Sender is not pending owner"); emit OwnershipTransferred(self.addressVars[_owner], self.addressVars[pending_owner]); self.addressVars[_owner] = self.addressVars[pending_owner]; } /** * @dev This function updates APIonQ and the requestQ when requestData or addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; _request.apiUintVars[totalTip] = _request.apiUintVars[totalTip].add(_tip); if(self.currentMiners[0].value == _requestId || self.currentMiners[1].value== _requestId ||self.currentMiners[2].value == _requestId||self.currentMiners[3].value== _requestId || self.currentMiners[4].value== _requestId ){ self.uintVars[currentTotalTips] += _tip; } else { //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[requestQPosition] == 0) { uint256 _min; uint256 _index; (_min, _index) = Utilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_request.apiUintVars[totalTip] > _min || _min == 0) { self.requestQ[_index] = _request.apiUintVars[totalTip]; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[requestQPosition] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[requestQPosition] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else{ self.requestQ[_request.apiUintVars[requestQPosition]] += _tip; } } } }
26,078
167
// Initializes the contract setting the deployer as the initial owner. /
constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); }
constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); }
2,491
222
// Order must be targeted at this protocol version (this Exchange contract). /
if (order.exchange != address(this)) { return false; }
if (order.exchange != address(this)) { return false; }
20,475
55
// Purchase tokens from contract and distribute token bonuses to referrers. Master referrer will ALWAYS recieve at least a 1% token bonus. A second referrer address is required to be provided when purchasing and they will recieve at least 1%. A third referrer is optional, but not required. If the optional referrer is an autherized Referrer by the contract owner, then the optional referrer will receive a minimum of a 1% token bonus. purchaseAmount - the amount of tokens that the purchaser wants to buy referrer - second referrer that is required optionalReferrer - third referrer that is optional/
function purchaseTokens(uint256 purchaseAmount, address referrer, address optionalReferrer) public payable { require(_msgSender() != address(0), "AddressZero cannot purchase tokens"); require(isSaleActive(), "Sale is not active"); require(getTokenPrice() != 0, "Token price is not set"); require(getMaxBonusPercent() != 0, "Referral bonus percent is not set"); require(isReferrer(referrer), "Referrer is not authorized"); //Calculate big number amounts uint256 purchaseAmountBig = purchaseAmount * 1 ether; //Amount of tokens user is purchasing uint256 totalRAmountBig = purchaseAmountBig.mul(_maxBonusPercent).div(10**2); //Amount of tokens referrers will earn uint256 totalAmountBig = purchaseAmountBig.add(totalRAmountBig); //Total amount of tokens being distributed uint256 masterBonusPercent = _maxBonusPercent; //Bonus percent for the master referrer require(totalAmountBig <= _saleSupplyLeft, "Purchase amount is bigger than the remaining sale supply"); uint256 totalPrice = purchaseAmount * _tokenPrice; //Total ETH price for tokens require(msg.value >= totalPrice, "Payment amount too low"); //If the optionalReferrer is an authorized referrer, then distribute referral bonus tokens if(isReferrer(optionalReferrer)) { require(_referrers[referrer].bonusPercent + _referrers[optionalReferrer].bonusPercent < _maxBonusPercent, "Referrers bonus percent must be less than max bonus"); //Subtract the master's bonus by the referrers' bonus AND transfer tokens to the optional referrer masterBonusPercent = masterBonusPercent.sub(_referrers[referrer].bonusPercent).sub(_referrers[optionalReferrer].bonusPercent); transferReferralTokens(optionalReferrer, _referrers[optionalReferrer].bonusPercent, purchaseAmountBig); } //There is only one referrer, ignore the optional referrer else { require(_referrers[referrer].bonusPercent < _maxBonusPercent, "Referrer bonus percent must be less than max bonus"); //Subtract the master's bonus by the referrer's bonus masterBonusPercent = masterBonusPercent.sub(_referrers[referrer].bonusPercent); } //Transfer tokens to referrer, master referrer, and purchaser transferReferralTokens(referrer, _referrers[referrer].bonusPercent, purchaseAmountBig); transferReferralTokens(_masterReferrerWallet, masterBonusPercent, purchaseAmountBig); _token.transfer(msg.sender, (purchaseAmountBig)); //Modify sale information _weiRaised[_saleCount] = _weiRaised[_saleCount] + totalPrice; _saleSupplyLeft = _saleSupplyLeft - (totalAmountBig); //Transfer ETH back to presale wallet address payable walletPayable = payable(_ETHWallet); walletPayable.transfer(totalPrice); //Transfer extra ETH back to buyer address payable client = payable(msg.sender); client.transfer(msg.value - totalPrice); }
function purchaseTokens(uint256 purchaseAmount, address referrer, address optionalReferrer) public payable { require(_msgSender() != address(0), "AddressZero cannot purchase tokens"); require(isSaleActive(), "Sale is not active"); require(getTokenPrice() != 0, "Token price is not set"); require(getMaxBonusPercent() != 0, "Referral bonus percent is not set"); require(isReferrer(referrer), "Referrer is not authorized"); //Calculate big number amounts uint256 purchaseAmountBig = purchaseAmount * 1 ether; //Amount of tokens user is purchasing uint256 totalRAmountBig = purchaseAmountBig.mul(_maxBonusPercent).div(10**2); //Amount of tokens referrers will earn uint256 totalAmountBig = purchaseAmountBig.add(totalRAmountBig); //Total amount of tokens being distributed uint256 masterBonusPercent = _maxBonusPercent; //Bonus percent for the master referrer require(totalAmountBig <= _saleSupplyLeft, "Purchase amount is bigger than the remaining sale supply"); uint256 totalPrice = purchaseAmount * _tokenPrice; //Total ETH price for tokens require(msg.value >= totalPrice, "Payment amount too low"); //If the optionalReferrer is an authorized referrer, then distribute referral bonus tokens if(isReferrer(optionalReferrer)) { require(_referrers[referrer].bonusPercent + _referrers[optionalReferrer].bonusPercent < _maxBonusPercent, "Referrers bonus percent must be less than max bonus"); //Subtract the master's bonus by the referrers' bonus AND transfer tokens to the optional referrer masterBonusPercent = masterBonusPercent.sub(_referrers[referrer].bonusPercent).sub(_referrers[optionalReferrer].bonusPercent); transferReferralTokens(optionalReferrer, _referrers[optionalReferrer].bonusPercent, purchaseAmountBig); } //There is only one referrer, ignore the optional referrer else { require(_referrers[referrer].bonusPercent < _maxBonusPercent, "Referrer bonus percent must be less than max bonus"); //Subtract the master's bonus by the referrer's bonus masterBonusPercent = masterBonusPercent.sub(_referrers[referrer].bonusPercent); } //Transfer tokens to referrer, master referrer, and purchaser transferReferralTokens(referrer, _referrers[referrer].bonusPercent, purchaseAmountBig); transferReferralTokens(_masterReferrerWallet, masterBonusPercent, purchaseAmountBig); _token.transfer(msg.sender, (purchaseAmountBig)); //Modify sale information _weiRaised[_saleCount] = _weiRaised[_saleCount] + totalPrice; _saleSupplyLeft = _saleSupplyLeft - (totalAmountBig); //Transfer ETH back to presale wallet address payable walletPayable = payable(_ETHWallet); walletPayable.transfer(totalPrice); //Transfer extra ETH back to buyer address payable client = payable(msg.sender); client.transfer(msg.value - totalPrice); }
45,290
2
// update url
function updateDefaultUri(string memory _before, string memory _after) external onlyOwner override returns (bool){ beforeUri = _before; // update the before uri for MPI afterUri = _after; // update the after uri for MPI return true; }
function updateDefaultUri(string memory _before, string memory _after) external onlyOwner override returns (bool){ beforeUri = _before; // update the before uri for MPI afterUri = _after; // update the after uri for MPI return true; }
11,319
50
// Calculates settlementFee amount Option amountreturn fee Settlement fee amount /
function getSettlementFee(uint amount) internal pure returns (uint) { return amount / 100; }
function getSettlementFee(uint amount) internal pure returns (uint) { return amount / 100; }
42,606
2
// loop through to addresses and send value
for (uint8 i = 0; i < _to.length; i++) { assert((Token(_t).transferFrom(msg.sender,_to[i], _value[i])) == true); }
for (uint8 i = 0; i < _to.length; i++) { assert((Token(_t).transferFrom(msg.sender,_to[i], _value[i])) == true); }
29,063
23
// To:
idByAddress[_to] = _id; positionsByAddress[_to].push(_id);
idByAddress[_to] = _id; positionsByAddress[_to].push(_id);
41,570
11
// --- Treasury ---/This returns the stability fee treasury allowance for this contract by taking the minimum between the per block and the total allowances/
function treasuryAllowance() public view returns (uint256) { (uint total, uint perBlock) = treasury.getAllowance(address(this)); return minimum(total, perBlock); }
function treasuryAllowance() public view returns (uint256) { (uint total, uint perBlock) = treasury.getAllowance(address(this)); return minimum(total, perBlock); }
792
16
// Hash of the EIP712 Domain Separator data solhint-disable-next-line var-name-mixedcase
bytes32 public EIP712_DOMAIN_HASH;
bytes32 public EIP712_DOMAIN_HASH;
17,037
9
// initialization
function Registrator (){ //price = pricePlace; // address public notarius = owner; Notariuses[msg.sender] = true; }
function Registrator (){ //price = pricePlace; // address public notarius = owner; Notariuses[msg.sender] = true; }
3,727
11
// Delete the payments registry object and refund gas_subscriptionIdentifier is the identifier of that customer's/
function deletePayment(bytes32 _subscriptionIdentifier) public onlyAuthorized
function deletePayment(bytes32 _subscriptionIdentifier) public onlyAuthorized
37,238
4
// Returns a human readable (short) name about this oracle./data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle./ For example:/ (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));/ return (string) A human readable symbol name about this oracle.
function symbol(bytes calldata data) external view returns (string memory);
function symbol(bytes calldata data) external view returns (string memory);
70,452
14
// Get the state of the token upgrade. /
function getUpgradeState() public view returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; }
function getUpgradeState() public view returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; }
17,813
42
// Function Change Owner
function OWN_transferOwnership(address newOwner) onlyOwner public { // function allowed only if the address is not smart contract if (!isContract(newOwner)) { owner = newOwner; } }
function OWN_transferOwnership(address newOwner) onlyOwner public { // function allowed only if the address is not smart contract if (!isContract(newOwner)) { owner = newOwner; } }
57,056
19
// Verifies that a mint request is signed by an account holding MINTER_ROLE (at the time of the function call).
function verify(MintRequest calldata _req, bytes calldata _signature) public view returns (bool, address) { address signer = recoverAddress(_req, _signature); return (!minted[_req.uid] && hasRole(MINTER_ROLE, signer), signer); }
function verify(MintRequest calldata _req, bytes calldata _signature) public view returns (bool, address) { address signer = recoverAddress(_req, _signature); return (!minted[_req.uid] && hasRole(MINTER_ROLE, signer), signer); }
58,260
19
// Balances
mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) internal allowed;
mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) internal allowed;
8,821
0
// Exchange addresses
address internal UniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address internal UniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
39,444
11
// Checks that the converted token is currently present in the contract.
require(tokenBalance > 0, "NO_BALANCE_TO_CONVERT");
require(tokenBalance > 0, "NO_BALANCE_TO_CONVERT");
13,904
4
// Get the hash of an input in a DApp's input box./_dapp The address of the DApp/_index The index of the input in the DApp's input box/ return The hash of the input at the provided index in the DApp's input box/`_index` MUST be in the interval `[0,n)` where `n` is the number of/inputs in the DApp's input box. See the `getNumberOfInputs` function.
function getInputHash( address _dapp, uint256 _index ) external view returns (bytes32);
function getInputHash( address _dapp, uint256 _index ) external view returns (bytes32);
7,524
62
// 可以清算
merchant[tempAddr].score -= _score; totalSettledScore += _score; SettleScore(msg.sender, 0, "商户积分清算成功"); return;
merchant[tempAddr].score -= _score; totalSettledScore += _score; SettleScore(msg.sender, 0, "商户积分清算成功"); return;
25,115
125
// deposit allowed only one month before deadline
if(now < onTimeTimestamp - EARTH_SECONDS_IN_MONTH) { return 0; /// @notice means deposit is in advance than allowed } else if(onTimeTimestamp >= now) {
if(now < onTimeTimestamp - EARTH_SECONDS_IN_MONTH) { return 0; /// @notice means deposit is in advance than allowed } else if(onTimeTimestamp >= now) {
24,172
3
// emitted when gated sale commission is updated for a given sale
event AdminSetKoCommissionOverrideForSale(uint256 indexed _saleId, uint256 _platformPrimarySaleCommission);
event AdminSetKoCommissionOverrideForSale(uint256 indexed _saleId, uint256 _platformPrimarySaleCommission);
54,392
24
// Harvest all
function harvestAll(uint256 _pid) external { for (uint8 i = 0; i < userInfo[_pid][msg.sender].length; i++) { UserInfo memory user = userInfo[_pid][msg.sender][i]; if (user.amount > 0) { harvest(_pid, i); } } }
function harvestAll(uint256 _pid) external { for (uint8 i = 0; i < userInfo[_pid][msg.sender].length; i++) { UserInfo memory user = userInfo[_pid][msg.sender][i]; if (user.amount > 0) { harvest(_pid, i); } } }
34,814
41
// increase referral count of referrer
referralCount[_referrer]++;
referralCount[_referrer]++;
48,439
18
// remove proof for simple call schedule
oraclize_setProof(proofType_NONE); oraclize_query(config_pricecheck_delay, "URL", "", config_update_gas_limit); pool = pool.sub(balance.sub(address(this).balance));
oraclize_setProof(proofType_NONE); oraclize_query(config_pricecheck_delay, "URL", "", config_update_gas_limit); pool = pool.sub(balance.sub(address(this).balance));
2,886
107
// Modern and gas efficient ERC-721 + ERC-20/EIP-2612-like implementation,/ including the MetaData, and partially, Enumerable extensions.
contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed spender, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ address implementation_; address public admin; /*/////////////////////////////////////////////////////////////// ERC-721 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; uint256 public maxSupply; mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// VIEW FUNCTION //////////////////////////////////////////////////////////////*/ function owner() external view returns (address) { return admin; } /*/////////////////////////////////////////////////////////////// ERC-20-LIKE LOGIC //////////////////////////////////////////////////////////////*/ function transfer(address to, uint256 tokenId) external { require(msg.sender == ownerOf[tokenId], "NOT_OWNER"); _transfer(msg.sender, to, tokenId); } /*/////////////////////////////////////////////////////////////// ERC-721 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) external pure returns (bool supported) { supported = interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f; } function approve(address spender, uint256 tokenId) external { address owner_ = ownerOf[tokenId]; require( msg.sender == owner_ || isApprovedForAll[owner_][msg.sender], "NOT_APPROVED" ); getApproved[tokenId] = spender; emit Approval(owner_, spender, tokenId); } function setApprovalForAll(address operator, bool approved) external { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom(address from, address to, uint256 tokenId) public { address owner_ = ownerOf[tokenId]; require( msg.sender == owner_ || msg.sender == getApproved[tokenId] || isApprovedForAll[owner_][msg.sender], "NOT_APPROVED" ); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) external { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public { transferFrom(from, to, tokenId); if (to.code.length != 0) { // selector = `onERC721Received(address,address,uint,bytes)` (, bytes memory returned) = to.staticcall( abi.encodeWithSelector( 0x150b7a02, msg.sender, from, tokenId, data ) ); bytes4 selector = abi.decode(returned, (bytes4)); require(selector == 0x150b7a02, "NOT_ERC721_RECEIVER"); } } /*/////////////////////////////////////////////////////////////// INTERNAL UTILS //////////////////////////////////////////////////////////////*/ function _transfer(address from, address to, uint256 tokenId) internal { require(ownerOf[tokenId] == from); balanceOf[from]--; balanceOf[to]++; delete getApproved[tokenId]; ownerOf[tokenId] = to; emit Transfer(from, to, tokenId); } function _mint(address to, uint256 tokenId) internal { require(ownerOf[tokenId] == address(0), "ALREADY_MINTED"); require(totalSupply++ <= maxSupply, "MAX SUPPLY REACHED"); // This is safe because the sum of all user // balances can't exceed type(uint256).max! unchecked { balanceOf[to]++; } ownerOf[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal { address owner_ = ownerOf[tokenId]; require(ownerOf[tokenId] != address(0), "NOT_MINTED"); totalSupply--; balanceOf[owner_]--; delete ownerOf[tokenId]; emit Transfer(owner_, address(0), tokenId); } }
contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed spender, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ address implementation_; address public admin; /*/////////////////////////////////////////////////////////////// ERC-721 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; uint256 public maxSupply; mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// VIEW FUNCTION //////////////////////////////////////////////////////////////*/ function owner() external view returns (address) { return admin; } /*/////////////////////////////////////////////////////////////// ERC-20-LIKE LOGIC //////////////////////////////////////////////////////////////*/ function transfer(address to, uint256 tokenId) external { require(msg.sender == ownerOf[tokenId], "NOT_OWNER"); _transfer(msg.sender, to, tokenId); } /*/////////////////////////////////////////////////////////////// ERC-721 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) external pure returns (bool supported) { supported = interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f; } function approve(address spender, uint256 tokenId) external { address owner_ = ownerOf[tokenId]; require( msg.sender == owner_ || isApprovedForAll[owner_][msg.sender], "NOT_APPROVED" ); getApproved[tokenId] = spender; emit Approval(owner_, spender, tokenId); } function setApprovalForAll(address operator, bool approved) external { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom(address from, address to, uint256 tokenId) public { address owner_ = ownerOf[tokenId]; require( msg.sender == owner_ || msg.sender == getApproved[tokenId] || isApprovedForAll[owner_][msg.sender], "NOT_APPROVED" ); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) external { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public { transferFrom(from, to, tokenId); if (to.code.length != 0) { // selector = `onERC721Received(address,address,uint,bytes)` (, bytes memory returned) = to.staticcall( abi.encodeWithSelector( 0x150b7a02, msg.sender, from, tokenId, data ) ); bytes4 selector = abi.decode(returned, (bytes4)); require(selector == 0x150b7a02, "NOT_ERC721_RECEIVER"); } } /*/////////////////////////////////////////////////////////////// INTERNAL UTILS //////////////////////////////////////////////////////////////*/ function _transfer(address from, address to, uint256 tokenId) internal { require(ownerOf[tokenId] == from); balanceOf[from]--; balanceOf[to]++; delete getApproved[tokenId]; ownerOf[tokenId] = to; emit Transfer(from, to, tokenId); } function _mint(address to, uint256 tokenId) internal { require(ownerOf[tokenId] == address(0), "ALREADY_MINTED"); require(totalSupply++ <= maxSupply, "MAX SUPPLY REACHED"); // This is safe because the sum of all user // balances can't exceed type(uint256).max! unchecked { balanceOf[to]++; } ownerOf[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal { address owner_ = ownerOf[tokenId]; require(ownerOf[tokenId] != address(0), "NOT_MINTED"); totalSupply--; balanceOf[owner_]--; delete ownerOf[tokenId]; emit Transfer(owner_, address(0), tokenId); } }
3,467
60
// Emits a {CallScheduled} event. Requirements: - the caller must have the 'proposer' role. /
function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); }
function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); }
23,515
36
// A method to retrieve the stake for a stakeholder. _stakeholder The stakeholder to retrieve the stake for.return uint256 The amount of wei staked. /
function stakeOf(address _stakeholder) public view returns(uint256)
function stakeOf(address _stakeholder) public view returns(uint256)
5,133
25
// Since root role is always at ID 0, we don't need to shift
return uint256(userRoles) & 1 != 0;
return uint256(userRoles) & 1 != 0;
37,411
75
// Claims reward for the user. It transfers the claimable reward to the user and updates user's liquidity limit.Note: We allow anyone to claim other rewards on behalf of others, but not for the AC reward. This is because claiming ACreward also updates the user's liquidity limit. Therefore, only authorized claimer can do that on behalf of user. _account Address of the user to claim. _receiver Address that receives the claimed reward _claimRewards Whether to claim other rewards as well. /
function claim(address _account, address _receiver, bool _claimRewards) external;
function claim(address _account, address _receiver, bool _claimRewards) external;
16,647
35
// 战略伙伴锁仓总额度
mapping(address=>uint256) public lockAmount;
mapping(address=>uint256) public lockAmount;
78,411
56
// We always give out coins in proportion to how many we have, Now if all coins were the same value, this math would easy, just take the percentage of each coin, and multiply by the value to be given out. But if coins are worth more than $1, then we would end up handing out too many coins. We need to adjust by the total value of coins. To do this, we total up the value of our coins, by their percentages. Then divide what we would otherwise give out by this number. Let say we have 100 DAI at
uint256 assetCount = getAssetCount(); uint256[] memory assetPrices = _getAssetPrices(); uint256[] memory assetBalances = new uint256[](assetCount); uint256[] memory assetDecimals = new uint256[](assetCount); uint256 totalOutputRatio = 0; outputs = new uint256[](assetCount);
uint256 assetCount = getAssetCount(); uint256[] memory assetPrices = _getAssetPrices(); uint256[] memory assetBalances = new uint256[](assetCount); uint256[] memory assetDecimals = new uint256[](assetCount); uint256 totalOutputRatio = 0; outputs = new uint256[](assetCount);
5,054
3
// we can create promo fishs, up to a limit. Only callable by COO/_genes the encoded genes of the fish to be created, any value is accepted/_owner the future owner of the created fishs. Default to contract COO
function createPromofish(uint256 _genes, address _owner) external onlyOwner { address fishOwner = _owner; if (fishOwner == address(0)) { fishOwner = owner; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createFish(_genes,0, 0, 0, fishOwner); }
function createPromofish(uint256 _genes, address _owner) external onlyOwner { address fishOwner = _owner; if (fishOwner == address(0)) { fishOwner = owner; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createFish(_genes,0, 0, 0, fishOwner); }
43,744
72
// Developer fund
uint256 public devFund; uint256 public devCount; mapping(uint256 => address) public devIDs; mapping(address => uint256) public devAllocations;
uint256 public devFund; uint256 public devCount; mapping(uint256 => address) public devIDs; mapping(address => uint256) public devAllocations;
42,338
68
// leave remaining balance for company to be claimed at later date
balances[this] = balances[this].sub(_burnAmount); Burn(this, _burnAmount);
balances[this] = balances[this].sub(_burnAmount); Burn(this, _burnAmount);
5,016
31
// to get the functions of ERC721 contract, we inherits from it
contract MyEpicGame is ERC721 { //Each NFT will have this attributes: struct CharacterAttributes { uint characterIndex; string name; string imageURI; string characterType; uint hp; uint maxHp; uint attackDamage; } //Array to hold default data about characters CharacterAttributes[] defaultCharacters; //Creating the tokenID: using Counters for Counters.Counter; Counters.Counter private _tokenIds; //Mapping for tokenId => NFT: mapping(uint256 => CharacterAttributes) public nftHolderAttributes; //mapping for adress => tokenId: mapping(address => uint256) public nftHolders; event CharacterNFTMinted(address sender, uint256 tokenId, uint256 characterIndex); event AttackComplete(uint newBossHp, uint newPlayerHp); //creating the boss for the game: struct BigBoss { string name; string imageURI; uint hp; uint maxHp; uint attackDamage; } BigBoss public bigBoss; //Doing a looping to saving the values of each character (there will be 3 types) and creating the boos: constructor( string[] memory characterNames, string[] memory characterImageURIs, string[] memory characterType, uint[] memory characterHp, uint[] memory characterAttackDmg, string memory bossName, string memory bossImageURI, uint bossHp, uint bossAttackDamage // token name and symbol ) ERC721("Masters", "HE") { for(uint i = 0; i < characterNames.length; i += 1) { defaultCharacters.push(CharacterAttributes({ characterIndex: i, name: characterNames[i], imageURI: characterImageURIs[i], characterType: characterType[i], hp: characterHp[i], maxHp: characterHp[i], attackDamage: characterAttackDmg[i] })); CharacterAttributes memory c = defaultCharacters[i]; console.log("Done initializing %s w/ HP %s, img %s", c.name, c.hp, c.imageURI);} //the boss: bigBoss = BigBoss({ name: bossName, imageURI: bossImageURI, hp: bossHp, maxHp: bossHp, attackDamage: bossAttackDamage}); console.log("Done initializing boss %s w/ HP %s, img %s", bigBoss.name, bigBoss.hp, bigBoss.imageURI); //increment for NFT starting with id = 1 _tokenIds.increment(); } //functions for users to mint the NFT: function mintCharacterNFT(uint _characterIndex) external { uint256 newItemId = _tokenIds.current(); //function to mint nfts: _safeMint(msg.sender, newItemId); nftHolderAttributes[newItemId] = CharacterAttributes({ characterIndex: _characterIndex, name: defaultCharacters[_characterIndex].name, imageURI: defaultCharacters[_characterIndex].imageURI, characterType: defaultCharacters[_characterIndex].characterType, hp: defaultCharacters[_characterIndex].hp, maxHp: defaultCharacters[_characterIndex].maxHp, attackDamage: defaultCharacters[_characterIndex].attackDamage }); console.log("Minted NFT w/ tokenId %s and characterIndex %s", newItemId, _characterIndex); //mapping who owns the NFT nftHolders[msg.sender] = newItemId; //increment the tokenID: _tokenIds.increment(); //emit event emit CharacterNFTMinted(msg.sender, newItemId, _characterIndex); } //function to attack the dragon: function attackBoss() public { // Get the state of the player's NFT. uint256 nftTokenIdOfPlayer = nftHolders[msg.sender]; CharacterAttributes storage player = nftHolderAttributes[nftTokenIdOfPlayer]; console.log("\nPlayer w/ character %s about to attack. Has %s HP and %s AD", player.name, player.hp, player.attackDamage); console.log("Boss %s has %s HP and %s AD", bigBoss.name, bigBoss.hp, bigBoss.attackDamage); //the player only can attack if it isnt dead! require ( player.hp > 0, "Error: character must have HP to attack boss." ); //the player only can attack a dragon alive! require ( bigBoss.hp > 0, "Error: boss must have HP to attack boss." ); //Player Attack Boss -turnaround to not get negative numbers(we are only working with uint) - if (bigBoss.hp < player.attackDamage) { bigBoss.hp = 0; } else { bigBoss.hp = bigBoss.hp - player.attackDamage; } //Boss Attack player-turnaround to not get negative numbers(we are only working with uint) - if (player.hp < bigBoss.attackDamage) { player.hp = 0; } else { player.hp = player.hp - bigBoss.attackDamage; } console.log("Player attacked boss. New boss hp: %s", bigBoss.hp); console.log("Boss attacked player. New player hp: %s\n", player.hp); emit AttackComplete(bigBoss.hp, player.hp); } //function to see player NFT: function checkIfUserHasNFT() public view returns (CharacterAttributes memory) { // Get the tokenId of the user's character NFT uint256 userNftTokenId = nftHolders[msg.sender]; // If the user has a tokenId in the map, return their character. if (userNftTokenId > 0) { return nftHolderAttributes[userNftTokenId]; } // Else, return an empty character. else { CharacterAttributes memory emptyStruct; return emptyStruct; } } //function to see the default characters: function getAllDefaultCharacters() public view returns (CharacterAttributes[] memory) { return defaultCharacters; } //function to see the boss: function getBigBoss() public view returns (BigBoss memory) { return bigBoss; } //creating the URI function: function tokenURI(uint256 _tokenId) public view override returns (string memory) { CharacterAttributes memory charAttributes = nftHolderAttributes[_tokenId]; string memory strHp = Strings.toString(charAttributes.hp); string memory strMaxHp = Strings.toString(charAttributes.maxHp); string memory strAttackDamage = Strings.toString(charAttributes.attackDamage); string memory json = Base64.encode( abi.encodePacked( '{"name": "', charAttributes.name, ' -- NFT #: ', Strings.toString(_tokenId), ' -- Type: ', charAttributes.characterType, '", "description": "This is an NFT that lets people play in the He-man Metaverse!", "image": "', charAttributes.imageURI, '", "attributes": [ { "trait_type": "Health Points", "value": ',strHp,', "max_value":',strMaxHp,'}, { "trait_type": "Attack Damage", "value": ', strAttackDamage,'}]}' ) ); string memory output = string( abi.encodePacked("data:application/json;base64,", json) ); return output; } }
contract MyEpicGame is ERC721 { //Each NFT will have this attributes: struct CharacterAttributes { uint characterIndex; string name; string imageURI; string characterType; uint hp; uint maxHp; uint attackDamage; } //Array to hold default data about characters CharacterAttributes[] defaultCharacters; //Creating the tokenID: using Counters for Counters.Counter; Counters.Counter private _tokenIds; //Mapping for tokenId => NFT: mapping(uint256 => CharacterAttributes) public nftHolderAttributes; //mapping for adress => tokenId: mapping(address => uint256) public nftHolders; event CharacterNFTMinted(address sender, uint256 tokenId, uint256 characterIndex); event AttackComplete(uint newBossHp, uint newPlayerHp); //creating the boss for the game: struct BigBoss { string name; string imageURI; uint hp; uint maxHp; uint attackDamage; } BigBoss public bigBoss; //Doing a looping to saving the values of each character (there will be 3 types) and creating the boos: constructor( string[] memory characterNames, string[] memory characterImageURIs, string[] memory characterType, uint[] memory characterHp, uint[] memory characterAttackDmg, string memory bossName, string memory bossImageURI, uint bossHp, uint bossAttackDamage // token name and symbol ) ERC721("Masters", "HE") { for(uint i = 0; i < characterNames.length; i += 1) { defaultCharacters.push(CharacterAttributes({ characterIndex: i, name: characterNames[i], imageURI: characterImageURIs[i], characterType: characterType[i], hp: characterHp[i], maxHp: characterHp[i], attackDamage: characterAttackDmg[i] })); CharacterAttributes memory c = defaultCharacters[i]; console.log("Done initializing %s w/ HP %s, img %s", c.name, c.hp, c.imageURI);} //the boss: bigBoss = BigBoss({ name: bossName, imageURI: bossImageURI, hp: bossHp, maxHp: bossHp, attackDamage: bossAttackDamage}); console.log("Done initializing boss %s w/ HP %s, img %s", bigBoss.name, bigBoss.hp, bigBoss.imageURI); //increment for NFT starting with id = 1 _tokenIds.increment(); } //functions for users to mint the NFT: function mintCharacterNFT(uint _characterIndex) external { uint256 newItemId = _tokenIds.current(); //function to mint nfts: _safeMint(msg.sender, newItemId); nftHolderAttributes[newItemId] = CharacterAttributes({ characterIndex: _characterIndex, name: defaultCharacters[_characterIndex].name, imageURI: defaultCharacters[_characterIndex].imageURI, characterType: defaultCharacters[_characterIndex].characterType, hp: defaultCharacters[_characterIndex].hp, maxHp: defaultCharacters[_characterIndex].maxHp, attackDamage: defaultCharacters[_characterIndex].attackDamage }); console.log("Minted NFT w/ tokenId %s and characterIndex %s", newItemId, _characterIndex); //mapping who owns the NFT nftHolders[msg.sender] = newItemId; //increment the tokenID: _tokenIds.increment(); //emit event emit CharacterNFTMinted(msg.sender, newItemId, _characterIndex); } //function to attack the dragon: function attackBoss() public { // Get the state of the player's NFT. uint256 nftTokenIdOfPlayer = nftHolders[msg.sender]; CharacterAttributes storage player = nftHolderAttributes[nftTokenIdOfPlayer]; console.log("\nPlayer w/ character %s about to attack. Has %s HP and %s AD", player.name, player.hp, player.attackDamage); console.log("Boss %s has %s HP and %s AD", bigBoss.name, bigBoss.hp, bigBoss.attackDamage); //the player only can attack if it isnt dead! require ( player.hp > 0, "Error: character must have HP to attack boss." ); //the player only can attack a dragon alive! require ( bigBoss.hp > 0, "Error: boss must have HP to attack boss." ); //Player Attack Boss -turnaround to not get negative numbers(we are only working with uint) - if (bigBoss.hp < player.attackDamage) { bigBoss.hp = 0; } else { bigBoss.hp = bigBoss.hp - player.attackDamage; } //Boss Attack player-turnaround to not get negative numbers(we are only working with uint) - if (player.hp < bigBoss.attackDamage) { player.hp = 0; } else { player.hp = player.hp - bigBoss.attackDamage; } console.log("Player attacked boss. New boss hp: %s", bigBoss.hp); console.log("Boss attacked player. New player hp: %s\n", player.hp); emit AttackComplete(bigBoss.hp, player.hp); } //function to see player NFT: function checkIfUserHasNFT() public view returns (CharacterAttributes memory) { // Get the tokenId of the user's character NFT uint256 userNftTokenId = nftHolders[msg.sender]; // If the user has a tokenId in the map, return their character. if (userNftTokenId > 0) { return nftHolderAttributes[userNftTokenId]; } // Else, return an empty character. else { CharacterAttributes memory emptyStruct; return emptyStruct; } } //function to see the default characters: function getAllDefaultCharacters() public view returns (CharacterAttributes[] memory) { return defaultCharacters; } //function to see the boss: function getBigBoss() public view returns (BigBoss memory) { return bigBoss; } //creating the URI function: function tokenURI(uint256 _tokenId) public view override returns (string memory) { CharacterAttributes memory charAttributes = nftHolderAttributes[_tokenId]; string memory strHp = Strings.toString(charAttributes.hp); string memory strMaxHp = Strings.toString(charAttributes.maxHp); string memory strAttackDamage = Strings.toString(charAttributes.attackDamage); string memory json = Base64.encode( abi.encodePacked( '{"name": "', charAttributes.name, ' -- NFT #: ', Strings.toString(_tokenId), ' -- Type: ', charAttributes.characterType, '", "description": "This is an NFT that lets people play in the He-man Metaverse!", "image": "', charAttributes.imageURI, '", "attributes": [ { "trait_type": "Health Points", "value": ',strHp,', "max_value":',strMaxHp,'}, { "trait_type": "Attack Damage", "value": ', strAttackDamage,'}]}' ) ); string memory output = string( abi.encodePacked("data:application/json;base64,", json) ); return output; } }
51,730
20
// Returns the value stored at position `index` in the set. O(1). Note that there are no guarantees on the ordering of values inside thearray, and it may change when more values are added or removed. Requirements:
* - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; }
* - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; }
2,056
241
// Checks if requested set of features is enabled globally on the contractrequired set of features to check againstreturn true if all the features requested are enabled, false otherwise /
function isFeatureEnabled(uint256 required) public view returns (bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); }
function isFeatureEnabled(uint256 required) public view returns (bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); }
17,885
19
// Swap two tokens using this pool tokenIndexFrom the token the user wants to swap from tokenIndexTo the token the user wants to swap to dx the amount of tokens the user wants to swap from minDy the min amount the user would like to receive, or revert. deadline latest timestamp to accept this transaction /
function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override
function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override
34,833
69
// uint256 private constant _stabilizationLowerBound = 50; uint256 private constant _stabilizationLowerReset = 75; uint256 private constant _stabilizationUpperBound = 150; uint256 private constant _stabilizationUpperReset = 125; uint256 private constant _stabilizePercent = 10;
uint256 private constant _treasuryFee = 100; // 1%
uint256 private constant _treasuryFee = 100; // 1%
7,326