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
2
// Returns true if `account` is a contract. [IMPORTANT]====C U ON THE MOONIt is unsafe to assume that an address for which this function returnsfalse is an externally-owned account (EOA) and not a contract. Among others, `isContract` will return false for the followingtypes of addresses:- an externally-owned account - a contract in construction - an address where a contract will be created - an address where a contract lived, but was destroyed==== /
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
7,936
97
// setup local rID
uint256 _rID = rID_;
uint256 _rID = rID_;
5,139
3
// checks if there is an approved address clears it if there is
if (getApproved[tokenId_] != address(0x0)) { _approve(address(0x0), tokenId_); }
if (getApproved[tokenId_] != address(0x0)) { _approve(address(0x0), tokenId_); }
12,872
17
// NOTE: usually Treasury is behind proxy and this one minimizes possible errors.
function balance() external view returns(uint amount)
function balance() external view returns(uint amount)
7,954
116
// Used to retrieve the total GTX tokens for GTX claiming after the GTX ICO return uint256 - Presale stage/
function getStage() public view returns (uint256) { return uint(stage); }
function getStage() public view returns (uint256) { return uint(stage); }
37,206
13
// dont overmint
require(amount <= current_LIMIT -numTokens,"No Creatures left"); uint256 disc = 0 ; if (index != 0 ) { disc = discount[index] ; require(amount >= index , "order more items"); }
require(amount <= current_LIMIT -numTokens,"No Creatures left"); uint256 disc = 0 ; if (index != 0 ) { disc = discount[index] ; require(amount >= index , "order more items"); }
23,946
2
// `owner` defaults to msg.sender on construction.
constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); }
constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); }
1,484
36
// Revokes provider authorization. provider Address of the provider. /
function removeProvider(address provider) external onlyOwner
function removeProvider(address provider) external onlyOwner
23,940
19
// update price
function updatePrice(uint256 _price) public onlyOwner returns (bool){ price = _price ; return true; }
function updatePrice(uint256 _price) public onlyOwner returns (bool){ price = _price ; return true; }
53,571
5
// A crosschain call to open a gate
event CCOpenGate(string blockchainSystem, address contractAddress, string assetType, string gateName);
event CCOpenGate(string blockchainSystem, address contractAddress, string assetType, string gateName);
2,577
55
// mainnet address internal constant WHITE_LIST_ADDRESS = address(0x95Cc0c3F46Ae97b959d5Ffa02f0881C1994Ee39D); address internal constant TOKEN_MANAGER_ADDRESS = address(0x1c14052e535F47E041091D8de61F352cfd0d37c7);
IUniswapV2Router02 internal uniswapRouter; Whitelist internal whitelist; TokenManager internal tokenManager; using SafeMath for uint; using SafeERC20 for IERC20;
IUniswapV2Router02 internal uniswapRouter; Whitelist internal whitelist; TokenManager internal tokenManager; using SafeMath for uint; using SafeERC20 for IERC20;
34,267
20
// Cancel mint request, can be call only by ownerwhich created this mint request. /
function cancelMintRequest () public { require (msg.sender == setNewMint.initiator); require (!setNewMint.isCanceled && !setNewMint.isExecute); setNewMint.isCanceled = true; emit NewMintRequestCanceled(); }
function cancelMintRequest () public { require (msg.sender == setNewMint.initiator); require (!setNewMint.isCanceled && !setNewMint.isExecute); setNewMint.isCanceled = true; emit NewMintRequestCanceled(); }
20,361
110
// setting up default proposalTypes (board management txs)
proposalTypes["addProposalType"] = 0xeaa0dff1; proposalTypes["removeProposalType"] = 0x746d26b5; proposalTypes["changeMinVotes"] = 0x9bad192a; proposalTypes["addBoardMember"] = 0x1eac03ae; proposalTypes["removeBoardMember"] = 0x39a169f9; proposalTypes["replaceBoardMember"] = 0xbec44b4f;
proposalTypes["addProposalType"] = 0xeaa0dff1; proposalTypes["removeProposalType"] = 0x746d26b5; proposalTypes["changeMinVotes"] = 0x9bad192a; proposalTypes["addBoardMember"] = 0x1eac03ae; proposalTypes["removeBoardMember"] = 0x39a169f9; proposalTypes["replaceBoardMember"] = 0xbec44b4f;
41,965
6
// mapping from id to 'Transaction' to hold all empty, active, or finished transactions
mapping(uint256 txId => Transaction txInfo) public transactions;
mapping(uint256 txId => Transaction txInfo) public transactions;
21,479
19
// Transfers ENS name ownership back to original owner Can be run only by original owner or emergency multisig Sets newOwner to special address 0xdead/
function reclaimOwnership() public onlyWithoutNewOwner
function reclaimOwnership() public onlyWithoutNewOwner
48,516
17
// Increase authorized claim per share
authorizedPerShare = authorizedPerShare.add(mintPerShare);
authorizedPerShare = authorizedPerShare.add(mintPerShare);
50,824
4
// allows anyone to download to a charity and receive/give away a collectible ERC721 token charityName string the identifier of charity for which to donate the ether sent receiver address the address for whom to send the ERC721 token for the donation message string free text message from the donater /
function donate(string memory charityName, address receiver, string memory message) payable whenNotStopped public
function donate(string memory charityName, address receiver, string memory message) payable whenNotStopped public
557
174
// Do some validations depending on which step of the sale we are in
block.timestamp < publicSaleDate ? presaleValidations(ownerMintedCount, _mintAmount, supply) : publicsaleValidations(ownerMintedCount, _mintAmount); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); }
block.timestamp < publicSaleDate ? presaleValidations(ownerMintedCount, _mintAmount, supply) : publicsaleValidations(ownerMintedCount, _mintAmount); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); }
3,299
10
// Moves `amount` tokens from the caller's account to `recipient`. If send or receive hooks are registered for the caller and `recipient`,the corresponding functions will be called with `data` and empty`operatorData`. See {IERC777Sender} and {IERC777Recipient}. Emits a {Sent} event. Requirements - the caller must have at least `amount` tokens.- `recipient` cannot be the zero address.- if `recipient` is a contract, it must implement the {IERC777Recipient}interface. /
function send(address recipient, uint256 amount, bytes calldata data) external;
function send(address recipient, uint256 amount, bytes calldata data) external;
16,525
35
// ================================================to allow msg.senderto reduce allowance automatically on smart contract ================================================
emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); return true;
emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); return true;
42,734
13
// register investment and his amount with 10% interest rate. Basic members get 10% investment return.
investors.push(msg.sender); investmentsMade.push(amount * 110 / 100);
investors.push(msg.sender); investmentsMade.push(amount * 110 / 100);
9,924
11
// Structure for offer
struct CreateOffer { address nftAddress; uint256 tokenId; address owner; address buyer; address payToken; uint256 startTime; uint256 startPricePerItem; uint256 quantity; uint256 endTime; uint256 endPricePerItem; uint256 nonce; }
struct CreateOffer { address nftAddress; uint256 tokenId; address owner; address buyer; address payToken; uint256 startTime; uint256 startPricePerItem; uint256 quantity; uint256 endTime; uint256 endPricePerItem; uint256 nonce; }
17,115
11
// The last time they were paid out.
mapping(address => uint256) public lastUpdate; mapping(address => uint256) public lastUpdateCompanion;
mapping(address => uint256) public lastUpdate; mapping(address => uint256) public lastUpdateCompanion;
22,507
7
// Fix for short address attack against ERC20
modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; }
modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; }
3,835
60
// //Executes a relayed transaction._wallet The target wallet._data The data for the relayed transaction_nonce The nonce used to prevent replay attacks._signatures The signatures as a concatenated byte array._gasPrice The gas price to use for the gas refund._gasLimit The gas limit to use for the gas refund./
function execute( BaseWallet _wallet, bytes _data, uint256 _nonce, bytes _signatures, uint256 _gasPrice,
function execute( BaseWallet _wallet, bytes _data, uint256 _nonce, bytes _signatures, uint256 _gasPrice,
2,393
89
// 精度
uint256 private Precision;
uint256 private Precision;
8,342
165
// min supply
if (_targetSupply <= unleveraged) { _targetSupply = unleveraged; }
if (_targetSupply <= unleveraged) { _targetSupply = unleveraged; }
6,717
42
// Removes withdraw delay/This function can only be carreid out by the owner of this contract.
function removeWithdrawDelay() external onlyOwner { withdrawDelay = 0; }
function removeWithdrawDelay() external onlyOwner { withdrawDelay = 0; }
13,541
86
// Constructorwallet Wallet address where fees will gobsovTokenAddress Address of the lock tokenbsovTokenFee Fee for each lock in lock token/
constructor( address payable wallet, address bsovTokenAddress, uint256 bsovTokenFee, uint256 nonbsovTokenFee ) public
constructor( address payable wallet, address bsovTokenAddress, uint256 bsovTokenFee, uint256 nonbsovTokenFee ) public
18,122
118
// Sets the address of the base tokens used for the swap _token The address of a token to be usedas collateral/
function setBaseToken(address _token) public onlyOwner() { token = _token; }
function setBaseToken(address _token) public onlyOwner() { token = _token; }
72,679
228
// used to caculate user deposit weight
uint256[] private depositTimeWeight;
uint256[] private depositTimeWeight;
6,464
30
// Returns the current storage action
function currentAction() private pure returns (bytes4 action) { if (buffPtr() == bytes32(0)) return bytes4(0); assembly { action := mload(0xe0) } }
function currentAction() private pure returns (bytes4 action) { if (buffPtr() == bytes32(0)) return bytes4(0); assembly { action := mload(0xe0) } }
30,837
120
// disable Transfer delay - cannot be reenabled
function removeTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; }
function removeTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; }
1,197
12
// ICOBounty Percentage
uint256 public ICOBountyPercentage;
uint256 public ICOBountyPercentage;
17,596
27
// check new total oi on side does not exceed capOi
oiTotalOnSide += oi; oiTotalSharesOnSide += oi; require(oiTotalOnSide <= capOi, "OVLV1:oi>cap");
oiTotalOnSide += oi; oiTotalSharesOnSide += oi; require(oiTotalOnSide <= capOi, "OVLV1:oi>cap");
26,296
165
// change multiSig
function setMultiSig(address _address) public onlyGovernance { _setMultiSig(_address); }
function setMultiSig(address _address) public onlyGovernance { _setMultiSig(_address); }
32,930
387
// Emitted when the locking status is changed to locked./If a token is minted and the status is locked, this event should be emitted./tokenId The identifier for a token.
event Locked(uint256 tokenId);
event Locked(uint256 tokenId);
41,827
12
// gas optimization
if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y, "ERR_OVERFLOW"); return z;
if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y, "ERR_OVERFLOW"); return z;
15,573
16
// require(_ltAmount <= positions[_index].liquidity, "Position liquidity amount is less then requested");
uint256 receivedBAmount; uint256 liquidityBurned; { bytes memory data = abi.encodeWithSelector(bytes4(keccak256("closePosition(address,address,address,uint256,uint256)")),address(this),_basicToken,positions[_index].token,_ltAmount,_deadline); (bool success, bytes memory returnedData) = managers[positions[_index].manager].delegatecall(data); require(success, "PositionManager.closePosition call failed"); (receivedBAmount,liquidityBurned)=abi.decode(returnedData, (uint256, uint256)); }
uint256 receivedBAmount; uint256 liquidityBurned; { bytes memory data = abi.encodeWithSelector(bytes4(keccak256("closePosition(address,address,address,uint256,uint256)")),address(this),_basicToken,positions[_index].token,_ltAmount,_deadline); (bool success, bytes memory returnedData) = managers[positions[_index].manager].delegatecall(data); require(success, "PositionManager.closePosition call failed"); (receivedBAmount,liquidityBurned)=abi.decode(returnedData, (uint256, uint256)); }
2,526
15
// [External] Free certain portion of positions owned by the strategy _amount amount to free up /
function freeAavePositions(uint256 _amount) external onlyOwner { _freeAavePositions(_amount); }
function freeAavePositions(uint256 _amount) external onlyOwner { _freeAavePositions(_amount); }
37,705
6
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) { return msg.sender; }
function _msgSender() internal view returns(address payable) { return msg.sender; }
9,372
17
// Increment SupplyUsed.Note we can use tokenId as it is 1 based
supplyUsed = uint16(tokenId);
supplyUsed = uint16(tokenId);
29,399
461
// Collectable Dust
function sendDust( address _to, address _token, uint256 _amount
function sendDust( address _to, address _token, uint256 _amount
39,249
2
// Insert a new resource. _cid bytes16: Resource index(ClaimID). _udfsstring : The UDFS Hash value of the resource. _authoraddress: Declare the address of the resource. _pricing uint256: Pricing of resources. _deposit uint256: Declare a deposit required for a resource. _typeuint8: Type of resource.return bool : The successful call returns true. /
function insertClaim(bytes16 _cid, string _udfs, address _author, uint256 _pricing, uint256 _deposit, uint8 _type) public returns(bool)
function insertClaim(bytes16 _cid, string _udfs, address _author, uint256 _pricing, uint256 _deposit, uint8 _type) public returns(bool)
39,829
11
// Returns whether the bond has already been settled and the account hasbeen withdrawn from._orderHash - A keccack256 hash of the original order struct. /
function isSettled(bytes32 _orderHash) public view returns (bool ret) { return settled[_orderHash]; }
function isSettled(bytes32 _orderHash) public view returns (bool ret) { return settled[_orderHash]; }
51,239
25
// The address of the current highest bid.
address payable bidder;
address payable bidder;
23,546
3
// EscrowBase escrow contract, holds funds designated for a payee until they withdraw them.Intended usage: This contract (and derived escrow contracts) should be a standalone contract, that only interacts with the contract that instantiated it. That way, it is guaranteed that all Ether will be handled according to the Escrow rules, and there is no need to check for payable functions or transfers in the inheritance tree. The contract that uses the escrow as its payment method should be its primary, and provide public methods redirecting to the escrow's deposit and withdraw./
contract Escrow is Secondary { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public onlyPrimary payable { uint256 amount = msg.value; _deposits[payee] = _deposits[payee].add(amount); emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public onlyPrimary { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.transfer(payment); emit Withdrawn(payee, payment); } }
contract Escrow is Secondary { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public onlyPrimary payable { uint256 amount = msg.value; _deposits[payee] = _deposits[payee].add(amount); emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public onlyPrimary { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.transfer(payment); emit Withdrawn(payee, payment); } }
18,736
12
// Transfers control of the contract to a newOwner._newOwner The address to transfer ownership to./
function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; }
function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; }
23,524
1
// the total ordering of all events on a smart contract is defined a parent of 0x0 indicates root topic by convention, the bytes32 is a keccak-256 content hash the multihash prefix for this is 1b,20
event Topic(bytes32 _parentHash, bytes32 contentHash); event Payout(uint256 _lottery, address _user, uint256 _tokens); event Vote(uint256 _offset);
event Topic(bytes32 _parentHash, bytes32 contentHash); event Payout(uint256 _lottery, address _user, uint256 _tokens); event Vote(uint256 _offset);
22,411
175
// Destroys `amount` tokens from the caller. See {ERC20-_burn}. /
function burn(uint256 amount) external;
function burn(uint256 amount) external;
3,491
95
// use it in this contract, for optimized gas usage
function calcLiquidity(uint256 amount0, uint256 navps) public pure returns (uint256 liquidity) { liquidity = amount0.mul(NAVPS_BASE).div(navps); }
function calcLiquidity(uint256 amount0, uint256 navps) public pure returns (uint256 liquidity) { liquidity = amount0.mul(NAVPS_BASE).div(navps); }
38,379
19
// Unable to finalize an edition not marked as open (size set to uint64_max_value)
error Admin_UnableToFinalizeNotOpenEdition();
error Admin_UnableToFinalizeNotOpenEdition();
5,761
62
// Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`./pool Uniswap V3 pool/amount0 The amount of token0/amount1 The amount of token1/_tickLower The lower tick of the range/_tickUpper The upper tick of the range/ return The maximum amount of liquidity that can be held amount0 and amount1
function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper
function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper
20,521
42
// KYC data can not be present if added is false and hence we can set packed KYC as uint256(1) to set added as true
_dataStore.setUint256(_getKey(WHITELIST, _to), uint256(1));
_dataStore.setUint256(_getKey(WHITELIST, _to), uint256(1));
11,620
83
// The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
uint startBlock;
351
5
// maybe its better to use bytes32 data type for this variable.
bool paidDeposit; // we can add a check to make sure the citizen paid the deposit during the current year int taxesDue; // the amount of taxes the citizen needs to pay to the Municipality
bool paidDeposit; // we can add a check to make sure the citizen paid the deposit during the current year int taxesDue; // the amount of taxes the citizen needs to pay to the Municipality
20,674
112
// Close a deed and refund a specified fraction of the bid valuerefundRatio The amount1/1000 to refund /
function closeDeed(uint refundRatio) public onlyRegistrar onlyActive { active = false; require(burn.send(((1000 - refundRatio) * this.balance)/1000)); DeedClosed(); destroyDeed(); }
function closeDeed(uint refundRatio) public onlyRegistrar onlyActive { active = false; require(burn.send(((1000 - refundRatio) * this.balance)/1000)); DeedClosed(); destroyDeed(); }
34,680
92
// Place Bet and resume game
placeBet(bet);
placeBet(bet);
34,132
120
// ========== PUBLIC FUNCTIONS ========== / Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } }
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } }
12,615
134
// Helper function to process an arbitrary fee/If the fee is active, transfers a given portion in basis points of the specified value to the recipient/ return The fee that was taken
function _processFee( address token, uint256 amount, uint256 feeBps, address recipient
function _processFee( address token, uint256 amount, uint256 feeBps, address recipient
8,246
2
// require(_to != address(saleAuction)); require(_to != address(siringAuction));
require(_isOwns(msg.sender, _tokenId)); require(isForSale(_tokenId)); _transfer(msg.sender, _to, _tokenId);
require(_isOwns(msg.sender, _tokenId)); require(isForSale(_tokenId)); _transfer(msg.sender, _to, _tokenId);
52,350
2
// Treasury
ADJUST_TREASURY_CONFIRM_NUM_THRESHOLD, //設定國庫交易確認門檻 ADJUST_MASTER_TREASURY_CONFIRM_NUM_THRESHOLD //設定大師國庫交易確認門檻
ADJUST_TREASURY_CONFIRM_NUM_THRESHOLD, //設定國庫交易確認門檻 ADJUST_MASTER_TREASURY_CONFIRM_NUM_THRESHOLD //設定大師國庫交易確認門檻
2,855
9
// --- Single ERC20 listing ---
function acceptERC20Listing( ISeaport.AdvancedOrder calldata order, ERC20ListingParams calldata params, Fee[] calldata fees ) external nonReentrant refundERC20Leftover(params.refundTo, params.token) chargeERC20Fees(fees, params.token, params.amount)
function acceptERC20Listing( ISeaport.AdvancedOrder calldata order, ERC20ListingParams calldata params, Fee[] calldata fees ) external nonReentrant refundERC20Leftover(params.refundTo, params.token) chargeERC20Fees(fees, params.token, params.amount)
3,926
162
// Sequence force batches
for (uint256 i = 0; i < batchesNum; i++) {
for (uint256 i = 0; i < batchesNum; i++) {
6,298
111
// helper for get amount for both Bancor connectors for input amount of pool_amountrelay amount_relay address of bancor relay/
function getBancorConnectorsAmountByRelayAmount ( uint256 _amount, IERC20 _relay ) public view returns(uint256 bancorAmount, uint256 connectorAmount)
function getBancorConnectorsAmountByRelayAmount ( uint256 _amount, IERC20 _relay ) public view returns(uint256 bancorAmount, uint256 connectorAmount)
60,004
196
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID);
_pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID);
50,328
27
// LayerZeroBridgeERC20/Angle Labs, Inc., forked from https:github.com/LayerZero-Labs/solidity-examples/blob/main/contracts/token/oft/OFT.sol/Contract to be deployed on Ethereum for bridging an ERC20 token (ANGLE for instance) using/ a bridge intermediate token and LayerZero
contract LayerZeroBridgeERC20 is OFTCoreERC20, PausableUpgradeable { /// @notice Name of the contract for indexing purposes string public name; /// @notice Address of the bridgeable token IERC20 public canonicalToken; /// @notice Maps an address to the amount of token bridged but not received mapping(address => uint256) public balanceOf; // ================================ CONSTRUCTOR ================================ /// @notice Initializes the contract /// @param _name Name of the token corresponding to this contract /// @param _lzEndpoint Layer zero endpoint to pass messages /// @param _coreBorrow Address of the `CoreBorrow` contract used for access control function initialize( string memory _name, address _lzEndpoint, address _coreBorrow, IERC20 _canonicalToken ) external initializer { if (address(_canonicalToken) == address(0)) revert ZeroAddress(); __LzAppUpgradeable_init(_lzEndpoint, _coreBorrow); name = _name; canonicalToken = _canonicalToken; } /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} // ===================== EXTERNAL PERMISSIONLESS FUNCTIONS ===================== /// @inheritdoc OFTCoreERC20 function sendWithPermit( uint16 _dstChainId, bytes memory _toAddress, uint256 _amount, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20Permit(address(canonicalToken)).permit(msg.sender, address(this), _amount, deadline, v, r, s); send(_dstChainId, _toAddress, _amount, _refundAddress, _zroPaymentAddress, _adapterParams); } /// @inheritdoc OFTCoreERC20 function withdraw(uint256 amount, address recipient) external override returns (uint256) { return _withdraw(amount, msg.sender, recipient); } /// @notice Withdraws amount of `token` from the contract and sends it to the recipient /// @param amount Amount to withdraw /// @param recipient Address to withdraw for /// @return The amount of canonical token sent function withdrawFor(uint256 amount, address recipient) external returns (uint256) { return _withdraw(amount, recipient, recipient); } // ============================= INTERNAL FUNCTIONS ============================ /// @notice Withdraws `amount` from the balance of the `from` address and sends these tokens to the `to` address /// @dev It's important to make sure that `from` is either the `msg.sender` or that `from` and `to` are the same /// addresses function _withdraw( uint256 amount, address from, address to ) internal whenNotPaused returns (uint256) { balanceOf[from] = balanceOf[from] - amount; // Will overflow if the amount is too big canonicalToken.transfer(to, amount); return amount; } /// @inheritdoc OFTCoreERC20 function _debitFrom( uint16, bytes memory, uint256 _amount ) internal override whenNotPaused returns (uint256) { // No need to use safeTransferFrom as we know this implementation reverts on failure canonicalToken.transferFrom(msg.sender, address(this), _amount); return _amount; } /// @inheritdoc OFTCoreERC20 function _debitCreditFrom( uint16, bytes memory, uint256 _amount ) internal override whenNotPaused returns (uint256) { balanceOf[msg.sender] -= _amount; return _amount; } /// @inheritdoc OFTCoreERC20 function _creditTo( uint16, address _toAddress, uint256 _amount ) internal override whenNotPaused returns (uint256) { // Should never revert as all the LayerZero bridge tokens come from // this contract uint256 balance = canonicalToken.balanceOf(address(this)); if (balance < _amount) { balanceOf[_toAddress] = _amount - balance; if (balance > 0) canonicalToken.transfer(_toAddress, balance); } else { canonicalToken.transfer(_toAddress, _amount); } return _amount; } // =============================== VIEW FUNCTIONS ============================== /// @inheritdoc ERC165Upgradeable function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IOFTCore).interfaceId || super.supportsInterface(interfaceId); } // ============================ GOVERNANCE FUNCTIONS =========================== /// @notice Pauses bridging through the contract /// @param pause Future pause status function pauseSendTokens(bool pause) external onlyGovernorOrGuardian { pause ? _pause() : _unpause(); } /// @notice Decreases the balance of an address /// @param amount Amount to withdraw from balance /// @param recipient Address to withdraw from function sweep(uint256 amount, address recipient) external onlyGovernorOrGuardian { balanceOf[recipient] = balanceOf[recipient] - amount; // Will overflow if the amount is too big } uint256[47] private __gap; }
contract LayerZeroBridgeERC20 is OFTCoreERC20, PausableUpgradeable { /// @notice Name of the contract for indexing purposes string public name; /// @notice Address of the bridgeable token IERC20 public canonicalToken; /// @notice Maps an address to the amount of token bridged but not received mapping(address => uint256) public balanceOf; // ================================ CONSTRUCTOR ================================ /// @notice Initializes the contract /// @param _name Name of the token corresponding to this contract /// @param _lzEndpoint Layer zero endpoint to pass messages /// @param _coreBorrow Address of the `CoreBorrow` contract used for access control function initialize( string memory _name, address _lzEndpoint, address _coreBorrow, IERC20 _canonicalToken ) external initializer { if (address(_canonicalToken) == address(0)) revert ZeroAddress(); __LzAppUpgradeable_init(_lzEndpoint, _coreBorrow); name = _name; canonicalToken = _canonicalToken; } /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} // ===================== EXTERNAL PERMISSIONLESS FUNCTIONS ===================== /// @inheritdoc OFTCoreERC20 function sendWithPermit( uint16 _dstChainId, bytes memory _toAddress, uint256 _amount, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20Permit(address(canonicalToken)).permit(msg.sender, address(this), _amount, deadline, v, r, s); send(_dstChainId, _toAddress, _amount, _refundAddress, _zroPaymentAddress, _adapterParams); } /// @inheritdoc OFTCoreERC20 function withdraw(uint256 amount, address recipient) external override returns (uint256) { return _withdraw(amount, msg.sender, recipient); } /// @notice Withdraws amount of `token` from the contract and sends it to the recipient /// @param amount Amount to withdraw /// @param recipient Address to withdraw for /// @return The amount of canonical token sent function withdrawFor(uint256 amount, address recipient) external returns (uint256) { return _withdraw(amount, recipient, recipient); } // ============================= INTERNAL FUNCTIONS ============================ /// @notice Withdraws `amount` from the balance of the `from` address and sends these tokens to the `to` address /// @dev It's important to make sure that `from` is either the `msg.sender` or that `from` and `to` are the same /// addresses function _withdraw( uint256 amount, address from, address to ) internal whenNotPaused returns (uint256) { balanceOf[from] = balanceOf[from] - amount; // Will overflow if the amount is too big canonicalToken.transfer(to, amount); return amount; } /// @inheritdoc OFTCoreERC20 function _debitFrom( uint16, bytes memory, uint256 _amount ) internal override whenNotPaused returns (uint256) { // No need to use safeTransferFrom as we know this implementation reverts on failure canonicalToken.transferFrom(msg.sender, address(this), _amount); return _amount; } /// @inheritdoc OFTCoreERC20 function _debitCreditFrom( uint16, bytes memory, uint256 _amount ) internal override whenNotPaused returns (uint256) { balanceOf[msg.sender] -= _amount; return _amount; } /// @inheritdoc OFTCoreERC20 function _creditTo( uint16, address _toAddress, uint256 _amount ) internal override whenNotPaused returns (uint256) { // Should never revert as all the LayerZero bridge tokens come from // this contract uint256 balance = canonicalToken.balanceOf(address(this)); if (balance < _amount) { balanceOf[_toAddress] = _amount - balance; if (balance > 0) canonicalToken.transfer(_toAddress, balance); } else { canonicalToken.transfer(_toAddress, _amount); } return _amount; } // =============================== VIEW FUNCTIONS ============================== /// @inheritdoc ERC165Upgradeable function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IOFTCore).interfaceId || super.supportsInterface(interfaceId); } // ============================ GOVERNANCE FUNCTIONS =========================== /// @notice Pauses bridging through the contract /// @param pause Future pause status function pauseSendTokens(bool pause) external onlyGovernorOrGuardian { pause ? _pause() : _unpause(); } /// @notice Decreases the balance of an address /// @param amount Amount to withdraw from balance /// @param recipient Address to withdraw from function sweep(uint256 amount, address recipient) external onlyGovernorOrGuardian { balanceOf[recipient] = balanceOf[recipient] - amount; // Will overflow if the amount is too big } uint256[47] private __gap; }
16,891
29
// allow locked token to be obtained for member
function unlock () { require(now >= lockance[msg.sender].duration); uint256 _amount = lockance[msg.sender].amount; balances[msg.sender] += lockance[msg.sender].amount; lockance[msg.sender].amount = 0; Unlock(msg.sender, _amount); }
function unlock () { require(now >= lockance[msg.sender].duration); uint256 _amount = lockance[msg.sender].amount; balances[msg.sender] += lockance[msg.sender].amount; lockance[msg.sender].amount = 0; Unlock(msg.sender, _amount); }
10,120
119
// Sells
_taxAmt = sellTax;
_taxAmt = sellTax;
64,542
6
// Private properties
uint private lastRandomForGene; mapping(uint => bool) private mferClaimed; mapping(uint => bool) private aptClaimed; mapping(uint => TokenData) private tokenData; ERC721 private alienPunkThings; ERC721 private mfers; constructor() ERC721A("Alien Punk Mfers", "AlienPunkMfers")
uint private lastRandomForGene; mapping(uint => bool) private mferClaimed; mapping(uint => bool) private aptClaimed; mapping(uint => TokenData) private tokenData; ERC721 private alienPunkThings; ERC721 private mfers; constructor() ERC721A("Alien Punk Mfers", "AlienPunkMfers")
10,539
10
// Repay flashloan
(bool sent, ) = payable(address(flashloan)).call{value: flashLoanRepayAmount}("");
(bool sent, ) = payable(address(flashloan)).call{value: flashLoanRepayAmount}("");
30,911
305
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); }
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); }
5,691
19
// amount of asset that is to be transfered
uint256 amount;
uint256 amount;
8,492
90
// Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used toe.g. set automatic allowances for certain subsystems, etc.
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
2,832
36
// Math library for computing sqrt prices from ticks and vice versa/Aperture Finance/Modified from Uniswap (https:github.com/uniswap/v3-core/blob/main/contracts/libraries/TickMath.sol)/Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports/ prices between 2-128 and 2128
library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = 887272; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_RATIO - MIN_SQRT_RATIO - 1` uint160 internal constant MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE = 1461446703485210103287273052203988822378723970342 - 4295128739 - 1; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { unchecked { int256 tick256; assembly { // sign extend to make tick an int256 in twos complement tick256 := signextend(2, tick) } uint256 absTick = TernaryLib.abs(tick256); /// @solidity memory-safe-assembly assembly { // Equivalent: if (absTick > MAX_TICK) revert("T"); if gt(absTick, MAX_TICK) { // selector "Error(string)", [0x1c, 0x20) mstore(0, 0x08c379a0) // abi encoding offset mstore(0x20, 0x20) // reason string length 1 and 'T', [0x5f, 0x61) mstore(0x41, 0x0154) // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason revert(0x1c, 0x45) } } // Equivalent: ratio = 2**128 / sqrt(1.0001) if absTick & 0x1 else 1 << 128 uint256 ratio; assembly { ratio := and( shr( // 128 if absTick & 0x1 else 0 shl(7, and(absTick, 0x1)), // upper 128 bits of 2**256 / sqrt(1.0001) where the 128th bit is 1 0xfffcb933bd6fad37aa2d162d1a59400100000000000000000000000000000000 ), 0x1ffffffffffffffffffffffffffffffff // mask lower 129 bits ) } // Iterate through 1th to 19th bit of absTick because MAX_TICK < 2**20 // Equivalent to: // for i in range(1, 20): // if absTick & 2 ** i: // ratio = ratio * (2 ** 128 / 1.0001 ** (2 ** (i - 1))) / 2 ** 128 if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; // if (tick > 0) ratio = type(uint256).max / ratio; assembly { if sgt(tick256, 0) { ratio := div(not(0), ratio) } } // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent assembly { sqrtPriceX96 := shr(32, add(ratio, 0xffffffff)) } } } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // Equivalent: if (sqrtPriceX96 < MIN_SQRT_RATIO || sqrtPriceX96 >= MAX_SQRT_RATIO) revert("R"); // second inequality must be >= because the price can never reach the price at the max tick /// @solidity memory-safe-assembly assembly { // if sqrtPriceX96 < MIN_SQRT_RATIO, the `sub` underflows and `gt` is true // if sqrtPriceX96 >= MAX_SQRT_RATIO, sqrtPriceX96 - MIN_SQRT_RATIO > MAX_SQRT_RATIO - MAX_SQRT_RATIO - 1 if gt(sub(sqrtPriceX96, MIN_SQRT_RATIO), MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE) { // selector "Error(string)", [0x1c, 0x20) mstore(0, 0x08c379a0) // abi encoding offset mstore(0x20, 0x20) // reason string length 1 and 'R', [0x5f, 0x61) mstore(0x41, 0x0152) // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason revert(0x1c, 0x45) } } // Find the most significant bit of `sqrtPriceX96`, 160 > msb >= 32. uint8 msb; assembly { let x := sqrtPriceX96 msb := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) msb := or(msb, shl(6, lt(0xffffffffffffffff, shr(msb, x)))) msb := or(msb, shl(5, lt(0xffffffff, shr(msb, x)))) // For the remaining 32 bits, use a De Bruijn lookup. x := shr(msb, x) x := or(x, shr(1, x)) x := or(x, shr(2, x)) x := or(x, shr(4, x)) x := or(x, shr(8, x)) x := or(x, shr(16, x)) msb := or( msb, byte( shr(251, mul(x, shl(224, 0x07c4acdd))), 0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f ) ) } // 2**(msb - 95) > sqrtPrice >= 2**(msb - 96) // the integer part of log_2(sqrtPrice) * 2**64 = (msb - 96) << 64, 8.64 number int256 log_2X64; assembly { log_2X64 := shl(64, sub(msb, 96)) // Get the first 128 significant figures of `sqrtPriceX96`. // r = sqrtPriceX96 / 2**(msb - 127), where 2**128 > r >= 2**127 // sqrtPrice = 2**(msb - 96) * r / 2**127, in floating point math // Shift left first because 160 > msb >= 32. If we shift right first, we'll lose precision. let r := shr(sub(msb, 31), shl(96, sqrtPriceX96)) // Approximate `log_2X64` to 14 binary digits after decimal // log_2X64 = (msb - 96) * 2**64 + f_0 * 2**63 + f_1 * 2**62 + ...... // sqrtPrice**2 = 2**(2 * (msb - 96)) * (r / 2**127)**2 = 2**(2 * log_2X64 / 2**64) = 2**(2 * (msb - 96) + f_0) // 2**f_0 = (r / 2**127)**2 = r**2 / 2**255 * 2 // f_0 = 1 if (r**2 >= 2**255) else 0 // sqrtPrice**2 = 2**(2 * (msb - 96) + f_0) * r**2 / 2**(254 + f_0) = 2**(2 * (msb - 96) + f_0) * r' / 2**127 // r' = r**2 / 2**(127 + f_0) // sqrtPrice**4 = 2**(4 * (msb - 96) + 2 * f_0) * (r' / 2**127)**2 // = 2**(4 * log_2X64 / 2**64) = 2**(4 * (msb - 96) + 2 * f_0 + f_1) // 2**(f_1) = (r' / 2**127)**2 // f_1 = 1 if (r'**2 >= 2**255) else 0 // Check whether r >= sqrt(2) * 2**127 // 2**256 > r**2 >= 2**254 let square := mul(r, r) // f = (r**2 >= 2**255) let f := slt(square, 0) // r = r**2 >> 128 if r**2 >= 2**255 else r**2 >> 127 r := shr(add(127, f), square) log_2X64 := or(shl(63, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(62, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(61, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(60, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(59, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(58, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(57, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(56, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(55, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(54, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(53, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(52, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(51, f), log_2X64) log_2X64 := or(shl(50, slt(mul(r, r), 0)), log_2X64) } // sqrtPrice = sqrt(1.0001^tick) // tick = log_{sqrt(1.0001)}(sqrtPrice) = log_2(sqrtPrice) / log_2(sqrt(1.0001)) // 2**64 / log_2(sqrt(1.0001)) = 255738958999603826347141 int24 tickLow; int24 tickHi; assembly { let log_sqrt10001 := mul(log_2X64, 255738958999603826347141) // 128.128 number tickLow := shr(128, sub(log_sqrt10001, 3402992956809132418596140100660247210)) tickHi := shr(128, add(log_sqrt10001, 291339464771989622907027621153398088495)) } // Equivalent: tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; if (tickLow == tickHi) { tick = tickHi; } else { uint160 sqrtRatioAtTickHi = getSqrtRatioAtTick(tickHi); assembly { tick := sub(tickHi, gt(sqrtRatioAtTickHi, sqrtPriceX96)) } } } }
library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = 887272; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_RATIO - MIN_SQRT_RATIO - 1` uint160 internal constant MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE = 1461446703485210103287273052203988822378723970342 - 4295128739 - 1; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { unchecked { int256 tick256; assembly { // sign extend to make tick an int256 in twos complement tick256 := signextend(2, tick) } uint256 absTick = TernaryLib.abs(tick256); /// @solidity memory-safe-assembly assembly { // Equivalent: if (absTick > MAX_TICK) revert("T"); if gt(absTick, MAX_TICK) { // selector "Error(string)", [0x1c, 0x20) mstore(0, 0x08c379a0) // abi encoding offset mstore(0x20, 0x20) // reason string length 1 and 'T', [0x5f, 0x61) mstore(0x41, 0x0154) // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason revert(0x1c, 0x45) } } // Equivalent: ratio = 2**128 / sqrt(1.0001) if absTick & 0x1 else 1 << 128 uint256 ratio; assembly { ratio := and( shr( // 128 if absTick & 0x1 else 0 shl(7, and(absTick, 0x1)), // upper 128 bits of 2**256 / sqrt(1.0001) where the 128th bit is 1 0xfffcb933bd6fad37aa2d162d1a59400100000000000000000000000000000000 ), 0x1ffffffffffffffffffffffffffffffff // mask lower 129 bits ) } // Iterate through 1th to 19th bit of absTick because MAX_TICK < 2**20 // Equivalent to: // for i in range(1, 20): // if absTick & 2 ** i: // ratio = ratio * (2 ** 128 / 1.0001 ** (2 ** (i - 1))) / 2 ** 128 if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; // if (tick > 0) ratio = type(uint256).max / ratio; assembly { if sgt(tick256, 0) { ratio := div(not(0), ratio) } } // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent assembly { sqrtPriceX96 := shr(32, add(ratio, 0xffffffff)) } } } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // Equivalent: if (sqrtPriceX96 < MIN_SQRT_RATIO || sqrtPriceX96 >= MAX_SQRT_RATIO) revert("R"); // second inequality must be >= because the price can never reach the price at the max tick /// @solidity memory-safe-assembly assembly { // if sqrtPriceX96 < MIN_SQRT_RATIO, the `sub` underflows and `gt` is true // if sqrtPriceX96 >= MAX_SQRT_RATIO, sqrtPriceX96 - MIN_SQRT_RATIO > MAX_SQRT_RATIO - MAX_SQRT_RATIO - 1 if gt(sub(sqrtPriceX96, MIN_SQRT_RATIO), MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE) { // selector "Error(string)", [0x1c, 0x20) mstore(0, 0x08c379a0) // abi encoding offset mstore(0x20, 0x20) // reason string length 1 and 'R', [0x5f, 0x61) mstore(0x41, 0x0152) // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason revert(0x1c, 0x45) } } // Find the most significant bit of `sqrtPriceX96`, 160 > msb >= 32. uint8 msb; assembly { let x := sqrtPriceX96 msb := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) msb := or(msb, shl(6, lt(0xffffffffffffffff, shr(msb, x)))) msb := or(msb, shl(5, lt(0xffffffff, shr(msb, x)))) // For the remaining 32 bits, use a De Bruijn lookup. x := shr(msb, x) x := or(x, shr(1, x)) x := or(x, shr(2, x)) x := or(x, shr(4, x)) x := or(x, shr(8, x)) x := or(x, shr(16, x)) msb := or( msb, byte( shr(251, mul(x, shl(224, 0x07c4acdd))), 0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f ) ) } // 2**(msb - 95) > sqrtPrice >= 2**(msb - 96) // the integer part of log_2(sqrtPrice) * 2**64 = (msb - 96) << 64, 8.64 number int256 log_2X64; assembly { log_2X64 := shl(64, sub(msb, 96)) // Get the first 128 significant figures of `sqrtPriceX96`. // r = sqrtPriceX96 / 2**(msb - 127), where 2**128 > r >= 2**127 // sqrtPrice = 2**(msb - 96) * r / 2**127, in floating point math // Shift left first because 160 > msb >= 32. If we shift right first, we'll lose precision. let r := shr(sub(msb, 31), shl(96, sqrtPriceX96)) // Approximate `log_2X64` to 14 binary digits after decimal // log_2X64 = (msb - 96) * 2**64 + f_0 * 2**63 + f_1 * 2**62 + ...... // sqrtPrice**2 = 2**(2 * (msb - 96)) * (r / 2**127)**2 = 2**(2 * log_2X64 / 2**64) = 2**(2 * (msb - 96) + f_0) // 2**f_0 = (r / 2**127)**2 = r**2 / 2**255 * 2 // f_0 = 1 if (r**2 >= 2**255) else 0 // sqrtPrice**2 = 2**(2 * (msb - 96) + f_0) * r**2 / 2**(254 + f_0) = 2**(2 * (msb - 96) + f_0) * r' / 2**127 // r' = r**2 / 2**(127 + f_0) // sqrtPrice**4 = 2**(4 * (msb - 96) + 2 * f_0) * (r' / 2**127)**2 // = 2**(4 * log_2X64 / 2**64) = 2**(4 * (msb - 96) + 2 * f_0 + f_1) // 2**(f_1) = (r' / 2**127)**2 // f_1 = 1 if (r'**2 >= 2**255) else 0 // Check whether r >= sqrt(2) * 2**127 // 2**256 > r**2 >= 2**254 let square := mul(r, r) // f = (r**2 >= 2**255) let f := slt(square, 0) // r = r**2 >> 128 if r**2 >= 2**255 else r**2 >> 127 r := shr(add(127, f), square) log_2X64 := or(shl(63, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(62, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(61, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(60, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(59, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(58, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(57, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(56, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(55, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(54, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(53, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(52, f), log_2X64) square := mul(r, r) f := slt(square, 0) r := shr(add(127, f), square) log_2X64 := or(shl(51, f), log_2X64) log_2X64 := or(shl(50, slt(mul(r, r), 0)), log_2X64) } // sqrtPrice = sqrt(1.0001^tick) // tick = log_{sqrt(1.0001)}(sqrtPrice) = log_2(sqrtPrice) / log_2(sqrt(1.0001)) // 2**64 / log_2(sqrt(1.0001)) = 255738958999603826347141 int24 tickLow; int24 tickHi; assembly { let log_sqrt10001 := mul(log_2X64, 255738958999603826347141) // 128.128 number tickLow := shr(128, sub(log_sqrt10001, 3402992956809132418596140100660247210)) tickHi := shr(128, add(log_sqrt10001, 291339464771989622907027621153398088495)) } // Equivalent: tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; if (tickLow == tickHi) { tick = tickHi; } else { uint160 sqrtRatioAtTickHi = getSqrtRatioAtTick(tickHi); assembly { tick := sub(tickHi, gt(sqrtRatioAtTickHi, sqrtPriceX96)) } } } }
23,686
4
// Add Types.Call identifier
_encodedCalls[0] = abi.encodePacked(Types.Call).ref(0);
_encodedCalls[0] = abi.encodePacked(Types.Call).ref(0);
4,939
463
// Store the debt percentage and debt ledger as high precision integers
synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage);
synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage);
22,869
85
// Reverts if not in crowdsale time range. /
modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; }
modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; }
33,396
2
// Role given to an oracle address that is allowed to sign feed data
Signer
Signer
11,588
14
// Transfers control of the contract to a newOwner.newOwner The address to transfer ownership to./
function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
29,886
4
// WETH address
address weth;
address weth;
5,163
92
// Compliance with ERC-721 for Su Squares/This implementation assumes:/- A fixed supply of NFTs, cannot mint or burn/- ids are numbered sequentially starting at 1./- NFTs are initially assigned to this contract/- This contract does not externally call its own functions/William Entriken (https:phor.net)
contract CryptoStarsNFTs is ERC165, ERC721, ERC721Metadata, ERC721Enumerable, SupportsInterface { /// @dev The authorized address for each NFT mapping (uint256 => address) internal tokenApprovals; /// @dev The authorized operators for each address mapping (address => mapping (address => bool)) internal operatorApprovals; /// @dev Guarantees msg.sender is the owner of _tokenId /// @param _tokenId The token to validate belongs to msg.sender modifier onlyOwnerOf(uint256 _tokenId) { address owner = _tokenOwnerWithSubstitutions[_tokenId]; // assert(msg.sender != address(this)) require(msg.sender == owner); _; } modifier mustBeOwnedByThisContract(uint256 _tokenId) { require(_tokenId >= 1 && _tokenId <= TOTAL_SUPPLY); address owner = _tokenOwnerWithSubstitutions[_tokenId]; require(owner == address(0) || owner == address(this)); _; } modifier canOperate(uint256 _tokenId) { // assert(msg.sender != address(this)) address owner = _tokenOwnerWithSubstitutions[_tokenId]; require(msg.sender == owner || operatorApprovals[owner][msg.sender]); _; } modifier canTransfer(uint256 _tokenId) { // assert(msg.sender != address(this)) address owner = _tokenOwnerWithSubstitutions[_tokenId]; require(msg.sender == owner || msg.sender == tokenApprovals[_tokenId] || operatorApprovals[owner][msg.sender]); _; } modifier mustBeValidToken(uint256 _tokenId) { require(_tokenId >= 1 && _tokenId <= TOTAL_SUPPLY); _; } /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256) { require(_owner != address(0)); return _tokensOfOwnerWithSubstitutions[_owner].length; } /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view mustBeValidToken(_tokenId) returns (address _owner) { _owner = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (_owner == address(0)) { _owner = address(this); } } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable { _safeTransferFrom(_from, _to, _tokenId, data); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable mustBeValidToken(_tokenId) canTransfer(_tokenId) { address owner = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (owner == address(0)) { owner = address(this); } require(owner == _from); require(_to != address(0)); _transfer(_tokenId, _to); } /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable // assert(mustBeValidToken(_tokenId)) canOperate(_tokenId) { address _owner = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (_owner == address(0)) { _owner = address(this); } tokenApprovals[_tokenId] = _approved; emit Approval(_owner, _approved, _tokenId); } /// @notice Enable or disable approval for a third party ("operator") to /// manage all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view mustBeValidToken(_tokenId) returns (address) { return tokenApprovals[_tokenId]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorApprovals[_owner][_operator]; } // COMPLIANCE WITH ERC721Metadata ////////////////////////////////////////// /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string) { return "Crypto Stars"; } /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string) { return "CSTARS"; } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view mustBeValidToken(_tokenId) returns (string _tokenURI) { _tokenURI = "ipfs://QmcAmuwE6n2YGrbjgfRe2pJCmPd1RcBEhr55TmDznhgPv9/cryptostar0000.json"; bytes memory _tokenURIBytes = bytes(_tokenURI); _tokenURIBytes[64] = bytes1(uint8(48+(_tokenId / 1000) % 10)); _tokenURIBytes[65] = bytes1(uint8(48+(_tokenId / 100) % 10)); _tokenURIBytes[66] = bytes1(uint8(48+(_tokenId / 10) % 10)); _tokenURIBytes[67] = bytes1(uint8(48+(_tokenId / 1) % 10)); } // COMPLIANCE WITH ERC721Enumerable //////////////////////////////////////// /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one /// has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256) { return TOTAL_SUPPLY; } /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index < TOTAL_SUPPLY); return _index + 1; } /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_owner != address(0)); require(_index < _tokensOfOwnerWithSubstitutions[_owner].length); _tokenId = _tokensOfOwnerWithSubstitutions[_owner][_index]; // Handle substitutions if (_owner == address(this)) { if (_tokenId == 0) { _tokenId = _index + 1; } } } /* function available(uint8 needed) public view returns (uint8) { uint8 count=0; for (uint8 t=1;t<1002;t++) { if (_tokenOwnerWithSubstitutions[t] == address(0)) count++; // if (count>=needed) // { // return count; // break; // } } return count; } */ function starsAvailable() public view returns (uint256) { return _tokensOfOwnerWithSubstitutions[address(this)].length; } function buyCryptoStars(uint256 count) external payable { require(msg.value >= count*0.001 ether); require(starsAvailable()>=count); // function id "buyCryptoStars(uint16)": "d29b13b1", uint256 claimed=0; uint256 tokenid; do { tokenid=uint(keccak256(abi.encodePacked(block.timestamp*(tokenid+1)*(claimed+1), block.difficulty))) % 1001+1; while (_tokenOwnerWithSubstitutions[tokenid] != address(0)) { tokenid++; if (tokenid==1002) tokenid=1; } _transfer(tokenid, msg.sender); claimed++; } while (claimed<count); } function giftCryptoStars(uint256 count, address friend) internal { uint256 claimed=0; uint256 tokenid; do { tokenid=uint256(keccak256(abi.encodePacked(block.timestamp*(tokenid+1)*(claimed+1), block.difficulty))) % 1001+1; while (_tokenOwnerWithSubstitutions[tokenid] != address(0)) { tokenid++; if (tokenid==1002) tokenid=1; } _transfer(tokenid, friend); claimed++; } while (claimed<count); } // INTERNAL INTERFACE ////////////////////////////////////////////////////// /// @dev Actually do a transfer, does NO precondition checking function _transfer(uint256 _tokenId, address _to) internal { // Here are the preconditions we are not checking: // assert(canTransfer(_tokenId)) // assert(mustBeValidToken(_tokenId)) require(_to != address(0)); // Find the FROM address address from = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (from == address(0)) { from = address(this); } // Take away from the FROM address // The Entriken algorithm for deleting from an indexed, unsorted array uint256 indexToDelete = _ownedTokensIndexWithSubstitutions[_tokenId]; // Do owned tokens substitution if (indexToDelete == 0) { indexToDelete = _tokenId - 1; } else { indexToDelete = indexToDelete - 1; } // We can only shrink an array from its end. If the item we want to // delete is in the middle then copy last item to middle and shrink // the end. if (indexToDelete != _tokensOfOwnerWithSubstitutions[from].length - 1) { uint256 lastNft = _tokensOfOwnerWithSubstitutions[from][_tokensOfOwnerWithSubstitutions[from].length - 1]; // Do tokens of owner substitution if (lastNft == 0) { // assert(from == address(0) || from == address(this)); lastNft = _tokensOfOwnerWithSubstitutions[from].length; // - 1 + 1 } _tokensOfOwnerWithSubstitutions[from][indexToDelete] = lastNft; _ownedTokensIndexWithSubstitutions[lastNft] = indexToDelete + 1; } // Next line also deletes the contents at the last position of the array (gas refund) _tokensOfOwnerWithSubstitutions[from].length--; // Right now _ownedTokensIndexWithSubstitutions[_tokenId] is invalid, set it below based on the new owner // Give to the TO address _tokensOfOwnerWithSubstitutions[_to].push(_tokenId); _ownedTokensIndexWithSubstitutions[_tokenId] = (_tokensOfOwnerWithSubstitutions[_to].length - 1) + 1; // External processing _tokenOwnerWithSubstitutions[_tokenId] = _to; tokenApprovals[_tokenId] = address(0); emit Transfer(from, _to, _tokenId); } // PRIVATE STORAGE AND FUNCTIONS /////////////////////////////////////////// // See Solidity issue #3356, it would be clearer to initialize in SuMain uint256 private constant TOTAL_SUPPLY = 1001; bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); /// @dev The owner of each NFT /// If value == address(0), NFT is owned by address(this) /// If value != address(0), NFT is owned by value /// assert(This contract never assigns ownership to address(0) or destroys NFTs) /// See commented out code in constructor, saves hella gas /// In other words address(0) in storage means address(this) outside mapping (uint256 => address) private _tokenOwnerWithSubstitutions; /// @dev The list of NFTs owned by each address /// Nomenclature: arr[key][index] = value /// If key != address(this) or value != 0, then value represents an NFT /// If key == address(this) and value == 0, then index + 1 is the NFT /// assert(0 is not a valid NFT) /// See commented out code in constructor, saves hella gas /// In other words [0, 0, a, 0] is equivalent to [1, 2, a, 4] for address(this) mapping (address => uint256[]) private _tokensOfOwnerWithSubstitutions; /// @dev (Location + 1) of each NFT in its owner's list /// Nomenclature: arr[nftId] = value /// If value != 0, _tokensOfOwnerWithSubstitutions[owner][value - 1] = nftId /// If value == 0, _tokensOfOwnerWithSubstitutions[owner][nftId - 1] = nftId /// assert(2**256-1 is not a valid NFT) /// See commented out code in constructor, saves hella gas /// In other words mapping {a=>a} is equivalent to {a=>0} mapping (uint256 => uint256) private _ownedTokensIndexWithSubstitutions; // Due to implementation choices (no mint, no burn, contiguous NFT ids), it // is not necessary to keep an array of NFT ids nor where each NFT id is // located in that array. // address[] private nftIds; // mapping (uint256 => uint256) private nftIndexOfId; constructor() internal { // Publish interfaces with ERC-165 supportedInterfaces[0x80ac58cd] = true; // ERC721 supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable supportedInterfaces[0x8153916a] = true; // ERC721 + 165 (not needed) // The effect of substitution makes storing address(this), address(this) // ..., address(this) for a total of TOTAL_SUPPLY times unnecessary at // deployment time // for (uint256 i = 1; i <= TOTAL_SUPPLY; i++) { // _tokenOwnerWithSubstitutions[i] = address(this); // } // The effect of substitution makes storing 1, 2, ..., TOTAL_SUPPLY // unnecessary at deployment time _tokensOfOwnerWithSubstitutions[address(this)].length = TOTAL_SUPPLY; // for (uint256 i = 0; i < TOTAL_SUPPLY; i++) { // _tokensOfOwnerWithSubstitutions[address(this)][i] = i + 1; // } // for (uint256 i = 1; i <= TOTAL_SUPPLY; i++) { // _ownedTokensIndexWithSubstitutions[i] = i - 1; // } } /// @dev Actually perform the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) private mustBeValidToken(_tokenId) canTransfer(_tokenId) { address owner = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (owner == address(0)) { owner = address(this); } require(owner == _from); require(_to != address(0)); _transfer(_tokenId, _to); // Do the callback after everything is done to avoid reentrancy attack uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, data); require(retval == ERC721_RECEIVED); } }
contract CryptoStarsNFTs is ERC165, ERC721, ERC721Metadata, ERC721Enumerable, SupportsInterface { /// @dev The authorized address for each NFT mapping (uint256 => address) internal tokenApprovals; /// @dev The authorized operators for each address mapping (address => mapping (address => bool)) internal operatorApprovals; /// @dev Guarantees msg.sender is the owner of _tokenId /// @param _tokenId The token to validate belongs to msg.sender modifier onlyOwnerOf(uint256 _tokenId) { address owner = _tokenOwnerWithSubstitutions[_tokenId]; // assert(msg.sender != address(this)) require(msg.sender == owner); _; } modifier mustBeOwnedByThisContract(uint256 _tokenId) { require(_tokenId >= 1 && _tokenId <= TOTAL_SUPPLY); address owner = _tokenOwnerWithSubstitutions[_tokenId]; require(owner == address(0) || owner == address(this)); _; } modifier canOperate(uint256 _tokenId) { // assert(msg.sender != address(this)) address owner = _tokenOwnerWithSubstitutions[_tokenId]; require(msg.sender == owner || operatorApprovals[owner][msg.sender]); _; } modifier canTransfer(uint256 _tokenId) { // assert(msg.sender != address(this)) address owner = _tokenOwnerWithSubstitutions[_tokenId]; require(msg.sender == owner || msg.sender == tokenApprovals[_tokenId] || operatorApprovals[owner][msg.sender]); _; } modifier mustBeValidToken(uint256 _tokenId) { require(_tokenId >= 1 && _tokenId <= TOTAL_SUPPLY); _; } /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256) { require(_owner != address(0)); return _tokensOfOwnerWithSubstitutions[_owner].length; } /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view mustBeValidToken(_tokenId) returns (address _owner) { _owner = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (_owner == address(0)) { _owner = address(this); } } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable { _safeTransferFrom(_from, _to, _tokenId, data); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable mustBeValidToken(_tokenId) canTransfer(_tokenId) { address owner = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (owner == address(0)) { owner = address(this); } require(owner == _from); require(_to != address(0)); _transfer(_tokenId, _to); } /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable // assert(mustBeValidToken(_tokenId)) canOperate(_tokenId) { address _owner = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (_owner == address(0)) { _owner = address(this); } tokenApprovals[_tokenId] = _approved; emit Approval(_owner, _approved, _tokenId); } /// @notice Enable or disable approval for a third party ("operator") to /// manage all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view mustBeValidToken(_tokenId) returns (address) { return tokenApprovals[_tokenId]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorApprovals[_owner][_operator]; } // COMPLIANCE WITH ERC721Metadata ////////////////////////////////////////// /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string) { return "Crypto Stars"; } /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string) { return "CSTARS"; } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view mustBeValidToken(_tokenId) returns (string _tokenURI) { _tokenURI = "ipfs://QmcAmuwE6n2YGrbjgfRe2pJCmPd1RcBEhr55TmDznhgPv9/cryptostar0000.json"; bytes memory _tokenURIBytes = bytes(_tokenURI); _tokenURIBytes[64] = bytes1(uint8(48+(_tokenId / 1000) % 10)); _tokenURIBytes[65] = bytes1(uint8(48+(_tokenId / 100) % 10)); _tokenURIBytes[66] = bytes1(uint8(48+(_tokenId / 10) % 10)); _tokenURIBytes[67] = bytes1(uint8(48+(_tokenId / 1) % 10)); } // COMPLIANCE WITH ERC721Enumerable //////////////////////////////////////// /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one /// has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256) { return TOTAL_SUPPLY; } /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index < TOTAL_SUPPLY); return _index + 1; } /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_owner != address(0)); require(_index < _tokensOfOwnerWithSubstitutions[_owner].length); _tokenId = _tokensOfOwnerWithSubstitutions[_owner][_index]; // Handle substitutions if (_owner == address(this)) { if (_tokenId == 0) { _tokenId = _index + 1; } } } /* function available(uint8 needed) public view returns (uint8) { uint8 count=0; for (uint8 t=1;t<1002;t++) { if (_tokenOwnerWithSubstitutions[t] == address(0)) count++; // if (count>=needed) // { // return count; // break; // } } return count; } */ function starsAvailable() public view returns (uint256) { return _tokensOfOwnerWithSubstitutions[address(this)].length; } function buyCryptoStars(uint256 count) external payable { require(msg.value >= count*0.001 ether); require(starsAvailable()>=count); // function id "buyCryptoStars(uint16)": "d29b13b1", uint256 claimed=0; uint256 tokenid; do { tokenid=uint(keccak256(abi.encodePacked(block.timestamp*(tokenid+1)*(claimed+1), block.difficulty))) % 1001+1; while (_tokenOwnerWithSubstitutions[tokenid] != address(0)) { tokenid++; if (tokenid==1002) tokenid=1; } _transfer(tokenid, msg.sender); claimed++; } while (claimed<count); } function giftCryptoStars(uint256 count, address friend) internal { uint256 claimed=0; uint256 tokenid; do { tokenid=uint256(keccak256(abi.encodePacked(block.timestamp*(tokenid+1)*(claimed+1), block.difficulty))) % 1001+1; while (_tokenOwnerWithSubstitutions[tokenid] != address(0)) { tokenid++; if (tokenid==1002) tokenid=1; } _transfer(tokenid, friend); claimed++; } while (claimed<count); } // INTERNAL INTERFACE ////////////////////////////////////////////////////// /// @dev Actually do a transfer, does NO precondition checking function _transfer(uint256 _tokenId, address _to) internal { // Here are the preconditions we are not checking: // assert(canTransfer(_tokenId)) // assert(mustBeValidToken(_tokenId)) require(_to != address(0)); // Find the FROM address address from = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (from == address(0)) { from = address(this); } // Take away from the FROM address // The Entriken algorithm for deleting from an indexed, unsorted array uint256 indexToDelete = _ownedTokensIndexWithSubstitutions[_tokenId]; // Do owned tokens substitution if (indexToDelete == 0) { indexToDelete = _tokenId - 1; } else { indexToDelete = indexToDelete - 1; } // We can only shrink an array from its end. If the item we want to // delete is in the middle then copy last item to middle and shrink // the end. if (indexToDelete != _tokensOfOwnerWithSubstitutions[from].length - 1) { uint256 lastNft = _tokensOfOwnerWithSubstitutions[from][_tokensOfOwnerWithSubstitutions[from].length - 1]; // Do tokens of owner substitution if (lastNft == 0) { // assert(from == address(0) || from == address(this)); lastNft = _tokensOfOwnerWithSubstitutions[from].length; // - 1 + 1 } _tokensOfOwnerWithSubstitutions[from][indexToDelete] = lastNft; _ownedTokensIndexWithSubstitutions[lastNft] = indexToDelete + 1; } // Next line also deletes the contents at the last position of the array (gas refund) _tokensOfOwnerWithSubstitutions[from].length--; // Right now _ownedTokensIndexWithSubstitutions[_tokenId] is invalid, set it below based on the new owner // Give to the TO address _tokensOfOwnerWithSubstitutions[_to].push(_tokenId); _ownedTokensIndexWithSubstitutions[_tokenId] = (_tokensOfOwnerWithSubstitutions[_to].length - 1) + 1; // External processing _tokenOwnerWithSubstitutions[_tokenId] = _to; tokenApprovals[_tokenId] = address(0); emit Transfer(from, _to, _tokenId); } // PRIVATE STORAGE AND FUNCTIONS /////////////////////////////////////////// // See Solidity issue #3356, it would be clearer to initialize in SuMain uint256 private constant TOTAL_SUPPLY = 1001; bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); /// @dev The owner of each NFT /// If value == address(0), NFT is owned by address(this) /// If value != address(0), NFT is owned by value /// assert(This contract never assigns ownership to address(0) or destroys NFTs) /// See commented out code in constructor, saves hella gas /// In other words address(0) in storage means address(this) outside mapping (uint256 => address) private _tokenOwnerWithSubstitutions; /// @dev The list of NFTs owned by each address /// Nomenclature: arr[key][index] = value /// If key != address(this) or value != 0, then value represents an NFT /// If key == address(this) and value == 0, then index + 1 is the NFT /// assert(0 is not a valid NFT) /// See commented out code in constructor, saves hella gas /// In other words [0, 0, a, 0] is equivalent to [1, 2, a, 4] for address(this) mapping (address => uint256[]) private _tokensOfOwnerWithSubstitutions; /// @dev (Location + 1) of each NFT in its owner's list /// Nomenclature: arr[nftId] = value /// If value != 0, _tokensOfOwnerWithSubstitutions[owner][value - 1] = nftId /// If value == 0, _tokensOfOwnerWithSubstitutions[owner][nftId - 1] = nftId /// assert(2**256-1 is not a valid NFT) /// See commented out code in constructor, saves hella gas /// In other words mapping {a=>a} is equivalent to {a=>0} mapping (uint256 => uint256) private _ownedTokensIndexWithSubstitutions; // Due to implementation choices (no mint, no burn, contiguous NFT ids), it // is not necessary to keep an array of NFT ids nor where each NFT id is // located in that array. // address[] private nftIds; // mapping (uint256 => uint256) private nftIndexOfId; constructor() internal { // Publish interfaces with ERC-165 supportedInterfaces[0x80ac58cd] = true; // ERC721 supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable supportedInterfaces[0x8153916a] = true; // ERC721 + 165 (not needed) // The effect of substitution makes storing address(this), address(this) // ..., address(this) for a total of TOTAL_SUPPLY times unnecessary at // deployment time // for (uint256 i = 1; i <= TOTAL_SUPPLY; i++) { // _tokenOwnerWithSubstitutions[i] = address(this); // } // The effect of substitution makes storing 1, 2, ..., TOTAL_SUPPLY // unnecessary at deployment time _tokensOfOwnerWithSubstitutions[address(this)].length = TOTAL_SUPPLY; // for (uint256 i = 0; i < TOTAL_SUPPLY; i++) { // _tokensOfOwnerWithSubstitutions[address(this)][i] = i + 1; // } // for (uint256 i = 1; i <= TOTAL_SUPPLY; i++) { // _ownedTokensIndexWithSubstitutions[i] = i - 1; // } } /// @dev Actually perform the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) private mustBeValidToken(_tokenId) canTransfer(_tokenId) { address owner = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (owner == address(0)) { owner = address(this); } require(owner == _from); require(_to != address(0)); _transfer(_tokenId, _to); // Do the callback after everything is done to avoid reentrancy attack uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, data); require(retval == ERC721_RECEIVED); } }
14,677
2
// This event will track when someone sends some tokens.
event Sent(address from, address to, uint amount); event Mint(uint amount);
event Sent(address from, address to, uint amount); event Mint(uint amount);
42,234
8
// 1.StakerAddress is indeed a staker
require(isStakedOnLatestConfirmed(stakerAddress), "NOT_STAKED");
require(isStakedOnLatestConfirmed(stakerAddress), "NOT_STAKED");
33,711
74
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
result := mload(xor(0x60, returndatasize()))
21,283
1
// 'balance' function will simply return the amount currently held in escrow
function balance() public view returns (uint) { return address(this).balance; }
function balance() public view returns (uint) { return address(this).balance; }
13,267
17
// transfer input currency from sender (client) to the pair token pool (contract)
InputToken.transferFrom(msg.sender, poolTokenTo, inputCurrency);
InputToken.transferFrom(msg.sender, poolTokenTo, inputCurrency);
40,626
34
// if a via cash token is paid into this bond contract
else{
else{
26,090
15
// descending diagonal check
for (i = 3; i < 7; i++) { for (j = 3; j < 6; j++) { if (grid[i][j] == player && grid[i-1][j-1] == player && grid[i-2][j-2] == player && grid[i-3][j-3] == player) return true; }
for (i = 3; i < 7; i++) { for (j = 3; j < 6; j++) { if (grid[i][j] == player && grid[i-1][j-1] == player && grid[i-2][j-2] == player && grid[i-3][j-3] == player) return true; }
47,314
0
// Creates the DutchAuction contract.//_sellerAddress Address of the seller./_judgeAddress Address of the judge./_timer Timer reference/_initialPrice Start price of dutch auction./_biddingPeriod Number of time units this auction lasts./_priceDecrement Rate at which price is lowered for each time unit/following linear decay rule.
constructor( address _sellerAddress, address _judgeAddress, Timer _timer, uint _initialPrice, uint _biddingPeriod, uint _priceDecrement
constructor( address _sellerAddress, address _judgeAddress, Timer _timer, uint _initialPrice, uint _biddingPeriod, uint _priceDecrement
19,929
1
// Call function in ProjectCreator to update values
if(p.checkLimit(donation,admin,index) == false){ revert('Limt crossed/Invalid Amount');
if(p.checkLimit(donation,admin,index) == false){ revert('Limt crossed/Invalid Amount');
7,992
114
// The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 public immutable domainSeparator; uint256 internal constant MAX_UINT_VALUE = uint256(-1); mapping(address => uint256) public nonces; event Deposit(address indexed owner, uint256 shares, uint256 amount); event Withdraw(address indexed owner, uint256 shares, uint256 amount);
bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 public immutable domainSeparator; uint256 internal constant MAX_UINT_VALUE = uint256(-1); mapping(address => uint256) public nonces; event Deposit(address indexed owner, uint256 shares, uint256 amount); event Withdraw(address indexed owner, uint256 shares, uint256 amount);
42,609
83
// Shh -- currently unused
data;
data;
950
22
// Counter underflow is impossible as _burnCounter cannot be incremented more than `_currentIndex - _startTokenId()` times.
unchecked { return _currentIndex - _burnCounter - _startTokenId(); }
unchecked { return _currentIndex - _burnCounter - _startTokenId(); }
23,295
31
// used for ending the bidding period of a particular auction auctionID id of auction for which bidding period is to be stopped /
function endBiddingTime(uint auctionID) public { bool found = false; for(uint i = 0; i < ownerOfAuctions[msg.sender].length; i++) { if(ownerOfAuctions[msg.sender][i].auctionID == auctionID) { found = true; break; } } require(found == true, "You are not the owner of this auction"); require(auctionStatus[auctionID] == AuctionState.RUNNING, "Bidding has not started or has already ended"); auctionStatus[auctionID] = AuctionState.REVEAL_TIME; }
function endBiddingTime(uint auctionID) public { bool found = false; for(uint i = 0; i < ownerOfAuctions[msg.sender].length; i++) { if(ownerOfAuctions[msg.sender][i].auctionID == auctionID) { found = true; break; } } require(found == true, "You are not the owner of this auction"); require(auctionStatus[auctionID] == AuctionState.RUNNING, "Bidding has not started or has already ended"); auctionStatus[auctionID] = AuctionState.REVEAL_TIME; }
36,311
61
// Gets the current balance of the account provided. /
function getBalance( address _account ) public view returns (uint)
function getBalance( address _account ) public view returns (uint)
45,407
114
// From this moment `getPendingValidators()` returns the new validator set
_clearReportingCounter(_miningAddresses[i]); removed = true;
_clearReportingCounter(_miningAddresses[i]); removed = true;
7,554
119
// withdraw spaceport tokens percentile withdrawls allows fee on transfer or rebasing tokens to still work
function userWithdrawTokens () external nonReentrant { require(STATUS.LP_GENERATION_COMPLETE, 'AWAITING LP GENERATION'); BuyerInfo storage buyer = BUYERS[msg.sender]; require(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingCliff < block.timestamp, "vesting cliff : not time yet"); if (buyer.lastUpdate < STATUS.LP_GENERATION_COMPLETE_TIME ) { buyer.lastUpdate = STATUS.LP_GENERATION_COMPLETE_TIME; } uint256 tokensOwed = 0; if(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingEnd < block.timestamp) { tokensOwed = buyer.tokensOwed.sub(buyer.tokensClaimed); } else { tokensOwed = buyer.tokensOwed.mul(block.timestamp - buyer.lastUpdate).div(SPACEPORT_VESTING.vestingEnd); } buyer.lastUpdate = block.timestamp; buyer.tokensClaimed = buyer.tokensClaimed.add(tokensOwed); require(tokensOwed > 0, 'NOTHING TO CLAIM'); require(buyer.tokensClaimed <= buyer.tokensOwed, 'CLAIM TOKENS ERROR'); STATUS.TOTAL_TOKENS_WITHDRAWN = STATUS.TOTAL_TOKENS_WITHDRAWN.add(tokensOwed); TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), msg.sender, tokensOwed); emit spaceportUserWithdrawTokens(tokensOwed); }
function userWithdrawTokens () external nonReentrant { require(STATUS.LP_GENERATION_COMPLETE, 'AWAITING LP GENERATION'); BuyerInfo storage buyer = BUYERS[msg.sender]; require(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingCliff < block.timestamp, "vesting cliff : not time yet"); if (buyer.lastUpdate < STATUS.LP_GENERATION_COMPLETE_TIME ) { buyer.lastUpdate = STATUS.LP_GENERATION_COMPLETE_TIME; } uint256 tokensOwed = 0; if(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingEnd < block.timestamp) { tokensOwed = buyer.tokensOwed.sub(buyer.tokensClaimed); } else { tokensOwed = buyer.tokensOwed.mul(block.timestamp - buyer.lastUpdate).div(SPACEPORT_VESTING.vestingEnd); } buyer.lastUpdate = block.timestamp; buyer.tokensClaimed = buyer.tokensClaimed.add(tokensOwed); require(tokensOwed > 0, 'NOTHING TO CLAIM'); require(buyer.tokensClaimed <= buyer.tokensOwed, 'CLAIM TOKENS ERROR'); STATUS.TOTAL_TOKENS_WITHDRAWN = STATUS.TOTAL_TOKENS_WITHDRAWN.add(tokensOwed); TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), msg.sender, tokensOwed); emit spaceportUserWithdrawTokens(tokensOwed); }
59,791
32
// Transfer WETH from user.
_weth.transferFrom(msg.sender, address(this), amountIn);
_weth.transferFrom(msg.sender, address(this), amountIn);
35,600
14
// Delegate execution to implementation contract provided by upgrade beacon.
_delegate(_implementation());
_delegate(_implementation());
49,659