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
62
// WADTOKEN STARTS HERE /
contract WADCoin is Owned, TokenERC20 { using SafeMath for uint256; uint256 public sellPrice; uint256 public buyPrice; address public migrationAgent; uint256 public totalMigrated; address public migrationMaster; mapping(address => bytes32[]) public lockReason; mapping(address => mapping(bytes32 => lockToken)) public locked; struct lockToken { uint256 amount; uint256 validity; } // event Lock( // address indexed _of, // bytes32 indexed _reason, // uint256 _amount, // uint256 _validity // ); /* This generates a public event on the blockchain that will notify clients */ event Migrate(address indexed _from, address indexed _to, uint256 _value); /* Initializes contract with initial supply tokens to the creator of the contract */ // function MyAdvancedToken( function WADCoin( uint256 _initialSupply) TokenERC20(_initialSupply) public { // initialSupply = _initialSupply; // tokenName = _tokenName; // tokenSymbol = _tokenSymbol; } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(transferableBalanceOf(_from) >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time */ function lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) onlyOwner public returns (bool) { uint256 validUntil = block.timestamp.add(_time); // If tokens are already locked, the functions extendLock or // increaseLockAmount should be used to make any changes //require(tokensLocked(_of, _reason, block.timestamp) == 0); require(_amount <= transferableBalanceOf(_of)); if (locked[_of][_reason].amount == 0) lockReason[_of].push(_reason); if(tokensLocked(_of, _reason, block.timestamp) == 0){ locked[_of][_reason] = lockToken(_amount, validUntil); }else{ locked[_of][_reason].amount += _amount; } //emit Lock(_of, _reason, _amount, validUntil); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool) { require(tokensLocked(msg.sender, _reason, block.timestamp) > 0); locked[msg.sender][_reason].validity += _time; // emit Lock(msg.sender, _reason, locked[msg.sender][_reason].amount, locked[msg.sender][_reason].validity); return true; } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specified time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) amount = locked[_of][_reason].amount; } function transferableBalanceOf(address _of) public view returns (uint256 amount) { uint256 lockedAmount = 0; for (uint256 i=0; i < lockReason[_of].length; i++) { lockedAmount += tokensLocked(_of,lockReason[_of][i], block.timestamp); } // amount = balances[_of].sub(lockedAmount); amount = balanceOf[_of].sub(lockedAmount); return amount; } /// @notice Set address of migration target contract and enable migration /// process. /// @dev Required state: Operational Normal /// @dev State transition: -> Operational Migration /// @param _agent The address of the MigrationAgent contract function setMigrationAgent(address _agent) external { // Abort if not in Operational Normal state. if (migrationAgent != 0) throw; if (msg.sender != migrationMaster) throw; migrationAgent = _agent; } function setMigrationMaster(address _master) external { if (msg.sender != migrationMaster) throw; if (_master == 0) throw; migrationMaster = _master; } }
contract WADCoin is Owned, TokenERC20 { using SafeMath for uint256; uint256 public sellPrice; uint256 public buyPrice; address public migrationAgent; uint256 public totalMigrated; address public migrationMaster; mapping(address => bytes32[]) public lockReason; mapping(address => mapping(bytes32 => lockToken)) public locked; struct lockToken { uint256 amount; uint256 validity; } // event Lock( // address indexed _of, // bytes32 indexed _reason, // uint256 _amount, // uint256 _validity // ); /* This generates a public event on the blockchain that will notify clients */ event Migrate(address indexed _from, address indexed _to, uint256 _value); /* Initializes contract with initial supply tokens to the creator of the contract */ // function MyAdvancedToken( function WADCoin( uint256 _initialSupply) TokenERC20(_initialSupply) public { // initialSupply = _initialSupply; // tokenName = _tokenName; // tokenSymbol = _tokenSymbol; } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(transferableBalanceOf(_from) >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time */ function lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) onlyOwner public returns (bool) { uint256 validUntil = block.timestamp.add(_time); // If tokens are already locked, the functions extendLock or // increaseLockAmount should be used to make any changes //require(tokensLocked(_of, _reason, block.timestamp) == 0); require(_amount <= transferableBalanceOf(_of)); if (locked[_of][_reason].amount == 0) lockReason[_of].push(_reason); if(tokensLocked(_of, _reason, block.timestamp) == 0){ locked[_of][_reason] = lockToken(_amount, validUntil); }else{ locked[_of][_reason].amount += _amount; } //emit Lock(_of, _reason, _amount, validUntil); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool) { require(tokensLocked(msg.sender, _reason, block.timestamp) > 0); locked[msg.sender][_reason].validity += _time; // emit Lock(msg.sender, _reason, locked[msg.sender][_reason].amount, locked[msg.sender][_reason].validity); return true; } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specified time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) amount = locked[_of][_reason].amount; } function transferableBalanceOf(address _of) public view returns (uint256 amount) { uint256 lockedAmount = 0; for (uint256 i=0; i < lockReason[_of].length; i++) { lockedAmount += tokensLocked(_of,lockReason[_of][i], block.timestamp); } // amount = balances[_of].sub(lockedAmount); amount = balanceOf[_of].sub(lockedAmount); return amount; } /// @notice Set address of migration target contract and enable migration /// process. /// @dev Required state: Operational Normal /// @dev State transition: -> Operational Migration /// @param _agent The address of the MigrationAgent contract function setMigrationAgent(address _agent) external { // Abort if not in Operational Normal state. if (migrationAgent != 0) throw; if (msg.sender != migrationMaster) throw; migrationAgent = _agent; } function setMigrationMaster(address _master) external { if (msg.sender != migrationMaster) throw; if (_master == 0) throw; migrationMaster = _master; } }
15,948
32
// adding the collected taxes to the Tax Pool
AddTaxToPool(tax / 2);
AddTaxToPool(tax / 2);
28,547
17
// Error codes
uint constant ERR_INVALID_HEADER = 10050; uint constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Litecoin merkle isn't 0 uint constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined uint constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice uint constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found uint constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root isn't in the first 20 bytes of coinbase tx uint constant ERR_CHAIN_MERKLE = 10110; uint constant ERR_PARENT_MERKLE = 10120; uint constant ERR_PROOF_OF_WORK = 10130; uint constant ERR_INVALID_HEADER_HASH = 10140;
uint constant ERR_INVALID_HEADER = 10050; uint constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Litecoin merkle isn't 0 uint constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined uint constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice uint constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found uint constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root isn't in the first 20 bytes of coinbase tx uint constant ERR_CHAIN_MERKLE = 10110; uint constant ERR_PARENT_MERKLE = 10120; uint constant ERR_PROOF_OF_WORK = 10130; uint constant ERR_INVALID_HEADER_HASH = 10140;
2,978
87
// accrue and returns accrued stored of msg.sender /
function accrue() external returns (uint) { accrueInternal(); (, uint instantAccountAccruedAmount) = accruedStoredInternal(msg.sender, globalAccruedIndex); return instantAccountAccruedAmount; }
function accrue() external returns (uint) { accrueInternal(); (, uint instantAccountAccruedAmount) = accruedStoredInternal(msg.sender, globalAccruedIndex); return instantAccountAccruedAmount; }
18,862
26
// Namespace for the structs used in {SablierV2LockupLinear}./Struct encapsulating the parameters for the {SablierV2LockupLinear.createWithDurations} function./sender The address streaming the assets, with the ability to cancel the stream. It doesn't have to be the/ same as `msg.sender`./recipient The address receiving the assets./totalAmount The total amount of ERC-20 assets to be paid, including the stream deposit and any potential/ fees, all denoted in units of the asset's decimals./asset The contract address of the ERC-20 asset used for streaming./cancelable Indicates if the stream is cancelable./durations Struct containing (i) cliff period duration and (ii) total stream duration, both in seconds./broker Struct containing (i) the address
struct CreateWithDurations { address sender; address recipient; uint128 totalAmount; IERC20 asset; bool cancelable; Durations durations; Broker broker; }
struct CreateWithDurations { address sender; address recipient; uint128 totalAmount; IERC20 asset; bool cancelable; Durations durations; Broker broker; }
31,348
21
// Returns last time pool was paid
function getLastPaid(address asset) external view returns (uint256) { return lastPaid[asset]; }
function getLastPaid(address asset) external view returns (uint256) { return lastPaid[asset]; }
6,964
94
// Emits an {Approval} event. Requirements: - `user` cannot be the zero address.- `spender` cannot be the zero address. /
function _approve( address user, address spender, uint256 amount ) internal virtual { require(user != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[user][spender] = amount; emit Approval(user, spender, amount);
function _approve( address user, address spender, uint256 amount ) internal virtual { require(user != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[user][spender] = amount; emit Approval(user, spender, amount);
35,869
4
// Variables to manage the business logic of this contract
address private _creators; address private _marketing; uint256 private _poolForActors; uint256 private _poolForHolders; using EnumerableSet for EnumerableSet.AddressSet; address[] private _actors; EnumerableSet.AddressSet private _holders;
address private _creators; address private _marketing; uint256 private _poolForActors; uint256 private _poolForHolders; using EnumerableSet for EnumerableSet.AddressSet; address[] private _actors; EnumerableSet.AddressSet private _holders;
13,382
186
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
result = previousResult.mul(a);
7,066
26
// 查询商品
function getCommodity(uint256 _tokenId) external view returns (Commodity memory commodity)
function getCommodity(uint256 _tokenId) external view returns (Commodity memory commodity)
30,653
427
// If we have an unprocessed pending deposit from the previous rounds, we have to process it.
uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); uint256 depositAmount = amount;
uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); uint256 depositAmount = amount;
51,760
58
// Create a new rollup l1 user transaction babyPubKey Public key babyjubjub represented as point: sign + (Ay) fromIdx Index leaf of sender account or 0 if create new account loadAmountF Amount from L1 to L2 to sender account or new account amountF Amount transfered between L2 accounts tokenID Token identifier toIdx Index leaf of recipient account, or _EXIT_IDX if exit, or 0 if not transferEvents: `L1UserTxEvent` /
function addL1Transaction( uint256 babyPubKey, uint48 fromIdx, uint40 loadAmountF, uint40 amountF, uint32 tokenID, uint48 toIdx, bytes calldata permit
function addL1Transaction( uint256 babyPubKey, uint48 fromIdx, uint40 loadAmountF, uint40 amountF, uint32 tokenID, uint48 toIdx, bytes calldata permit
3,624
9
// reference to $avaWOOL for burning on mint
WOOL public wool;
WOOL public wool;
27,847
163
// emit event upon deploying new token
emit TokenDeployed(_tokenId.domain(), _tokenId.id(), _token);
emit TokenDeployed(_tokenId.domain(), _tokenId.id(), _token);
22,336
13
// message unnecessarily. For custom revert reasons use {tryDiv}. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. /
function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; }
function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; }
7,944
28
// get pool
function getPool(uint256 _pool) public view returns(address) { return pools[_pool].token; }
function getPool(uint256 _pool) public view returns(address) { return pools[_pool].token; }
13,817
179
// max supply
uint256 public constant MAX_TOKENS = 10000;
uint256 public constant MAX_TOKENS = 10000;
6,484
67
// Save locked accounts and rewards.
lockBalanceOf[msg.sender] += _lockValue + _reward; _calcRemainReward();
lockBalanceOf[msg.sender] += _lockValue + _reward; _calcRemainReward();
70,608
57
// check staking amount
function checkStakingAmount(address user) public view returns (uint256) { Stake storage _stake = addressToStakeMap[user]; return _stake.amount; }
function checkStakingAmount(address user) public view returns (uint256) { Stake storage _stake = addressToStakeMap[user]; return _stake.amount; }
41,616
111
// Execute the withdraw effects
_redeem(_totalAsset, _amountToReturn.toUint128(), _shares.toUint128(), _receiver, _owner);
_redeem(_totalAsset, _amountToReturn.toUint128(), _shares.toUint128(), _receiver, _owner);
38,247
30
// Get the virtual price, to help calculate profit self Swap struct to read fromreturn the virtual price, scaled to precision of Constants.POOL_PRECISION_DECIMALS /
function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply != 0) { return (d * (10**uint256(Constants.POOL_PRECISION_DECIMALS))) / supply; } return 0; }
function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply != 0) { return (d * (10**uint256(Constants.POOL_PRECISION_DECIMALS))) / supply; } return 0; }
20,996
47
// Allocate the memory.
mstore(0x40, str)
mstore(0x40, str)
31,824
0
// deploy smart contract, toggle WL, toggle WL when done, toggle publicSale 7 days later toggle reveal
bool public isRevealed; bool public publicSale; bool public whiteListSale; bool public pause; bool public teamMinted; bytes32 private merkleRoot; mapping(address => uint256) public totalPublicMint;
bool public isRevealed; bool public publicSale; bool public whiteListSale; bool public pause; bool public teamMinted; bytes32 private merkleRoot; mapping(address => uint256) public totalPublicMint;
12,104
163
// Get debt, currentValue (want+idle), only want
uint256 debt = vault.strategies(address(this)).totalDebt; uint256 currentValue = estimatedTotalAssets(); uint256 wantBalance = balanceOfWant();
uint256 debt = vault.strategies(address(this)).totalDebt; uint256 currentValue = estimatedTotalAssets(); uint256 wantBalance = balanceOfWant();
22,008
138
// Streamr Marketplace note about numbers:All prices and exchange rates are in "decimal fixed-point", that is, scaled by 10^18, like ETH vs wei. Seconds are integers as usual. Next version TODO: - EIP-165 inferface definition; PurchaseListener /
contract Marketplace is Ownable, IMarketplace2 { using SafeMath for uint256; // product events event ProductCreated(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductUpdated(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductDeleted(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductImported(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductRedeployed(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductOwnershipOffered(address indexed owner, bytes32 indexed id, address indexed to); event ProductOwnershipChanged(address indexed newOwner, bytes32 indexed id, address indexed oldOwner); // subscription events event Subscribed(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event NewSubscription(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionExtended(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionImported(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionTransferred(bytes32 indexed productId, address indexed from, address indexed to, uint secondsTransferred); // currency events event ExchangeRatesUpdated(uint timestamp, uint dataInUsd); // whitelist events event WhitelistRequested(bytes32 indexed productId, address indexed subscriber); event WhitelistApproved(bytes32 indexed productId, address indexed subscriber); event WhitelistRejected(bytes32 indexed productId, address indexed subscriber); event WhitelistEnabled(bytes32 indexed productId); event WhitelistDisabled(bytes32 indexed productId); //txFee events event TxFeeChanged(uint256 indexed newTxFee); struct Product { bytes32 id; string name; address owner; address beneficiary; // account where revenue is directed to uint pricePerSecond; Currency priceCurrency; uint minimumSubscriptionSeconds; ProductState state; address newOwnerCandidate; // Two phase hand-over to minimize the chance that the product ownership is lost to a non-existent address. bool requiresWhitelist; mapping(address => TimeBasedSubscription) subscriptions; mapping(address => WhitelistState) whitelist; } struct TimeBasedSubscription { uint endTimestamp; } /////////////// Marketplace lifecycle ///////////////// ERC20 public datacoin; address public currencyUpdateAgent; IMarketplace1 prev_marketplace; uint256 public txFee; constructor(address datacoinAddress, address currencyUpdateAgentAddress, address prev_marketplace_address) Ownable() public { _initialize(datacoinAddress, currencyUpdateAgentAddress, prev_marketplace_address); } function _initialize(address datacoinAddress, address currencyUpdateAgentAddress, address prev_marketplace_address) internal { currencyUpdateAgent = currencyUpdateAgentAddress; datacoin = ERC20(datacoinAddress); prev_marketplace = IMarketplace1(prev_marketplace_address); } ////////////////// Product management ///////////////// mapping (bytes32 => Product) public products; /* checks this marketplace first, then the previous */ function getProduct(bytes32 id) public override view returns (string memory name, address owner, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, ProductState state, bool requiresWhitelist) { (name, owner, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, state, requiresWhitelist) = _getProductLocal(id); if (owner != address(0)) return (name, owner, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, state, requiresWhitelist); (name, owner, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, state) = prev_marketplace.getProduct(id); return (name, owner, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, state, false); } /** checks only this marketplace, not the previous marketplace */ function _getProductLocal(bytes32 id) internal view returns (string memory name, address owner, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, ProductState state, bool requiresWhitelist) { Product memory p = products[id]; return ( p.name, p.owner, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds, p.state, p.requiresWhitelist ); } // also checks that p exists: p.owner == 0 for non-existent products modifier onlyProductOwner(bytes32 productId) { (,address _owner,,,,,,) = getProduct(productId); require(_owner != address(0), "error_notFound"); require(_owner == msg.sender || owner == msg.sender, "error_productOwnersOnly"); _; } /** * Imports product details (but NOT subscription details) from previous marketplace */ function _importProductIfNeeded(bytes32 productId) internal returns (bool imported){ Product storage p = products[productId]; if (p.id != 0x0) { return false; } (string memory _name, address _owner, address _beneficiary, uint _pricePerSecond, IMarketplace1.Currency _priceCurrency, uint _minimumSubscriptionSeconds, IMarketplace1.ProductState _state) = prev_marketplace.getProduct(productId); if (_owner == address(0)) { return false; } p.id = productId; p.name = _name; p.owner = _owner; p.beneficiary = _beneficiary; p.pricePerSecond = _pricePerSecond; p.priceCurrency = _priceCurrency; p.minimumSubscriptionSeconds = _minimumSubscriptionSeconds; p.state = _state; emit ProductImported(p.owner, p.id, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); return true; } function _importSubscriptionIfNeeded(bytes32 productId, address subscriber) internal returns (bool imported) { bool _productImported = _importProductIfNeeded(productId); // check that subscription didn't already exist in current marketplace (Product storage product, TimeBasedSubscription storage sub) = _getSubscriptionLocal(productId, subscriber); if (sub.endTimestamp != 0x0) { return false; } // check that subscription exists in the previous marketplace(s) // only call prev_marketplace.getSubscription() if product exists there // consider e.g. product created in current marketplace but subscription still doesn't exist // if _productImported, it must have existed in previous marketplace so no need to perform check if (!_productImported) { (,address _owner_prev,,,,,) = prev_marketplace.getProduct(productId); if (_owner_prev == address(0)) { return false; } } (, uint _endTimestamp) = prev_marketplace.getSubscription(productId, subscriber); if (_endTimestamp == 0x0) { return false; } product.subscriptions[subscriber] = TimeBasedSubscription(_endTimestamp); emit SubscriptionImported(productId, subscriber, _endTimestamp); return true; } function createProduct(bytes32 id, string memory name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds) public whenNotHalted { _createProduct(id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, false); } function createProductWithWhitelist(bytes32 id, string memory name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds) public whenNotHalted { _createProduct(id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, true); emit WhitelistEnabled(id); } function _createProduct(bytes32 id, string memory name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, bool requiresWhitelist) internal { require(id != 0x0, "error_nullProductId"); require(pricePerSecond > 0, "error_freeProductsNotSupported"); (,address _owner,,,,,,) = getProduct(id); require(_owner == address(0), "error_alreadyExists"); products[id] = Product({id: id, name: name, owner: msg.sender, beneficiary: beneficiary, pricePerSecond: pricePerSecond, priceCurrency: currency, minimumSubscriptionSeconds: minimumSubscriptionSeconds, state: ProductState.Deployed, newOwnerCandidate: address(0), requiresWhitelist: requiresWhitelist}); emit ProductCreated(msg.sender, id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds); } /** * Stop offering the product */ function deleteProduct(bytes32 productId) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.state == ProductState.Deployed, "error_notDeployed"); p.state = ProductState.NotDeployed; emit ProductDeleted(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); } /** * Return product to market */ function redeployProduct(bytes32 productId) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.state == ProductState.NotDeployed, "error_mustBeNotDeployed"); p.state = ProductState.Deployed; emit ProductRedeployed(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); } function updateProduct(bytes32 productId, string memory name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, bool redeploy) public onlyProductOwner(productId) { require(pricePerSecond > 0, "error_freeProductsNotSupported"); _importProductIfNeeded(productId); Product storage p = products[productId]; p.name = name; p.beneficiary = beneficiary; p.pricePerSecond = pricePerSecond; p.priceCurrency = currency; p.minimumSubscriptionSeconds = minimumSubscriptionSeconds; emit ProductUpdated(p.owner, p.id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds); if (redeploy) { redeployProduct(productId); } } /** * Changes ownership of the product. Two phase hand-over minimizes the chance that the product ownership is lost to a non-existent address. */ function offerProductOwnership(bytes32 productId, address newOwnerCandidate) public onlyProductOwner(productId) { _importProductIfNeeded(productId); // that productId exists is already checked in onlyProductOwner products[productId].newOwnerCandidate = newOwnerCandidate; emit ProductOwnershipOffered(products[productId].owner, productId, newOwnerCandidate); } /** * Changes ownership of the product. Two phase hand-over minimizes the chance that the product ownership is lost to a non-existent address. */ function claimProductOwnership(bytes32 productId) public whenNotHalted { _importProductIfNeeded(productId); // also checks that productId exists (newOwnerCandidate is zero for non-existent) Product storage p = products[productId]; require(msg.sender == p.newOwnerCandidate, "error_notPermitted"); emit ProductOwnershipChanged(msg.sender, productId, p.owner); p.owner = msg.sender; p.newOwnerCandidate = address(0); } /////////////// Whitelist management /////////////// function setRequiresWhitelist(bytes32 productId, bool _requiresWhitelist) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); p.requiresWhitelist = _requiresWhitelist; if (_requiresWhitelist) { emit WhitelistEnabled(productId); } else { emit WhitelistDisabled(productId); } } function whitelistApprove(bytes32 productId, address subscriber) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); require(p.requiresWhitelist, "error_whitelistNotEnabled"); p.whitelist[subscriber] = WhitelistState.Approved; emit WhitelistApproved(productId, subscriber); } function whitelistReject(bytes32 productId, address subscriber) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); require(p.requiresWhitelist, "error_whitelistNotEnabled"); p.whitelist[subscriber] = WhitelistState.Rejected; emit WhitelistRejected(productId, subscriber); } function whitelistRequest(bytes32 productId) public { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); require(p.requiresWhitelist, "error_whitelistNotEnabled"); require(p.whitelist[msg.sender] == WhitelistState.None, "error_whitelistRequestAlreadySubmitted"); p.whitelist[msg.sender] = WhitelistState.Pending; emit WhitelistRequested(productId, msg.sender); } function getWhitelistState(bytes32 productId, address subscriber) public view returns (WhitelistState wlstate) { (, address _owner,,,,,,) = getProduct(productId); require(_owner != address(0), "error_notFound"); // if product is not local (maybe in old marketplace) this will return 0 (WhitelistState.None) Product storage p = products[productId]; return p.whitelist[subscriber]; } /////////////// Subscription management /////////////// function getSubscription(bytes32 productId, address subscriber) public override view returns (bool isValid, uint endTimestamp) { (,address _owner,,,,,,) = _getProductLocal(productId); if (_owner == address(0)) { return prev_marketplace.getSubscription(productId,subscriber); } (, TimeBasedSubscription storage sub) = _getSubscriptionLocal(productId, subscriber); if (sub.endTimestamp == 0x0) { // only call prev_marketplace.getSubscription() if product exists in previous marketplace too (,address _owner_prev,,,,,) = prev_marketplace.getProduct(productId); if (_owner_prev != address(0)) { return prev_marketplace.getSubscription(productId,subscriber); } } return (_isValid(sub), sub.endTimestamp); } function getSubscriptionTo(bytes32 productId) public view returns (bool isValid, uint endTimestamp) { return getSubscription(productId, msg.sender); } /** * Checks if the given address currently has a valid subscription * @param productId to check * @param subscriber to check */ function hasValidSubscription(bytes32 productId, address subscriber) public view returns (bool isValid) { (isValid,) = getSubscription(productId, subscriber); } /** * Enforces payment rules, triggers PurchaseListener event */ function _subscribe(bytes32 productId, uint addSeconds, address subscriber, bool requirePayment) internal { _importSubscriptionIfNeeded(productId, subscriber); (Product storage p, TimeBasedSubscription storage oldSub) = _getSubscriptionLocal(productId, subscriber); require(p.state == ProductState.Deployed, "error_notDeployed"); require(!p.requiresWhitelist || p.whitelist[subscriber] == WhitelistState.Approved, "error_whitelistNotAllowed"); uint endTimestamp; if (oldSub.endTimestamp > block.timestamp) { require(addSeconds > 0, "error_topUpTooSmall"); endTimestamp = oldSub.endTimestamp.add(addSeconds); oldSub.endTimestamp = endTimestamp; emit SubscriptionExtended(p.id, subscriber, endTimestamp); } else { require(addSeconds >= p.minimumSubscriptionSeconds, "error_newSubscriptionTooSmall"); endTimestamp = block.timestamp.add(addSeconds); TimeBasedSubscription memory newSub = TimeBasedSubscription(endTimestamp); p.subscriptions[subscriber] = newSub; emit NewSubscription(p.id, subscriber, endTimestamp); } emit Subscribed(p.id, subscriber, endTimestamp); uint256 price = 0; uint256 fee = 0; address recipient = p.beneficiary; if (requirePayment) { price = getPriceInData(addSeconds, p.pricePerSecond, p.priceCurrency); fee = txFee.mul(price).div(1 ether); require(datacoin.transferFrom(msg.sender, recipient, price.sub(fee)), "error_paymentFailed"); if (fee > 0) { require(datacoin.transferFrom(msg.sender, owner, fee), "error_paymentFailed"); } } uint256 codeSize; assembly { codeSize := extcodesize(recipient) } // solhint-disable-line no-inline-assembly if (codeSize > 0) { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returnData) = recipient.call( abi.encodeWithSignature("onPurchase(bytes32,address,uint256,uint256,uint256)", productId, subscriber, oldSub.endTimestamp, price, fee) ); if (success) { (bool accepted) = abi.decode(returnData, (bool)); require(accepted, "error_rejectedBySeller"); } } } function grantSubscription(bytes32 productId, uint subscriptionSeconds, address recipient) public whenNotHalted onlyProductOwner(productId){ return _subscribe(productId, subscriptionSeconds, recipient, false); } function buyFor(bytes32 productId, uint subscriptionSeconds, address recipient) public override whenNotHalted { return _subscribe(productId, subscriptionSeconds, recipient, true); } /** * Purchases access to this stream for msg.sender. * If the address already has a valid subscription, extends the subscription by the given period. * @dev since v4.0: Notify the seller if the seller implements PurchaseListener interface */ function buy(bytes32 productId, uint subscriptionSeconds) public whenNotHalted { buyFor(productId,subscriptionSeconds, msg.sender); } /** Gets subscriptions info from the subscriptions stored in this contract */ function _getSubscriptionLocal(bytes32 productId, address subscriber) internal view returns (Product storage p, TimeBasedSubscription storage s) { p = products[productId]; require(p.id != 0x0, "error_notFound"); s = p.subscriptions[subscriber]; } function _isValid(TimeBasedSubscription storage s) internal view returns (bool) { return s.endTimestamp >= block.timestamp; // solhint-disable-line not-rely-on-time } // TODO: transfer allowance to another Marketplace contract // Mechanism basically is that this Marketplace draws from the allowance and credits // the account on another Marketplace; OR that there is a central credit pool (say, an ERC20 token) // Creating another ERC20 token for this could be a simple fix: it would need the ability to transfer allowances /////////////// Currency management /////////////// // Exchange rates are formatted as "decimal fixed-point", that is, scaled by 10^18, like ether. // Exponent: 10^18 15 12 9 6 3 0 // | | | | | | | uint public dataPerUsd = 100000000000000000; // ~= 0.1 DATA/USD /** * Update currency exchange rates; all purchases are still billed in DATAcoin * @param timestamp in seconds when the exchange rates were last updated * @param dataUsd how many data atoms (10^-18 DATA) equal one USD dollar */ function updateExchangeRates(uint timestamp, uint dataUsd) public { require(msg.sender == currencyUpdateAgent, "error_notPermitted"); require(dataUsd > 0, "error_invalidRate"); dataPerUsd = dataUsd; emit ExchangeRatesUpdated(timestamp, dataUsd); } /** * Helper function to calculate (hypothetical) subscription cost for given seconds and price, using current exchange rates. * @param subscriptionSeconds length of hypothetical subscription, as a non-scaled integer * @param price nominal price scaled by 10^18 ("token wei" or "attodollars") * @param unit unit of the number price */ function getPriceInData(uint subscriptionSeconds, uint price, Currency unit) public override view returns (uint datacoinAmount) { if (unit == Currency.DATA) { return price.mul(subscriptionSeconds); } return price.mul(dataPerUsd).mul(subscriptionSeconds).div(10**18); } /////////////// Admin functionality /////////////// event Halted(); event Resumed(); bool public halted = false; modifier whenNotHalted() { require(!halted || owner == msg.sender, "error_halted"); _; } function halt() public onlyOwner { halted = true; emit Halted(); } function resume() public onlyOwner { halted = false; emit Resumed(); } function reInitialize(address datacoinAddress, address currencyUpdateAgentAddress, address prev_marketplace_address) public onlyOwner { _initialize(datacoinAddress, currencyUpdateAgentAddress, prev_marketplace_address); } function setTxFee(uint256 newTxFee) public onlyOwner { require(newTxFee <= 1 ether, "error_invalidTxFee"); txFee = newTxFee; emit TxFeeChanged(txFee); } }
contract Marketplace is Ownable, IMarketplace2 { using SafeMath for uint256; // product events event ProductCreated(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductUpdated(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductDeleted(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductImported(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductRedeployed(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductOwnershipOffered(address indexed owner, bytes32 indexed id, address indexed to); event ProductOwnershipChanged(address indexed newOwner, bytes32 indexed id, address indexed oldOwner); // subscription events event Subscribed(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event NewSubscription(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionExtended(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionImported(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionTransferred(bytes32 indexed productId, address indexed from, address indexed to, uint secondsTransferred); // currency events event ExchangeRatesUpdated(uint timestamp, uint dataInUsd); // whitelist events event WhitelistRequested(bytes32 indexed productId, address indexed subscriber); event WhitelistApproved(bytes32 indexed productId, address indexed subscriber); event WhitelistRejected(bytes32 indexed productId, address indexed subscriber); event WhitelistEnabled(bytes32 indexed productId); event WhitelistDisabled(bytes32 indexed productId); //txFee events event TxFeeChanged(uint256 indexed newTxFee); struct Product { bytes32 id; string name; address owner; address beneficiary; // account where revenue is directed to uint pricePerSecond; Currency priceCurrency; uint minimumSubscriptionSeconds; ProductState state; address newOwnerCandidate; // Two phase hand-over to minimize the chance that the product ownership is lost to a non-existent address. bool requiresWhitelist; mapping(address => TimeBasedSubscription) subscriptions; mapping(address => WhitelistState) whitelist; } struct TimeBasedSubscription { uint endTimestamp; } /////////////// Marketplace lifecycle ///////////////// ERC20 public datacoin; address public currencyUpdateAgent; IMarketplace1 prev_marketplace; uint256 public txFee; constructor(address datacoinAddress, address currencyUpdateAgentAddress, address prev_marketplace_address) Ownable() public { _initialize(datacoinAddress, currencyUpdateAgentAddress, prev_marketplace_address); } function _initialize(address datacoinAddress, address currencyUpdateAgentAddress, address prev_marketplace_address) internal { currencyUpdateAgent = currencyUpdateAgentAddress; datacoin = ERC20(datacoinAddress); prev_marketplace = IMarketplace1(prev_marketplace_address); } ////////////////// Product management ///////////////// mapping (bytes32 => Product) public products; /* checks this marketplace first, then the previous */ function getProduct(bytes32 id) public override view returns (string memory name, address owner, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, ProductState state, bool requiresWhitelist) { (name, owner, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, state, requiresWhitelist) = _getProductLocal(id); if (owner != address(0)) return (name, owner, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, state, requiresWhitelist); (name, owner, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, state) = prev_marketplace.getProduct(id); return (name, owner, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, state, false); } /** checks only this marketplace, not the previous marketplace */ function _getProductLocal(bytes32 id) internal view returns (string memory name, address owner, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, ProductState state, bool requiresWhitelist) { Product memory p = products[id]; return ( p.name, p.owner, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds, p.state, p.requiresWhitelist ); } // also checks that p exists: p.owner == 0 for non-existent products modifier onlyProductOwner(bytes32 productId) { (,address _owner,,,,,,) = getProduct(productId); require(_owner != address(0), "error_notFound"); require(_owner == msg.sender || owner == msg.sender, "error_productOwnersOnly"); _; } /** * Imports product details (but NOT subscription details) from previous marketplace */ function _importProductIfNeeded(bytes32 productId) internal returns (bool imported){ Product storage p = products[productId]; if (p.id != 0x0) { return false; } (string memory _name, address _owner, address _beneficiary, uint _pricePerSecond, IMarketplace1.Currency _priceCurrency, uint _minimumSubscriptionSeconds, IMarketplace1.ProductState _state) = prev_marketplace.getProduct(productId); if (_owner == address(0)) { return false; } p.id = productId; p.name = _name; p.owner = _owner; p.beneficiary = _beneficiary; p.pricePerSecond = _pricePerSecond; p.priceCurrency = _priceCurrency; p.minimumSubscriptionSeconds = _minimumSubscriptionSeconds; p.state = _state; emit ProductImported(p.owner, p.id, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); return true; } function _importSubscriptionIfNeeded(bytes32 productId, address subscriber) internal returns (bool imported) { bool _productImported = _importProductIfNeeded(productId); // check that subscription didn't already exist in current marketplace (Product storage product, TimeBasedSubscription storage sub) = _getSubscriptionLocal(productId, subscriber); if (sub.endTimestamp != 0x0) { return false; } // check that subscription exists in the previous marketplace(s) // only call prev_marketplace.getSubscription() if product exists there // consider e.g. product created in current marketplace but subscription still doesn't exist // if _productImported, it must have existed in previous marketplace so no need to perform check if (!_productImported) { (,address _owner_prev,,,,,) = prev_marketplace.getProduct(productId); if (_owner_prev == address(0)) { return false; } } (, uint _endTimestamp) = prev_marketplace.getSubscription(productId, subscriber); if (_endTimestamp == 0x0) { return false; } product.subscriptions[subscriber] = TimeBasedSubscription(_endTimestamp); emit SubscriptionImported(productId, subscriber, _endTimestamp); return true; } function createProduct(bytes32 id, string memory name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds) public whenNotHalted { _createProduct(id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, false); } function createProductWithWhitelist(bytes32 id, string memory name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds) public whenNotHalted { _createProduct(id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, true); emit WhitelistEnabled(id); } function _createProduct(bytes32 id, string memory name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, bool requiresWhitelist) internal { require(id != 0x0, "error_nullProductId"); require(pricePerSecond > 0, "error_freeProductsNotSupported"); (,address _owner,,,,,,) = getProduct(id); require(_owner == address(0), "error_alreadyExists"); products[id] = Product({id: id, name: name, owner: msg.sender, beneficiary: beneficiary, pricePerSecond: pricePerSecond, priceCurrency: currency, minimumSubscriptionSeconds: minimumSubscriptionSeconds, state: ProductState.Deployed, newOwnerCandidate: address(0), requiresWhitelist: requiresWhitelist}); emit ProductCreated(msg.sender, id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds); } /** * Stop offering the product */ function deleteProduct(bytes32 productId) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.state == ProductState.Deployed, "error_notDeployed"); p.state = ProductState.NotDeployed; emit ProductDeleted(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); } /** * Return product to market */ function redeployProduct(bytes32 productId) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.state == ProductState.NotDeployed, "error_mustBeNotDeployed"); p.state = ProductState.Deployed; emit ProductRedeployed(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); } function updateProduct(bytes32 productId, string memory name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, bool redeploy) public onlyProductOwner(productId) { require(pricePerSecond > 0, "error_freeProductsNotSupported"); _importProductIfNeeded(productId); Product storage p = products[productId]; p.name = name; p.beneficiary = beneficiary; p.pricePerSecond = pricePerSecond; p.priceCurrency = currency; p.minimumSubscriptionSeconds = minimumSubscriptionSeconds; emit ProductUpdated(p.owner, p.id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds); if (redeploy) { redeployProduct(productId); } } /** * Changes ownership of the product. Two phase hand-over minimizes the chance that the product ownership is lost to a non-existent address. */ function offerProductOwnership(bytes32 productId, address newOwnerCandidate) public onlyProductOwner(productId) { _importProductIfNeeded(productId); // that productId exists is already checked in onlyProductOwner products[productId].newOwnerCandidate = newOwnerCandidate; emit ProductOwnershipOffered(products[productId].owner, productId, newOwnerCandidate); } /** * Changes ownership of the product. Two phase hand-over minimizes the chance that the product ownership is lost to a non-existent address. */ function claimProductOwnership(bytes32 productId) public whenNotHalted { _importProductIfNeeded(productId); // also checks that productId exists (newOwnerCandidate is zero for non-existent) Product storage p = products[productId]; require(msg.sender == p.newOwnerCandidate, "error_notPermitted"); emit ProductOwnershipChanged(msg.sender, productId, p.owner); p.owner = msg.sender; p.newOwnerCandidate = address(0); } /////////////// Whitelist management /////////////// function setRequiresWhitelist(bytes32 productId, bool _requiresWhitelist) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); p.requiresWhitelist = _requiresWhitelist; if (_requiresWhitelist) { emit WhitelistEnabled(productId); } else { emit WhitelistDisabled(productId); } } function whitelistApprove(bytes32 productId, address subscriber) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); require(p.requiresWhitelist, "error_whitelistNotEnabled"); p.whitelist[subscriber] = WhitelistState.Approved; emit WhitelistApproved(productId, subscriber); } function whitelistReject(bytes32 productId, address subscriber) public onlyProductOwner(productId) { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); require(p.requiresWhitelist, "error_whitelistNotEnabled"); p.whitelist[subscriber] = WhitelistState.Rejected; emit WhitelistRejected(productId, subscriber); } function whitelistRequest(bytes32 productId) public { _importProductIfNeeded(productId); Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); require(p.requiresWhitelist, "error_whitelistNotEnabled"); require(p.whitelist[msg.sender] == WhitelistState.None, "error_whitelistRequestAlreadySubmitted"); p.whitelist[msg.sender] = WhitelistState.Pending; emit WhitelistRequested(productId, msg.sender); } function getWhitelistState(bytes32 productId, address subscriber) public view returns (WhitelistState wlstate) { (, address _owner,,,,,,) = getProduct(productId); require(_owner != address(0), "error_notFound"); // if product is not local (maybe in old marketplace) this will return 0 (WhitelistState.None) Product storage p = products[productId]; return p.whitelist[subscriber]; } /////////////// Subscription management /////////////// function getSubscription(bytes32 productId, address subscriber) public override view returns (bool isValid, uint endTimestamp) { (,address _owner,,,,,,) = _getProductLocal(productId); if (_owner == address(0)) { return prev_marketplace.getSubscription(productId,subscriber); } (, TimeBasedSubscription storage sub) = _getSubscriptionLocal(productId, subscriber); if (sub.endTimestamp == 0x0) { // only call prev_marketplace.getSubscription() if product exists in previous marketplace too (,address _owner_prev,,,,,) = prev_marketplace.getProduct(productId); if (_owner_prev != address(0)) { return prev_marketplace.getSubscription(productId,subscriber); } } return (_isValid(sub), sub.endTimestamp); } function getSubscriptionTo(bytes32 productId) public view returns (bool isValid, uint endTimestamp) { return getSubscription(productId, msg.sender); } /** * Checks if the given address currently has a valid subscription * @param productId to check * @param subscriber to check */ function hasValidSubscription(bytes32 productId, address subscriber) public view returns (bool isValid) { (isValid,) = getSubscription(productId, subscriber); } /** * Enforces payment rules, triggers PurchaseListener event */ function _subscribe(bytes32 productId, uint addSeconds, address subscriber, bool requirePayment) internal { _importSubscriptionIfNeeded(productId, subscriber); (Product storage p, TimeBasedSubscription storage oldSub) = _getSubscriptionLocal(productId, subscriber); require(p.state == ProductState.Deployed, "error_notDeployed"); require(!p.requiresWhitelist || p.whitelist[subscriber] == WhitelistState.Approved, "error_whitelistNotAllowed"); uint endTimestamp; if (oldSub.endTimestamp > block.timestamp) { require(addSeconds > 0, "error_topUpTooSmall"); endTimestamp = oldSub.endTimestamp.add(addSeconds); oldSub.endTimestamp = endTimestamp; emit SubscriptionExtended(p.id, subscriber, endTimestamp); } else { require(addSeconds >= p.minimumSubscriptionSeconds, "error_newSubscriptionTooSmall"); endTimestamp = block.timestamp.add(addSeconds); TimeBasedSubscription memory newSub = TimeBasedSubscription(endTimestamp); p.subscriptions[subscriber] = newSub; emit NewSubscription(p.id, subscriber, endTimestamp); } emit Subscribed(p.id, subscriber, endTimestamp); uint256 price = 0; uint256 fee = 0; address recipient = p.beneficiary; if (requirePayment) { price = getPriceInData(addSeconds, p.pricePerSecond, p.priceCurrency); fee = txFee.mul(price).div(1 ether); require(datacoin.transferFrom(msg.sender, recipient, price.sub(fee)), "error_paymentFailed"); if (fee > 0) { require(datacoin.transferFrom(msg.sender, owner, fee), "error_paymentFailed"); } } uint256 codeSize; assembly { codeSize := extcodesize(recipient) } // solhint-disable-line no-inline-assembly if (codeSize > 0) { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returnData) = recipient.call( abi.encodeWithSignature("onPurchase(bytes32,address,uint256,uint256,uint256)", productId, subscriber, oldSub.endTimestamp, price, fee) ); if (success) { (bool accepted) = abi.decode(returnData, (bool)); require(accepted, "error_rejectedBySeller"); } } } function grantSubscription(bytes32 productId, uint subscriptionSeconds, address recipient) public whenNotHalted onlyProductOwner(productId){ return _subscribe(productId, subscriptionSeconds, recipient, false); } function buyFor(bytes32 productId, uint subscriptionSeconds, address recipient) public override whenNotHalted { return _subscribe(productId, subscriptionSeconds, recipient, true); } /** * Purchases access to this stream for msg.sender. * If the address already has a valid subscription, extends the subscription by the given period. * @dev since v4.0: Notify the seller if the seller implements PurchaseListener interface */ function buy(bytes32 productId, uint subscriptionSeconds) public whenNotHalted { buyFor(productId,subscriptionSeconds, msg.sender); } /** Gets subscriptions info from the subscriptions stored in this contract */ function _getSubscriptionLocal(bytes32 productId, address subscriber) internal view returns (Product storage p, TimeBasedSubscription storage s) { p = products[productId]; require(p.id != 0x0, "error_notFound"); s = p.subscriptions[subscriber]; } function _isValid(TimeBasedSubscription storage s) internal view returns (bool) { return s.endTimestamp >= block.timestamp; // solhint-disable-line not-rely-on-time } // TODO: transfer allowance to another Marketplace contract // Mechanism basically is that this Marketplace draws from the allowance and credits // the account on another Marketplace; OR that there is a central credit pool (say, an ERC20 token) // Creating another ERC20 token for this could be a simple fix: it would need the ability to transfer allowances /////////////// Currency management /////////////// // Exchange rates are formatted as "decimal fixed-point", that is, scaled by 10^18, like ether. // Exponent: 10^18 15 12 9 6 3 0 // | | | | | | | uint public dataPerUsd = 100000000000000000; // ~= 0.1 DATA/USD /** * Update currency exchange rates; all purchases are still billed in DATAcoin * @param timestamp in seconds when the exchange rates were last updated * @param dataUsd how many data atoms (10^-18 DATA) equal one USD dollar */ function updateExchangeRates(uint timestamp, uint dataUsd) public { require(msg.sender == currencyUpdateAgent, "error_notPermitted"); require(dataUsd > 0, "error_invalidRate"); dataPerUsd = dataUsd; emit ExchangeRatesUpdated(timestamp, dataUsd); } /** * Helper function to calculate (hypothetical) subscription cost for given seconds and price, using current exchange rates. * @param subscriptionSeconds length of hypothetical subscription, as a non-scaled integer * @param price nominal price scaled by 10^18 ("token wei" or "attodollars") * @param unit unit of the number price */ function getPriceInData(uint subscriptionSeconds, uint price, Currency unit) public override view returns (uint datacoinAmount) { if (unit == Currency.DATA) { return price.mul(subscriptionSeconds); } return price.mul(dataPerUsd).mul(subscriptionSeconds).div(10**18); } /////////////// Admin functionality /////////////// event Halted(); event Resumed(); bool public halted = false; modifier whenNotHalted() { require(!halted || owner == msg.sender, "error_halted"); _; } function halt() public onlyOwner { halted = true; emit Halted(); } function resume() public onlyOwner { halted = false; emit Resumed(); } function reInitialize(address datacoinAddress, address currencyUpdateAgentAddress, address prev_marketplace_address) public onlyOwner { _initialize(datacoinAddress, currencyUpdateAgentAddress, prev_marketplace_address); } function setTxFee(uint256 newTxFee) public onlyOwner { require(newTxFee <= 1 ether, "error_invalidTxFee"); txFee = newTxFee; emit TxFeeChanged(txFee); } }
84,498
3
// MINTING LIMITS /
function allowedMintCount(address minter) public view returns (uint256) { return MINT_LIMIT_PER_WALLET - mintCountMap[minter]; }
function allowedMintCount(address minter) public view returns (uint256) { return MINT_LIMIT_PER_WALLET - mintCountMap[minter]; }
11,332
85
// Internal function to get the exercible amount of an ACO token. acoToken Address of the ACO token.return The exercisable amount. /
function _getExercisableAmount(address acoToken) internal view returns(uint256) { uint256 balance = _getPoolBalanceOf(acoToken); if (balance > 0) { uint256 collaterized = IACOToken(acoToken).currentCollateralizedTokens(address(this)); if (balance > collaterized) { return balance.sub(collaterized); } } return 0; }
function _getExercisableAmount(address acoToken) internal view returns(uint256) { uint256 balance = _getPoolBalanceOf(acoToken); if (balance > 0) { uint256 collaterized = IACOToken(acoToken).currentCollateralizedTokens(address(this)); if (balance > collaterized) { return balance.sub(collaterized); } } return 0; }
56,536
4
// Generate edition metadata from storage information as base64-json blob/ Combines the media data and metadata/name Name of NFT in metadata/description Description of NFT in metadata/imageUrl URL of image to render for edition/tokenOfEdition Token ID for specific token/editionSize Size of entire edition to show
function createMetadataEdition( string memory name, string memory description, string memory imageUrl, uint256 tokenOfEdition, uint256 editionSize
function createMetadataEdition( string memory name, string memory description, string memory imageUrl, uint256 tokenOfEdition, uint256 editionSize
20,085
8
// END: Flights // BEGIN: Passengers /
function buyInsurance(bytes32 flightKey) external payable { dataContract.buyInsurance{value: msg.value}(msg.sender, flightKey); }
function buyInsurance(bytes32 flightKey) external payable { dataContract.buyInsurance{value: msg.value}(msg.sender, flightKey); }
4,246
195
// returns the URI for a specific token to show metadata on marketplaces_id the maximum supply of tokens for this token/
function uri(uint256 _id) public override view returns (string memory) { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return baseTokenURI[_id]; }
function uri(uint256 _id) public override view returns (string memory) { require(exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return baseTokenURI[_id]; }
20,108
21
// Gnosis Protocol v2 Order Library/Gnosis Developers
library GPv2Order { /// @dev The complete data for a Gnosis Protocol order. This struct contains /// all order parameters that are signed for submitting to GP. struct Data { IERC20 sellToken; IERC20 buyToken; address receiver; uint256 sellAmount; uint256 buyAmount; uint32 validTo; bytes32 appData; uint256 feeAmount; bytes32 kind; bool partiallyFillable; bytes32 sellTokenBalance; bytes32 buyTokenBalance; } /// @dev The order EIP-712 type hash for the [`GPv2Order.Data`] struct. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256( /// "Order(" + /// "address sellToken," + /// "address buyToken," + /// "address receiver," + /// "uint256 sellAmount," + /// "uint256 buyAmount," + /// "uint32 validTo," + /// "bytes32 appData," + /// "uint256 feeAmount," + /// "string kind," + /// "bool partiallyFillable," + /// "string sellTokenBalance," + /// "string buyTokenBalance" + /// ")" /// ) /// ``` bytes32 internal constant TYPE_HASH = hex"d5a25ba2e97094ad7d83dc28a6572da797d6b3e7fc6663bd93efb789fc17e489"; /// @dev The marker value for a sell order for computing the order struct /// hash. This allows the EIP-712 compatible wallets to display a /// descriptive string for the order kind (instead of 0 or 1). /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("sell") /// ``` bytes32 internal constant KIND_SELL = hex"f3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"; /// @dev The OrderKind marker value for a buy order for computing the order /// struct hash. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("buy") /// ``` bytes32 internal constant KIND_BUY = hex"6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"; /// @dev The TokenBalance marker value for using direct ERC20 balances for /// computing the order struct hash. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("erc20") /// ``` bytes32 internal constant BALANCE_ERC20 = hex"5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"; /// @dev The TokenBalance marker value for using Balancer Vault external /// balances (in order to re-use Vault ERC20 approvals) for computing the /// order struct hash. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("external") /// ``` bytes32 internal constant BALANCE_EXTERNAL = hex"abee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"; /// @dev The TokenBalance marker value for using Balancer Vault internal /// balances for computing the order struct hash. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("internal") /// ``` bytes32 internal constant BALANCE_INTERNAL = hex"4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"; /// @dev Marker address used to indicate that the receiver of the trade /// proceeds should the owner of the order. /// /// This is chosen to be `address(0)` for gas efficiency as it is expected /// to be the most common case. address internal constant RECEIVER_SAME_AS_OWNER = address(0); /// @dev The byte length of an order unique identifier. uint256 internal constant UID_LENGTH = 56; /// @dev Returns the actual receiver for an order. This function checks /// whether or not the [`receiver`] field uses the marker value to indicate /// it is the same as the order owner. /// /// @return receiver The actual receiver of trade proceeds. function actualReceiver(Data memory order, address owner) internal pure returns (address receiver) { if (order.receiver == RECEIVER_SAME_AS_OWNER) { receiver = owner; } else { receiver = order.receiver; } } /// @dev Return the EIP-712 signing hash for the specified order. /// /// @param order The order to compute the EIP-712 signing hash for. /// @param domainSeparator The EIP-712 domain separator to use. /// @return orderDigest The 32 byte EIP-712 struct hash. function hash(Data memory order, bytes32 domainSeparator) internal pure returns (bytes32 orderDigest) { bytes32 structHash; // NOTE: Compute the EIP-712 order struct hash in place. As suggested // in the EIP proposal, noting that the order struct has 12 fields, and // prefixing the type hash `(1 + 12) * 32 = 416` bytes to hash. // <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-encodedata> // solhint-disable-next-line no-inline-assembly assembly { let dataStart := sub(order, 32) let temp := mload(dataStart) mstore(dataStart, TYPE_HASH) structHash := keccak256(dataStart, 416) mstore(dataStart, temp) } // NOTE: Now that we have the struct hash, compute the EIP-712 signing // hash using scratch memory past the free memory pointer. The signing // hash is computed from `"\x19\x01" || domainSeparator || structHash`. // <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory> // <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification> // solhint-disable-next-line no-inline-assembly assembly { let freeMemoryPointer := mload(0x40) mstore(freeMemoryPointer, "\x19\x01") mstore(add(freeMemoryPointer, 2), domainSeparator) mstore(add(freeMemoryPointer, 34), structHash) orderDigest := keccak256(freeMemoryPointer, 66) } } /// @dev Packs order UID parameters into the specified memory location. The /// result is equivalent to `abi.encodePacked(...)` with the difference that /// it allows re-using the memory for packing the order UID. /// /// This function reverts if the order UID buffer is not the correct size. /// /// @param orderUid The buffer pack the order UID parameters into. /// @param orderDigest The EIP-712 struct digest derived from the order /// parameters. /// @param owner The address of the user who owns this order. /// @param validTo The epoch time at which the order will stop being valid. function packOrderUidParams( bytes memory orderUid, bytes32 orderDigest, address owner, uint32 validTo ) internal pure { require(orderUid.length == UID_LENGTH, "GPv2: uid buffer overflow"); // NOTE: Write the order UID to the allocated memory buffer. The order // parameters are written to memory in **reverse order** as memory // operations write 32-bytes at a time and we want to use a packed // encoding. This means, for example, that after writing the value of // `owner` to bytes `20:52`, writing the `orderDigest` to bytes `0:32` // will **overwrite** bytes `20:32`. This is desirable as addresses are // only 20 bytes and `20:32` should be `0`s: // // | 1111111111222222222233333333334444444444555555 // byte | 01234567890123456789012345678901234567890123456789012345 // -------+--------------------------------------------------------- // field | [.........orderDigest..........][......owner.......][vT] // -------+--------------------------------------------------------- // mstore | [000000000000000000000000000.vT] // | [00000000000.......owner.......] // | [.........orderDigest..........] // // Additionally, since Solidity `bytes memory` are length prefixed, // 32 needs to be added to all the offsets. // // solhint-disable-next-line no-inline-assembly assembly { mstore(add(orderUid, 56), validTo) mstore(add(orderUid, 52), owner) mstore(add(orderUid, 32), orderDigest) } } /// @dev Extracts specific order information from the standardized unique /// order id of the protocol. /// /// @param orderUid The unique identifier used to represent an order in /// the protocol. This uid is the packed concatenation of the order digest, /// the validTo order parameter and the address of the user who created the /// order. It is used by the user to interface with the contract directly, /// and not by calls that are triggered by the solvers. /// @return orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @return owner The address of the user who owns this order. /// @return validTo The epoch time at which the order will stop being valid. function extractOrderUidParams(bytes calldata orderUid) internal pure returns ( bytes32 orderDigest, address owner, uint32 validTo ) { require(orderUid.length == UID_LENGTH, "GPv2: invalid uid"); // Use assembly to efficiently decode packed calldata. // solhint-disable-next-line no-inline-assembly assembly { orderDigest := calldataload(orderUid.offset) owner := shr(96, calldataload(add(orderUid.offset, 32))) validTo := shr(224, calldataload(add(orderUid.offset, 52))) } } }
library GPv2Order { /// @dev The complete data for a Gnosis Protocol order. This struct contains /// all order parameters that are signed for submitting to GP. struct Data { IERC20 sellToken; IERC20 buyToken; address receiver; uint256 sellAmount; uint256 buyAmount; uint32 validTo; bytes32 appData; uint256 feeAmount; bytes32 kind; bool partiallyFillable; bytes32 sellTokenBalance; bytes32 buyTokenBalance; } /// @dev The order EIP-712 type hash for the [`GPv2Order.Data`] struct. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256( /// "Order(" + /// "address sellToken," + /// "address buyToken," + /// "address receiver," + /// "uint256 sellAmount," + /// "uint256 buyAmount," + /// "uint32 validTo," + /// "bytes32 appData," + /// "uint256 feeAmount," + /// "string kind," + /// "bool partiallyFillable," + /// "string sellTokenBalance," + /// "string buyTokenBalance" + /// ")" /// ) /// ``` bytes32 internal constant TYPE_HASH = hex"d5a25ba2e97094ad7d83dc28a6572da797d6b3e7fc6663bd93efb789fc17e489"; /// @dev The marker value for a sell order for computing the order struct /// hash. This allows the EIP-712 compatible wallets to display a /// descriptive string for the order kind (instead of 0 or 1). /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("sell") /// ``` bytes32 internal constant KIND_SELL = hex"f3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"; /// @dev The OrderKind marker value for a buy order for computing the order /// struct hash. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("buy") /// ``` bytes32 internal constant KIND_BUY = hex"6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"; /// @dev The TokenBalance marker value for using direct ERC20 balances for /// computing the order struct hash. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("erc20") /// ``` bytes32 internal constant BALANCE_ERC20 = hex"5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"; /// @dev The TokenBalance marker value for using Balancer Vault external /// balances (in order to re-use Vault ERC20 approvals) for computing the /// order struct hash. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("external") /// ``` bytes32 internal constant BALANCE_EXTERNAL = hex"abee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"; /// @dev The TokenBalance marker value for using Balancer Vault internal /// balances for computing the order struct hash. /// /// This value is pre-computed from the following expression: /// ``` /// keccak256("internal") /// ``` bytes32 internal constant BALANCE_INTERNAL = hex"4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"; /// @dev Marker address used to indicate that the receiver of the trade /// proceeds should the owner of the order. /// /// This is chosen to be `address(0)` for gas efficiency as it is expected /// to be the most common case. address internal constant RECEIVER_SAME_AS_OWNER = address(0); /// @dev The byte length of an order unique identifier. uint256 internal constant UID_LENGTH = 56; /// @dev Returns the actual receiver for an order. This function checks /// whether or not the [`receiver`] field uses the marker value to indicate /// it is the same as the order owner. /// /// @return receiver The actual receiver of trade proceeds. function actualReceiver(Data memory order, address owner) internal pure returns (address receiver) { if (order.receiver == RECEIVER_SAME_AS_OWNER) { receiver = owner; } else { receiver = order.receiver; } } /// @dev Return the EIP-712 signing hash for the specified order. /// /// @param order The order to compute the EIP-712 signing hash for. /// @param domainSeparator The EIP-712 domain separator to use. /// @return orderDigest The 32 byte EIP-712 struct hash. function hash(Data memory order, bytes32 domainSeparator) internal pure returns (bytes32 orderDigest) { bytes32 structHash; // NOTE: Compute the EIP-712 order struct hash in place. As suggested // in the EIP proposal, noting that the order struct has 12 fields, and // prefixing the type hash `(1 + 12) * 32 = 416` bytes to hash. // <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-encodedata> // solhint-disable-next-line no-inline-assembly assembly { let dataStart := sub(order, 32) let temp := mload(dataStart) mstore(dataStart, TYPE_HASH) structHash := keccak256(dataStart, 416) mstore(dataStart, temp) } // NOTE: Now that we have the struct hash, compute the EIP-712 signing // hash using scratch memory past the free memory pointer. The signing // hash is computed from `"\x19\x01" || domainSeparator || structHash`. // <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory> // <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification> // solhint-disable-next-line no-inline-assembly assembly { let freeMemoryPointer := mload(0x40) mstore(freeMemoryPointer, "\x19\x01") mstore(add(freeMemoryPointer, 2), domainSeparator) mstore(add(freeMemoryPointer, 34), structHash) orderDigest := keccak256(freeMemoryPointer, 66) } } /// @dev Packs order UID parameters into the specified memory location. The /// result is equivalent to `abi.encodePacked(...)` with the difference that /// it allows re-using the memory for packing the order UID. /// /// This function reverts if the order UID buffer is not the correct size. /// /// @param orderUid The buffer pack the order UID parameters into. /// @param orderDigest The EIP-712 struct digest derived from the order /// parameters. /// @param owner The address of the user who owns this order. /// @param validTo The epoch time at which the order will stop being valid. function packOrderUidParams( bytes memory orderUid, bytes32 orderDigest, address owner, uint32 validTo ) internal pure { require(orderUid.length == UID_LENGTH, "GPv2: uid buffer overflow"); // NOTE: Write the order UID to the allocated memory buffer. The order // parameters are written to memory in **reverse order** as memory // operations write 32-bytes at a time and we want to use a packed // encoding. This means, for example, that after writing the value of // `owner` to bytes `20:52`, writing the `orderDigest` to bytes `0:32` // will **overwrite** bytes `20:32`. This is desirable as addresses are // only 20 bytes and `20:32` should be `0`s: // // | 1111111111222222222233333333334444444444555555 // byte | 01234567890123456789012345678901234567890123456789012345 // -------+--------------------------------------------------------- // field | [.........orderDigest..........][......owner.......][vT] // -------+--------------------------------------------------------- // mstore | [000000000000000000000000000.vT] // | [00000000000.......owner.......] // | [.........orderDigest..........] // // Additionally, since Solidity `bytes memory` are length prefixed, // 32 needs to be added to all the offsets. // // solhint-disable-next-line no-inline-assembly assembly { mstore(add(orderUid, 56), validTo) mstore(add(orderUid, 52), owner) mstore(add(orderUid, 32), orderDigest) } } /// @dev Extracts specific order information from the standardized unique /// order id of the protocol. /// /// @param orderUid The unique identifier used to represent an order in /// the protocol. This uid is the packed concatenation of the order digest, /// the validTo order parameter and the address of the user who created the /// order. It is used by the user to interface with the contract directly, /// and not by calls that are triggered by the solvers. /// @return orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @return owner The address of the user who owns this order. /// @return validTo The epoch time at which the order will stop being valid. function extractOrderUidParams(bytes calldata orderUid) internal pure returns ( bytes32 orderDigest, address owner, uint32 validTo ) { require(orderUid.length == UID_LENGTH, "GPv2: invalid uid"); // Use assembly to efficiently decode packed calldata. // solhint-disable-next-line no-inline-assembly assembly { orderDigest := calldataload(orderUid.offset) owner := shr(96, calldataload(add(orderUid.offset, 32))) validTo := shr(224, calldataload(add(orderUid.offset, 52))) } } }
6,471
256
// This struct represents the issuance activity that's happened in a fee period.
struct FeePeriod { uint64 feePeriodId; uint64 startingDebtIndex; uint64 startTime; uint feesToDistribute; uint feesClaimed; uint rewardsToDistribute; uint rewardsClaimed; }
struct FeePeriod { uint64 feePeriodId; uint64 startingDebtIndex; uint64 startTime; uint feesToDistribute; uint feesClaimed; uint rewardsToDistribute; uint rewardsClaimed; }
31,282
64
// If it hasn't been curated before then initialize the curve
if (!isCurated(_subgraphDeploymentID)) { require( _tokens >= minimumCurationDeposit, "Curation deposit is below minimum required" );
if (!isCurated(_subgraphDeploymentID)) { require( _tokens >= minimumCurationDeposit, "Curation deposit is below minimum required" );
1,643
92
// Number of transfer to execute
uint256 nTransfer = _ids.length;
uint256 nTransfer = _ids.length;
19,195
8
// The max `totalSupply + burnedSupply`/This limit ensures that the DAT's formulas do not overflow (<MAX_BEFORE_SQUARE/2)
uint private constant MAX_SUPPLY = 10 ** 38;
uint private constant MAX_SUPPLY = 10 ** 38;
4,175
65
// Internal function to set allowance owner Token owner's address spender Spender's address value Allowance amount /
function _approve( address owner, address spender, uint256 value
function _approve( address owner, address spender, uint256 value
18,154
15
// whitelist users to Certified Partner allowing them to trade Certified Partner's properties/cp Certified Partner identifier/users Array of user identifiers
function addWhitelisted(string memory cp, string[] memory users) public onlyCPOrManager(cp) { bytes32 cpBytes = getUserBytes(cp); for (uint256 i = 0; i < users.length; i++) { bytes32 userBytes = getUserBytes(users[i]); _certifiedPartner[cpBytes].whitelistedUsers[userBytes] = true; } emit AddedWhitelisted(cpBytes, users, cp); }
function addWhitelisted(string memory cp, string[] memory users) public onlyCPOrManager(cp) { bytes32 cpBytes = getUserBytes(cp); for (uint256 i = 0; i < users.length; i++) { bytes32 userBytes = getUserBytes(users[i]); _certifiedPartner[cpBytes].whitelistedUsers[userBytes] = true; } emit AddedWhitelisted(cpBytes, users, cp); }
25,111
206
// The second of the two tokens of the pool, sorted by address/ return The token contract address
function token1() external view returns (address);
function token1() external view returns (address);
9,863
58
// Transfer token for a specified addresses from The address to transfer from. to The address to transfer to. value The amount to be transferred. /
function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); }
function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); }
5,379
43
// return Hash to be signed by tokens supplier.
function hash( TransactionData memory data ) internal pure returns (bytes32)
function hash( TransactionData memory data ) internal pure returns (bytes32)
32,375
25
// delete the element in the tree
BidOrderBook.remove(maxbid_id);
BidOrderBook.remove(maxbid_id);
15,568
16
// Sets the top up amount /
function setTopUpAmount(uint256 topUpAmount) external onlyOwner returns (uint256) { require(topUpAmount > 0); return s_topUpAmount = topUpAmount; }
function setTopUpAmount(uint256 topUpAmount) external onlyOwner returns (uint256) { require(topUpAmount > 0); return s_topUpAmount = topUpAmount; }
23,576
13
// unpause the presale (only for MANAGER_ROLE, only if the presale is paused) /
function unpause() external virtual onlyRole(MANAGER_ROLE) whenPaused { _paused = false; emit PresaleFinished(msg.sender); }
function unpause() external virtual onlyRole(MANAGER_ROLE) whenPaused { _paused = false; emit PresaleFinished(msg.sender); }
5,696
5
// Returns the total supply of votes available at the end of a past block (`blockNumber`). NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.Votes that have not been delegated are still part of total supply, even though they would not participate in avote. /
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
26,674
6
// Bridge voters array
address[] internal _bridgeVoterList;
address[] internal _bridgeVoterList;
23,990
96
// Destroys token `id`, using `by`.// Requirements:// - Token `id` must exist./ - If `by` is not the zero address,/ it must be the owner of the token, or be approved to manage the token./
/// Emits a {Transfer} event. function _burn(address by, uint256 id) internal virtual { address owner = ownerOf(id); _beforeTokenTransfer(owner, address(0), id); /// @solidity memory-safe-assembly assembly { // Clear the upper 96 bits. by := shr(96, shl(96, by)) // Load the ownership data. mstore(0x00, id) mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by)) let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20))) let ownershipPacked := sload(ownershipSlot) // Reload the owner in case it is changed in `_beforeTokenTransfer`. owner := shr(96, shl(96, ownershipPacked)) // Revert if the token does not exist. if iszero(owner) { mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`. revert(0x1c, 0x04) } // Load and check the token approval. { mstore(0x00, owner) let approvedAddress := sload(add(1, ownershipSlot)) // If `by` is not the zero address, do the authorization check. // Revert if the `by` is not the owner, nor approved. if iszero(or(iszero(by), or(eq(by, owner), eq(by, approvedAddress)))) { if iszero(sload(keccak256(0x0c, 0x30))) { mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`. revert(0x1c, 0x04) } } // Delete the approved address if any. if approvedAddress { sstore(add(1, ownershipSlot), 0) } } // Clear the owner. sstore(ownershipSlot, xor(ownershipPacked, owner)) // Decrement the balance of `owner`. { let balanceSlot := keccak256(0x0c, 0x1c) sstore(balanceSlot, sub(sload(balanceSlot), 1)) } // Emit the {Transfer} event. log4(0x00, 0x00, _TRANSFER_EVENT_SIGNATURE, owner, 0, id) } _afterTokenTransfer(owner, address(0), id); }
/// Emits a {Transfer} event. function _burn(address by, uint256 id) internal virtual { address owner = ownerOf(id); _beforeTokenTransfer(owner, address(0), id); /// @solidity memory-safe-assembly assembly { // Clear the upper 96 bits. by := shr(96, shl(96, by)) // Load the ownership data. mstore(0x00, id) mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by)) let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20))) let ownershipPacked := sload(ownershipSlot) // Reload the owner in case it is changed in `_beforeTokenTransfer`. owner := shr(96, shl(96, ownershipPacked)) // Revert if the token does not exist. if iszero(owner) { mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`. revert(0x1c, 0x04) } // Load and check the token approval. { mstore(0x00, owner) let approvedAddress := sload(add(1, ownershipSlot)) // If `by` is not the zero address, do the authorization check. // Revert if the `by` is not the owner, nor approved. if iszero(or(iszero(by), or(eq(by, owner), eq(by, approvedAddress)))) { if iszero(sload(keccak256(0x0c, 0x30))) { mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`. revert(0x1c, 0x04) } } // Delete the approved address if any. if approvedAddress { sstore(add(1, ownershipSlot), 0) } } // Clear the owner. sstore(ownershipSlot, xor(ownershipPacked, owner)) // Decrement the balance of `owner`. { let balanceSlot := keccak256(0x0c, 0x1c) sstore(balanceSlot, sub(sload(balanceSlot), 1)) } // Emit the {Transfer} event. log4(0x00, 0x00, _TRANSFER_EVENT_SIGNATURE, owner, 0, id) } _afterTokenTransfer(owner, address(0), id); }
20,251
164
// Users borrow assets from the protocol to their own addressborrowAmount The amount of the underlying asset to borrow return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * If doTransferOut fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferOut(borrower, borrowAmount); require(vars.err == Error.NO_ERROR, "borrow transfer out failed"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); }
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * If doTransferOut fails despite the fact we checked pre-conditions, * we revert because we can't be sure if side effects occurred. */ vars.err = doTransferOut(borrower, borrowAmount); require(vars.err == Error.NO_ERROR, "borrow transfer out failed"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); }
10,701
938
// Sets the collateralization limit.// This function reverts if the caller is not the current governance or if the collateralization limit is outside/ of the accepted bounds.//_limit the new collateralization limit.
function setCollateralizationLimit(uint256 _limit) external onlyGov { require(_limit >= MINIMUM_COLLATERALIZATION_LIMIT, "Alchemist: collateralization limit below minimum."); require(_limit <= MAXIMUM_COLLATERALIZATION_LIMIT, "Alchemist: collateralization limit above maximum."); _ctx.collateralizationLimit = FixedPointMath.FixedDecimal(_limit); emit CollateralizationLimitUpdated(_limit); }
function setCollateralizationLimit(uint256 _limit) external onlyGov { require(_limit >= MINIMUM_COLLATERALIZATION_LIMIT, "Alchemist: collateralization limit below minimum."); require(_limit <= MAXIMUM_COLLATERALIZATION_LIMIT, "Alchemist: collateralization limit above maximum."); _ctx.collateralizationLimit = FixedPointMath.FixedDecimal(_limit); emit CollateralizationLimitUpdated(_limit); }
20,453
132
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
bytes memory result = abi.encodePacked(input);
31,699
31
// Actually transfer the token to the new owner_address
safeTransferFrom(address(this), msg.sender, tokenId);
safeTransferFrom(address(this), msg.sender, tokenId);
17,949
176
// change private sale state
function flipPrivateSaleState() external onlyOwner { _privateSale = !_privateSale; emit privateSaleState(_privateSale); }
function flipPrivateSaleState() external onlyOwner { _privateSale = !_privateSale; emit privateSaleState(_privateSale); }
81,315
2
// Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value
modifier validRewards(uint256 _requestReward, uint256 _resultReward, uint256 _blockReward) { uint256 reqResReward = _requestReward + _resultReward; require(reqResReward >= _requestReward, "The sum of rewards overflows"); require(reqResReward + _blockReward >= reqResReward, "The sum of rewards overflows"); require(msg.value == _requestReward + _resultReward + _blockReward, "Transaction value should equal the sum of rewards"); _; }
modifier validRewards(uint256 _requestReward, uint256 _resultReward, uint256 _blockReward) { uint256 reqResReward = _requestReward + _resultReward; require(reqResReward >= _requestReward, "The sum of rewards overflows"); require(reqResReward + _blockReward >= reqResReward, "The sum of rewards overflows"); require(msg.value == _requestReward + _resultReward + _blockReward, "Transaction value should equal the sum of rewards"); _; }
30,553
105
// Drain funding from FundingLocker, transfers all the Liquidity Asset to this Loan.
IFundingLocker(fundingLocker).drain(); return liquidityAsset.balanceOf(address(this)).sub(preBal);
IFundingLocker(fundingLocker).drain(); return liquidityAsset.balanceOf(address(this)).sub(preBal);
23,708
169
// Creates a new token type and assigns _initialSupply to an address _maxSupply max supply allowed _initialSupply Optional amount to supply the first owner _uri Optional URI for this token type _data Optional data to pass if receiver is contractreturn The newly created token ID /
function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data
function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data
27,186
259
// free funds to repay debt + profit to the strategy
uint256 amountAvailable = balanceOfWant(); uint256 amountRequired = _debtOutstanding.add(_profit); if (amountRequired > amountAvailable) {
uint256 amountAvailable = balanceOfWant(); uint256 amountRequired = _debtOutstanding.add(_profit); if (amountRequired > amountAvailable) {
18,342
10
// Name of the token
string public constant name = "STELLARGOLD";
string public constant name = "STELLARGOLD";
28,987
221
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
25,374
31
// Creates a core pool (ModaCorePool) and registers it within the factoryCan be executed by the pool factory owner onlypoolStartTimestamp init timestamp to be used for the pool creation time weight weight of the pool to be created /
function createCorePool(uint256 poolStartTimestamp, uint32 weight) external virtual onlyOwner { // create/deploy new core pool instance IPool pool = new ModaCorePool(moda, address(this), address(0), moda, weight, poolStartTimestamp); // Now the owner needs to be set to whoever is calling this function. pool.transferOwnership(msg.sender); // register it within this factory registerPool(address(pool)); // Tell the world we've done that emit CorePoolCreated(msg.sender, address(pool)); }
function createCorePool(uint256 poolStartTimestamp, uint32 weight) external virtual onlyOwner { // create/deploy new core pool instance IPool pool = new ModaCorePool(moda, address(this), address(0), moda, weight, poolStartTimestamp); // Now the owner needs to be set to whoever is calling this function. pool.transferOwnership(msg.sender); // register it within this factory registerPool(address(pool)); // Tell the world we've done that emit CorePoolCreated(msg.sender, address(pool)); }
24,474
22
// Account / trader who opens the Swap
address buyer;
address buyer;
31,259
6
// Convert ETH To Dai /
function convertEthToDai(uint daiAmount) public payable { uint deadline = now + 15; // using 'now' for convenience, for mainnet pass deadline from frontend! uniswapRouter.swapETHForExactTokens.value(msg.value)(daiAmount, getPathForETHtoDAI(), address(this), deadline); // refund leftover ETH to user msg.sender.call.value(address(this).balance)(""); }
function convertEthToDai(uint daiAmount) public payable { uint deadline = now + 15; // using 'now' for convenience, for mainnet pass deadline from frontend! uniswapRouter.swapETHForExactTokens.value(msg.value)(daiAmount, getPathForETHtoDAI(), address(this), deadline); // refund leftover ETH to user msg.sender.call.value(address(this).balance)(""); }
46,791
88
// Calculates the amount of Sushi the xSushi is worth
uint256 what = _share.mul(sushi.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); sushi.transfer(msg.sender, what);
uint256 what = _share.mul(sushi.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); sushi.transfer(msg.sender, what);
43,929
223
// Sets `adminRole` as ``role``'s admin role. /
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; }
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; }
6,448
233
// Approves the globalSettlement to take out COIN from the proxy's balance in the safeEngine
if (safeEngine.canModifySAFE(address(this), address(globalSettlement)) == 0) { safeEngine.approveSAFEModification(globalSettlement); }
if (safeEngine.canModifySAFE(address(this), address(globalSettlement)) == 0) { safeEngine.approveSAFEModification(globalSettlement); }
7,569
130
// round 54
ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849); sbox_partial(i, q); mix(i, q);
ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849); sbox_partial(i, q); mix(i, q);
31,610
128
// Create inner scope to prevent stack too deep error
uint256 point1 = flashParams[1]; uint256 point2 = flashParams[2]; uint256 _bal;
uint256 point1 = flashParams[1]; uint256 point2 = flashParams[2]; uint256 _bal;
12,021
48
// ========== STATE VARIABLES ========== // ========== CONSTRUCTOR ========== /
constructor(address _mix) public { mix = IMIXToken(_mix); governance = msg.sender; teamAddr = msg.sender; blockFinish = block.number.add(blocksPerDuration); }
constructor(address _mix) public { mix = IMIXToken(_mix); governance = msg.sender; teamAddr = msg.sender; blockFinish = block.number.add(blocksPerDuration); }
34,132
29
// The ConverterRegistryData contract is an integral part of the converter registry as it serves as the database contract that holds all registry data. The registry is separated into two different contracts for upgradability - the data contract is harder to upgrade as it requires migrating all registry data into a new contract, while the registry contract itself can be easily upgraded. For that same reason, the data contract is simple and contains no logic beyond the basic data access utilities that it exposes./
contract ConverterRegistryData is IConverterRegistryData, ContractRegistryClient { struct Item { bool valid; uint256 index; } struct Items { address[] array; mapping(address => Item) table; } struct List { uint256 index; Items items; } struct Lists { address[] array; mapping(address => List) table; } Items private smartTokens; Items private liquidityPools; Lists private convertibleTokens; /** * @dev initializes a new ConverterRegistryData instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { } /** * @dev adds a smart token * * @param _anchor smart token */ function addSmartToken(IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { addItem(smartTokens, address(_anchor)); } /** * @dev removes a smart token * * @param _anchor smart token */ function removeSmartToken(IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { removeItem(smartTokens, address(_anchor)); } /** * @dev adds a liquidity pool * * @param _liquidityPoolAnchor liquidity pool */ function addLiquidityPool(IConverterAnchor _liquidityPoolAnchor) external override only(CONVERTER_REGISTRY) { addItem(liquidityPools, address(_liquidityPoolAnchor)); } /** * @dev removes a liquidity pool * * @param _liquidityPoolAnchor liquidity pool */ function removeLiquidityPool(IConverterAnchor _liquidityPoolAnchor) external override only(CONVERTER_REGISTRY) { removeItem(liquidityPools, address(_liquidityPoolAnchor)); } /** * @dev adds a convertible token * * @param _convertibleToken convertible token * @param _anchor associated smart token */ function addConvertibleToken(IERC20Token _convertibleToken, IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[address(_convertibleToken)]; if (list.items.array.length == 0) { list.index = convertibleTokens.array.length; convertibleTokens.array.push(address(_convertibleToken)); } addItem(list.items, address(_anchor)); } /** * @dev removes a convertible token * * @param _convertibleToken convertible token * @param _anchor associated smart token */ function removeConvertibleToken(IERC20Token _convertibleToken, IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[address(_convertibleToken)]; removeItem(list.items, address(_anchor)); if (list.items.array.length == 0) { address lastConvertibleToken = convertibleTokens.array[convertibleTokens.array.length - 1]; convertibleTokens.table[lastConvertibleToken].index = list.index; convertibleTokens.array[list.index] = lastConvertibleToken; convertibleTokens.array.pop(); delete convertibleTokens.table[address(_convertibleToken)]; } } /** * @dev returns the number of smart tokens * * @return number of smart tokens */ function getSmartTokenCount() external view override returns (uint256) { return smartTokens.array.length; } /** * @dev returns the list of smart tokens * * @return list of smart tokens */ function getSmartTokens() external view override returns (address[] memory) { return smartTokens.array; } /** * @dev returns the smart token at a given index * * @param _index index * @return smart token at the given index */ function getSmartToken(uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(smartTokens.array[_index]); } /** * @dev checks whether or not a given value is a smart token * * @param _value value * @return true if the given value is a smart token, false if not */ function isSmartToken(address _value) external view override returns (bool) { return smartTokens.table[_value].valid; } /** * @dev returns the number of liquidity pools * * @return number of liquidity pools */ function getLiquidityPoolCount() external view override returns (uint256) { return liquidityPools.array.length; } /** * @dev returns the list of liquidity pools * * @return list of liquidity pools */ function getLiquidityPools() external view override returns (address[] memory) { return liquidityPools.array; } /** * @dev returns the liquidity pool at a given index * * @param _index index * @return liquidity pool at the given index */ function getLiquidityPool(uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(liquidityPools.array[_index]); } /** * @dev checks whether or not a given value is a liquidity pool * * @param _value value * @return true if the given value is a liquidity pool, false if not */ function isLiquidityPool(address _value) external view override returns (bool) { return liquidityPools.table[_value].valid; } /** * @dev returns the number of convertible tokens * * @return number of convertible tokens */ function getConvertibleTokenCount() external view override returns (uint256) { return convertibleTokens.array.length; } /** * @dev returns the list of convertible tokens * * @return list of convertible tokens */ function getConvertibleTokens() external view override returns (address[] memory) { return convertibleTokens.array; } /** * @dev returns the convertible token at a given index * * @param _index index * @return convertible token at the given index */ function getConvertibleToken(uint256 _index) external view override returns (IERC20Token) { return IERC20Token(convertibleTokens.array[_index]); } /** * @dev checks whether or not a given value is a convertible token * * @param _value value * @return true if the given value is a convertible token, false if not */ function isConvertibleToken(address _value) external view override returns (bool) { return convertibleTokens.table[_value].items.array.length > 0; } /** * @dev returns the number of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return number of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokenCount(IERC20Token _convertibleToken) external view override returns (uint256) { return convertibleTokens.table[address(_convertibleToken)].items.array.length; } /** * @dev returns the list of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return list of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokens(IERC20Token _convertibleToken) external view override returns (address[] memory) { return convertibleTokens.table[address(_convertibleToken)].items.array; } /** * @dev returns the smart token associated with a given convertible token at a given index * * @param _index index * @return smart token associated with the given convertible token at the given index */ function getConvertibleTokenSmartToken(IERC20Token _convertibleToken, uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(convertibleTokens.table[address(_convertibleToken)].items.array[_index]); } /** * @dev checks whether or not a given value is a smart token of a given convertible token * * @param _convertibleToken convertible token * @param _value value * @return true if the given value is a smart token of the given convertible token, false it not */ function isConvertibleTokenSmartToken(IERC20Token _convertibleToken, address _value) external view override returns (bool) { return convertibleTokens.table[address(_convertibleToken)].items.table[_value].valid; } /** * @dev adds an item to a list of items * * @param _items list of items * @param _value item's value */ function addItem(Items storage _items, address _value) internal validAddress(_value) { Item storage item = _items.table[_value]; require(!item.valid, "ERR_INVALID_ITEM"); item.index = _items.array.length; _items.array.push(_value); item.valid = true; } /** * @dev removes an item from a list of items * * @param _items list of items * @param _value item's value */ function removeItem(Items storage _items, address _value) internal validAddress(_value) { Item storage item = _items.table[_value]; require(item.valid, "ERR_INVALID_ITEM"); address lastValue = _items.array[_items.array.length - 1]; _items.table[lastValue].index = item.index; _items.array[item.index] = lastValue; _items.array.pop(); delete _items.table[_value]; } }
contract ConverterRegistryData is IConverterRegistryData, ContractRegistryClient { struct Item { bool valid; uint256 index; } struct Items { address[] array; mapping(address => Item) table; } struct List { uint256 index; Items items; } struct Lists { address[] array; mapping(address => List) table; } Items private smartTokens; Items private liquidityPools; Lists private convertibleTokens; /** * @dev initializes a new ConverterRegistryData instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public { } /** * @dev adds a smart token * * @param _anchor smart token */ function addSmartToken(IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { addItem(smartTokens, address(_anchor)); } /** * @dev removes a smart token * * @param _anchor smart token */ function removeSmartToken(IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { removeItem(smartTokens, address(_anchor)); } /** * @dev adds a liquidity pool * * @param _liquidityPoolAnchor liquidity pool */ function addLiquidityPool(IConverterAnchor _liquidityPoolAnchor) external override only(CONVERTER_REGISTRY) { addItem(liquidityPools, address(_liquidityPoolAnchor)); } /** * @dev removes a liquidity pool * * @param _liquidityPoolAnchor liquidity pool */ function removeLiquidityPool(IConverterAnchor _liquidityPoolAnchor) external override only(CONVERTER_REGISTRY) { removeItem(liquidityPools, address(_liquidityPoolAnchor)); } /** * @dev adds a convertible token * * @param _convertibleToken convertible token * @param _anchor associated smart token */ function addConvertibleToken(IERC20Token _convertibleToken, IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[address(_convertibleToken)]; if (list.items.array.length == 0) { list.index = convertibleTokens.array.length; convertibleTokens.array.push(address(_convertibleToken)); } addItem(list.items, address(_anchor)); } /** * @dev removes a convertible token * * @param _convertibleToken convertible token * @param _anchor associated smart token */ function removeConvertibleToken(IERC20Token _convertibleToken, IConverterAnchor _anchor) external override only(CONVERTER_REGISTRY) { List storage list = convertibleTokens.table[address(_convertibleToken)]; removeItem(list.items, address(_anchor)); if (list.items.array.length == 0) { address lastConvertibleToken = convertibleTokens.array[convertibleTokens.array.length - 1]; convertibleTokens.table[lastConvertibleToken].index = list.index; convertibleTokens.array[list.index] = lastConvertibleToken; convertibleTokens.array.pop(); delete convertibleTokens.table[address(_convertibleToken)]; } } /** * @dev returns the number of smart tokens * * @return number of smart tokens */ function getSmartTokenCount() external view override returns (uint256) { return smartTokens.array.length; } /** * @dev returns the list of smart tokens * * @return list of smart tokens */ function getSmartTokens() external view override returns (address[] memory) { return smartTokens.array; } /** * @dev returns the smart token at a given index * * @param _index index * @return smart token at the given index */ function getSmartToken(uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(smartTokens.array[_index]); } /** * @dev checks whether or not a given value is a smart token * * @param _value value * @return true if the given value is a smart token, false if not */ function isSmartToken(address _value) external view override returns (bool) { return smartTokens.table[_value].valid; } /** * @dev returns the number of liquidity pools * * @return number of liquidity pools */ function getLiquidityPoolCount() external view override returns (uint256) { return liquidityPools.array.length; } /** * @dev returns the list of liquidity pools * * @return list of liquidity pools */ function getLiquidityPools() external view override returns (address[] memory) { return liquidityPools.array; } /** * @dev returns the liquidity pool at a given index * * @param _index index * @return liquidity pool at the given index */ function getLiquidityPool(uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(liquidityPools.array[_index]); } /** * @dev checks whether or not a given value is a liquidity pool * * @param _value value * @return true if the given value is a liquidity pool, false if not */ function isLiquidityPool(address _value) external view override returns (bool) { return liquidityPools.table[_value].valid; } /** * @dev returns the number of convertible tokens * * @return number of convertible tokens */ function getConvertibleTokenCount() external view override returns (uint256) { return convertibleTokens.array.length; } /** * @dev returns the list of convertible tokens * * @return list of convertible tokens */ function getConvertibleTokens() external view override returns (address[] memory) { return convertibleTokens.array; } /** * @dev returns the convertible token at a given index * * @param _index index * @return convertible token at the given index */ function getConvertibleToken(uint256 _index) external view override returns (IERC20Token) { return IERC20Token(convertibleTokens.array[_index]); } /** * @dev checks whether or not a given value is a convertible token * * @param _value value * @return true if the given value is a convertible token, false if not */ function isConvertibleToken(address _value) external view override returns (bool) { return convertibleTokens.table[_value].items.array.length > 0; } /** * @dev returns the number of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return number of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokenCount(IERC20Token _convertibleToken) external view override returns (uint256) { return convertibleTokens.table[address(_convertibleToken)].items.array.length; } /** * @dev returns the list of smart tokens associated with a given convertible token * * @param _convertibleToken convertible token * @return list of smart tokens associated with the given convertible token */ function getConvertibleTokenSmartTokens(IERC20Token _convertibleToken) external view override returns (address[] memory) { return convertibleTokens.table[address(_convertibleToken)].items.array; } /** * @dev returns the smart token associated with a given convertible token at a given index * * @param _index index * @return smart token associated with the given convertible token at the given index */ function getConvertibleTokenSmartToken(IERC20Token _convertibleToken, uint256 _index) external view override returns (IConverterAnchor) { return IConverterAnchor(convertibleTokens.table[address(_convertibleToken)].items.array[_index]); } /** * @dev checks whether or not a given value is a smart token of a given convertible token * * @param _convertibleToken convertible token * @param _value value * @return true if the given value is a smart token of the given convertible token, false it not */ function isConvertibleTokenSmartToken(IERC20Token _convertibleToken, address _value) external view override returns (bool) { return convertibleTokens.table[address(_convertibleToken)].items.table[_value].valid; } /** * @dev adds an item to a list of items * * @param _items list of items * @param _value item's value */ function addItem(Items storage _items, address _value) internal validAddress(_value) { Item storage item = _items.table[_value]; require(!item.valid, "ERR_INVALID_ITEM"); item.index = _items.array.length; _items.array.push(_value); item.valid = true; } /** * @dev removes an item from a list of items * * @param _items list of items * @param _value item's value */ function removeItem(Items storage _items, address _value) internal validAddress(_value) { Item storage item = _items.table[_value]; require(item.valid, "ERR_INVALID_ITEM"); address lastValue = _items.array[_items.array.length - 1]; _items.table[lastValue].index = item.index; _items.array[item.index] = lastValue; _items.array.pop(); delete _items.table[_value]; } }
33,226
11
// ----MODIFIERSModifier that will check if the ether amount being entered is greater than 0.01
modifier HasValidAmount() { require(msg.value > 0.01 ether,"Accepted value is greater than or equal to 0.01 ether."); _; }
modifier HasValidAmount() { require(msg.value > 0.01 ether,"Accepted value is greater than or equal to 0.01 ether."); _; }
7,401
151
// Called after validating a `onTransferReceived` operator address The address which called `transferAndCall` or `transferFromAndCall` function from address The address which are token transferred from value uint256 The amount of tokens transferred data bytes Additional data with no specified format /
function _transferReceived( address operator, // solhint-disable-line no-unused-vars address from, uint256 value, bytes memory data // solhint-disable-line no-unused-vars ) internal
function _transferReceived( address operator, // solhint-disable-line no-unused-vars address from, uint256 value, bytes memory data // solhint-disable-line no-unused-vars ) internal
10,825
5
// Keeping track of approved operators for a given Key manager. This approves a given operator for all keys managed by the calling "keyManager" The caller may not currently be the keyManager for ANY keys. These approvals are never reset/revoked automatically, unlike "approved", which is reset on transfer.
mapping (address => mapping (address => bool)) private managerToOperatorApproved;
mapping (address => mapping (address => bool)) private managerToOperatorApproved;
16,581
44
// hash the address (used to calculate checksum).
bytes32 b = keccak256(abi.encodePacked(_toAsciiString(a)));
bytes32 b = keccak256(abi.encodePacked(_toAsciiString(a)));
69,850
290
// OnchainWithdrawal data length
uint256 constant ONCHAIN_WITHDRAWAL_BYTES = 40;
uint256 constant ONCHAIN_WITHDRAWAL_BYTES = 40;
22,537
82
// VestingWallet This contract handles the vesting of Eth and ERC20 tokens for a given beneficiary. Custody of multiple tokenscan be given to this contract, which will release the token to the beneficiary following a given vesting schedule.
* The vesting schedule is customizable through the {vestedAmount} function. * * Any token transferred to this contract will follow the vesting schedule as if they were locked from the beginning. * Consequently, if the vesting has already started, any amount of tokens sent to this contract will (at least partly) * be immediately releasable. */ contract RisitasVesting is Context { event EtherReleased(uint256 amount); event ERC20Released(address indexed token, uint256 amount); uint256 private _released; mapping(address => uint256) private _erc20Released; address private immutable _beneficiary; uint64 private immutable _start; uint64 private immutable _duration; /** * @dev Set the beneficiary, start timestamp and vesting duration of the vesting wallet. */ constructor(address beneficiaryAddress, uint64 startTimestamp, uint64 durationSeconds) payable { require(beneficiaryAddress != address(0), "VestingWallet: beneficiary is zero address"); _beneficiary = beneficiaryAddress; _start = startTimestamp; _duration = durationSeconds; } /** * @dev The contract should be able to receive Eth. */ receive() external payable virtual {} /** * @dev Getter for the beneficiary address. */ function beneficiary() public view virtual returns (address) { return _beneficiary; } /** * @dev Getter for the start timestamp. */ function start() public view virtual returns (uint256) { return _start; } /** * @dev Getter for the vesting duration. */ function duration() public view virtual returns (uint256) { return _duration; } /** * @dev Amount of eth already released */ function released() public view virtual returns (uint256) { return _released; } /** * @dev Amount of token already released */ function released(address token) public view virtual returns (uint256) { return _erc20Released[token]; } /** * @dev Getter for the amount of releasable eth. */ function releasable() public view virtual returns (uint256) { return vestedAmount(uint64(block.timestamp)) - released(); } /** * @dev Getter for the amount of releasable `token` tokens. `token` should be the address of an * IERC20 contract. */ function releasable(address token) public view virtual returns (uint256) { return vestedAmount(token, uint64(block.timestamp)) - released(token); } /** * @dev Release the native token (ether) that have already vested. * * Emits a {EtherReleased} event. */ function release() public virtual { uint256 amount = releasable(); _released += amount; emit EtherReleased(amount); Address.sendValue(payable(beneficiary()), amount); } /** * @dev Release the tokens that have already vested. * * Emits a {ERC20Released} event. */ function release(address token) public virtual { uint256 amount = releasable(token); _erc20Released[token] += amount; emit ERC20Released(token, amount); SafeERC20.safeTransfer(IERC20(token), beneficiary(), amount); } /** * @dev Calculates the amount of ether that has already vested. Default implementation is a linear vesting curve. */ function vestedAmount(uint64 timestamp) public view virtual returns (uint256) { return _vestingSchedule(address(this).balance + released(), timestamp); } /** * @dev Calculates the amount of tokens that has already vested. Default implementation is a linear vesting curve. */ function vestedAmount(address token, uint64 timestamp) public view virtual returns (uint256) { return _vestingSchedule(IERC20(token).balanceOf(address(this)) + released(token), timestamp); } /** * @dev Virtual implementation of the vesting formula. This returns the amount vested, as a function of time, for * an asset given its total historical allocation. */ function _vestingSchedule(uint256 totalAllocation, uint64 timestamp) internal view virtual returns (uint256) { if (timestamp < start()) { return 0; } else if (timestamp > start() + duration()) { return totalAllocation; } else { return (totalAllocation * (timestamp - start())) / duration(); } } }
* The vesting schedule is customizable through the {vestedAmount} function. * * Any token transferred to this contract will follow the vesting schedule as if they were locked from the beginning. * Consequently, if the vesting has already started, any amount of tokens sent to this contract will (at least partly) * be immediately releasable. */ contract RisitasVesting is Context { event EtherReleased(uint256 amount); event ERC20Released(address indexed token, uint256 amount); uint256 private _released; mapping(address => uint256) private _erc20Released; address private immutable _beneficiary; uint64 private immutable _start; uint64 private immutable _duration; /** * @dev Set the beneficiary, start timestamp and vesting duration of the vesting wallet. */ constructor(address beneficiaryAddress, uint64 startTimestamp, uint64 durationSeconds) payable { require(beneficiaryAddress != address(0), "VestingWallet: beneficiary is zero address"); _beneficiary = beneficiaryAddress; _start = startTimestamp; _duration = durationSeconds; } /** * @dev The contract should be able to receive Eth. */ receive() external payable virtual {} /** * @dev Getter for the beneficiary address. */ function beneficiary() public view virtual returns (address) { return _beneficiary; } /** * @dev Getter for the start timestamp. */ function start() public view virtual returns (uint256) { return _start; } /** * @dev Getter for the vesting duration. */ function duration() public view virtual returns (uint256) { return _duration; } /** * @dev Amount of eth already released */ function released() public view virtual returns (uint256) { return _released; } /** * @dev Amount of token already released */ function released(address token) public view virtual returns (uint256) { return _erc20Released[token]; } /** * @dev Getter for the amount of releasable eth. */ function releasable() public view virtual returns (uint256) { return vestedAmount(uint64(block.timestamp)) - released(); } /** * @dev Getter for the amount of releasable `token` tokens. `token` should be the address of an * IERC20 contract. */ function releasable(address token) public view virtual returns (uint256) { return vestedAmount(token, uint64(block.timestamp)) - released(token); } /** * @dev Release the native token (ether) that have already vested. * * Emits a {EtherReleased} event. */ function release() public virtual { uint256 amount = releasable(); _released += amount; emit EtherReleased(amount); Address.sendValue(payable(beneficiary()), amount); } /** * @dev Release the tokens that have already vested. * * Emits a {ERC20Released} event. */ function release(address token) public virtual { uint256 amount = releasable(token); _erc20Released[token] += amount; emit ERC20Released(token, amount); SafeERC20.safeTransfer(IERC20(token), beneficiary(), amount); } /** * @dev Calculates the amount of ether that has already vested. Default implementation is a linear vesting curve. */ function vestedAmount(uint64 timestamp) public view virtual returns (uint256) { return _vestingSchedule(address(this).balance + released(), timestamp); } /** * @dev Calculates the amount of tokens that has already vested. Default implementation is a linear vesting curve. */ function vestedAmount(address token, uint64 timestamp) public view virtual returns (uint256) { return _vestingSchedule(IERC20(token).balanceOf(address(this)) + released(token), timestamp); } /** * @dev Virtual implementation of the vesting formula. This returns the amount vested, as a function of time, for * an asset given its total historical allocation. */ function _vestingSchedule(uint256 totalAllocation, uint64 timestamp) internal view virtual returns (uint256) { if (timestamp < start()) { return 0; } else if (timestamp > start() + duration()) { return totalAllocation; } else { return (totalAllocation * (timestamp - start())) / duration(); } } }
39,643
35
// This function calculates the total available rewards for a given staker
function availableRewards(address staker) public view returns (uint256) { // Calculate the rewards that have already been earned but not yet claimed by the staker uint256 rewards = calculateRewards(staker) + stakers[staker].unclaimedRewards; // Return the total rewards available to the staker return rewards; }
function availableRewards(address staker) public view returns (uint256) { // Calculate the rewards that have already been earned but not yet claimed by the staker uint256 rewards = calculateRewards(staker) + stakers[staker].unclaimedRewards; // Return the total rewards available to the staker return rewards; }
10,605
2
// Enable token redemption period /
function enableRedemption() external;
function enableRedemption() external;
17,236
8
// fee wallet to receive fees from buy/sell
address public feeWallet = 0xccFfa89265bB31f8d07328d3B2c8d2994CEb76e8;
address public feeWallet = 0xccFfa89265bB31f8d07328d3B2c8d2994CEb76e8;
29,918
102
// all remaining tokens will be sent to the last address in the addresses array
uint256 rRemainder = _rTotal - rDistributed; address liQuidityWalletAddress = addresses[addresses.length - 1]; _rOwned[liQuidityWalletAddress] = rRemainder; emit Transfer(address(0), liQuidityWalletAddress, tokenFromReflection(rRemainder));
uint256 rRemainder = _rTotal - rDistributed; address liQuidityWalletAddress = addresses[addresses.length - 1]; _rOwned[liQuidityWalletAddress] = rRemainder; emit Transfer(address(0), liQuidityWalletAddress, tokenFromReflection(rRemainder));
78,623
7
// Called by the proxy when setting this contract as implementation
function initialize( address _recipientBurn, address _tokenToBurn, address _kyberProxy, address[] memory _receivers, uint256[] memory _percentages, IERC20[] memory _tokens
function initialize( address _recipientBurn, address _tokenToBurn, address _kyberProxy, address[] memory _receivers, uint256[] memory _percentages, IERC20[] memory _tokens
32,515
46
// the previous whole hour of a timestamp
function getPreviousTimestampHour() internal view returns (uint256) { return block.timestamp - (getMinute(block.timestamp) * 60 + getSecond(block.timestamp)); }
function getPreviousTimestampHour() internal view returns (uint256) { return block.timestamp - (getMinute(block.timestamp) * 60 + getSecond(block.timestamp)); }
29,122
156
// Price Ratios, to x decimal places hencedecimals, dependent on the size of the denominator. Ratios are relative to eth, amount of ether for a single token, ie. ETH / GNO == 0.2 Ether per 1 Gnosis
uint256 orderPrice; // The price the maker is willing to accept uint256 offeredPrice; // The offer the taker has given
uint256 orderPrice; // The price the maker is willing to accept uint256 offeredPrice; // The offer the taker has given
22,727
17
// accept() lets receivers accept the delivery
function accept() public { require(now < start+term1, "The timeout term1 has been reached"); require(receiversState[msg.sender]==State.created, "Only receivers with 'created' state can accept"); acceptedReceivers = acceptedReceivers+1; receiversState[msg.sender] = State.accepted; }
function accept() public { require(now < start+term1, "The timeout term1 has been reached"); require(receiversState[msg.sender]==State.created, "Only receivers with 'created' state can accept"); acceptedReceivers = acceptedReceivers+1; receiversState[msg.sender] = State.accepted; }
36,252
5
// TokenURIs
function _baseURI() internal view override returns (string memory) { return baseUri; }
function _baseURI() internal view override returns (string memory) { return baseUri; }
23,922
1
// Errors // Initialize the contract /
function initialize( IERC20 underlyingToken, uint8 underlyingDecimals, string calldata n, string calldata s ) external;
function initialize( IERC20 underlyingToken, uint8 underlyingDecimals, string calldata n, string calldata s ) external;
4,862
439
// Set the base mutable meta URI/baseMutableURI_ the new base for mutable meta uri used in mutableURI()
function _setBaseMutableURI(string memory baseMutableURI_) internal { baseMutableURI = baseMutableURI_; }
function _setBaseMutableURI(string memory baseMutableURI_) internal { baseMutableURI = baseMutableURI_; }
44,446
288
// Emitted when iToken's borrow factor is changed by admin
event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external;
event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external;
34,576
15
// Curve main registry
address public constant MAIN_REGISTRY = address(0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5);
address public constant MAIN_REGISTRY = address(0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5);
67,276
130
// send bonuses according to signkeys bonus program
signkeysBonusProgram.sendBonus( _referrer, _tokenReceiver, tokensAmount, (tokensAmount.mul(tokenPriceCents).div(10 ** uint256(signkeysToken.decimals()))), _couponCampaignId);
signkeysBonusProgram.sendBonus( _referrer, _tokenReceiver, tokensAmount, (tokensAmount.mul(tokenPriceCents).div(10 ** uint256(signkeysToken.decimals()))), _couponCampaignId);
18,777
0
// SingularityNetToken Constructor/
function SingularityNetToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; }
function SingularityNetToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; }
37,526
146
// We have an active booster pool -> bridge
result = abi.encodePacked(result, poolData); needBridge = true;
result = abi.encodePacked(result, poolData); needBridge = true;
41,254
155
// 断言将WHT发送到了地址路径0,1组成的配对合约中
assert(IWHT(WHT).transfer(GoSwapLibrary.pairFor(company, path[0], path[1]), amountIn));
assert(IWHT(WHT).transfer(GoSwapLibrary.pairFor(company, path[0], path[1]), amountIn));
15,717
109
// and not the official LP receiving
&& recipient != address(pair) ) {
&& recipient != address(pair) ) {
28,095
140
// Mapping for token bid price
mapping(uint256 => uint256) private _tokenBidPrice;
mapping(uint256 => uint256) private _tokenBidPrice;
6,590
45
// Buy Boost Item itemTypeBoost Item type. /
function stakeForBoost(uint256 itemType) external { require(isWhitelisted(msg.sender), "You are not allowed to stake"); uint256 tokenBalance = IERC20(paymentTokenAddress).balanceOf( msg.sender ); require( boostItemExpireTime[msg.sender][1] == 0 || boostItemExpireTime[msg.sender][1] < block.timestamp, "You already have an active boost item" ); require( boostItemExpireTime[msg.sender][2] == 0 || boostItemExpireTime[msg.sender][2] < block.timestamp, "You already have an active boost item" ); require( boostItemExpireTime[msg.sender][3] == 0 || boostItemExpireTime[msg.sender][3] < block.timestamp, "You already have an active boost item" ); uint256 amount = 0; if (itemType == 1) { amount = _goldItemPrice; } else if (itemType == 2) { amount = _silverItemPrice; } else if (itemType == 3) { amount = _bronzeItemPrice; } else { require(false, "Invalid item type"); } require(tokenBalance >= amount, "Insufficient balance for boost"); require( IERC20(paymentTokenAddress).transferFrom( msg.sender, address(this), amount ), "Token Stake error" ); platformStatistic.totalStakedForBoost = platformStatistic .totalStakedForBoost .add(amount); platformStatistic.totalCommission = platformStatistic .totalCommission .add(amount); userBoostItemBalance[msg.sender][itemType] = userBoostItemBalance[ msg.sender ][itemType].add(1); boostItemExpireTime[msg.sender][itemType] = block.timestamp.add( BOOST_EXPIRE_TIME ); emit PurchasedBoostItem(msg.sender, itemType); emit UpdatedStatisticData(platformStatistic); }
function stakeForBoost(uint256 itemType) external { require(isWhitelisted(msg.sender), "You are not allowed to stake"); uint256 tokenBalance = IERC20(paymentTokenAddress).balanceOf( msg.sender ); require( boostItemExpireTime[msg.sender][1] == 0 || boostItemExpireTime[msg.sender][1] < block.timestamp, "You already have an active boost item" ); require( boostItemExpireTime[msg.sender][2] == 0 || boostItemExpireTime[msg.sender][2] < block.timestamp, "You already have an active boost item" ); require( boostItemExpireTime[msg.sender][3] == 0 || boostItemExpireTime[msg.sender][3] < block.timestamp, "You already have an active boost item" ); uint256 amount = 0; if (itemType == 1) { amount = _goldItemPrice; } else if (itemType == 2) { amount = _silverItemPrice; } else if (itemType == 3) { amount = _bronzeItemPrice; } else { require(false, "Invalid item type"); } require(tokenBalance >= amount, "Insufficient balance for boost"); require( IERC20(paymentTokenAddress).transferFrom( msg.sender, address(this), amount ), "Token Stake error" ); platformStatistic.totalStakedForBoost = platformStatistic .totalStakedForBoost .add(amount); platformStatistic.totalCommission = platformStatistic .totalCommission .add(amount); userBoostItemBalance[msg.sender][itemType] = userBoostItemBalance[ msg.sender ][itemType].add(1); boostItemExpireTime[msg.sender][itemType] = block.timestamp.add( BOOST_EXPIRE_TIME ); emit PurchasedBoostItem(msg.sender, itemType); emit UpdatedStatisticData(platformStatistic); }
31,804
3
// Whether the minting is open
bool public mintOpen;
bool public mintOpen;
50,122
13
// The amount of shares the user deposited.
uint128 shares;
uint128 shares;
60,755
3
// Add some fake pools
constructor() { Pool memory fakePool; fakePool.referenceAsset = "ETH/USD"; fakePool.expiryTime = 1657349074; fakePool.floor = 2000000000000000000000; fakePool.inflection = 2000000000000000000000; fakePool.cap = 4500000000000000000000; fakePool.supplyInitial = 100000000000000000000; fakePool.collateralToken = 0x867e53feDe91d27101E062BF7002143EbaEA3e30; fakePool.collateralBalanceShortInitial = 50000000000000000000; fakePool.collateralBalanceLongInitial = 50000000000000000000; fakePool.collateralBalance = 214199598796389167516; fakePool.shortToken = 0x91E75Aebda86a6B02d5510438f2981AC4Af1A44d; fakePool.longToken = 0x945b1fA4DB6Fb1f8d3C7501968F6549C8c147D4e; fakePool.finalReferenceValue = 0; fakePool.statusFinalReferenceValue = Status.Open; fakePool.redemptionAmountLongToken = 0; fakePool.redemptionAmountShortToken = 0; fakePool.statusTimestamp = 1647349398; fakePool.dataProvider = 0xED6D661645a11C45F4B82274db677867a7D32675; fakePool.redemptionFee = 2500000000000000; fakePool.settlementFee = 500000000000000; fakePool.capacity = 0; pools[3] = fakePool; }
constructor() { Pool memory fakePool; fakePool.referenceAsset = "ETH/USD"; fakePool.expiryTime = 1657349074; fakePool.floor = 2000000000000000000000; fakePool.inflection = 2000000000000000000000; fakePool.cap = 4500000000000000000000; fakePool.supplyInitial = 100000000000000000000; fakePool.collateralToken = 0x867e53feDe91d27101E062BF7002143EbaEA3e30; fakePool.collateralBalanceShortInitial = 50000000000000000000; fakePool.collateralBalanceLongInitial = 50000000000000000000; fakePool.collateralBalance = 214199598796389167516; fakePool.shortToken = 0x91E75Aebda86a6B02d5510438f2981AC4Af1A44d; fakePool.longToken = 0x945b1fA4DB6Fb1f8d3C7501968F6549C8c147D4e; fakePool.finalReferenceValue = 0; fakePool.statusFinalReferenceValue = Status.Open; fakePool.redemptionAmountLongToken = 0; fakePool.redemptionAmountShortToken = 0; fakePool.statusTimestamp = 1647349398; fakePool.dataProvider = 0xED6D661645a11C45F4B82274db677867a7D32675; fakePool.redemptionFee = 2500000000000000; fakePool.settlementFee = 500000000000000; fakePool.capacity = 0; pools[3] = fakePool; }
18,443
20
// One of the signers must be an address we want to set here
require(userAddress == reviewerAddresses[0] || userAddress == reviewerAddresses[1], "colony-task-role-assignment-not-signed-by-new-user-for-role");
require(userAddress == reviewerAddresses[0] || userAddress == reviewerAddresses[1], "colony-task-role-assignment-not-signed-by-new-user-for-role");
31,522
171
// overriding version of ${transfer} that includes message in token transfer /
function transfer(address recipient, uint256 amount, string calldata message) external returns (bool) { require(recipient != address(this), "ERC20: transfer to the this contract"); uint256 _fee = calculateTransferFee(amount); uint256 _amount = amount.sub(_fee);
function transfer(address recipient, uint256 amount, string calldata message) external returns (bool) { require(recipient != address(this), "ERC20: transfer to the this contract"); uint256 _fee = calculateTransferFee(amount); uint256 _amount = amount.sub(_fee);
15,883
379
// reward 0.5 level
uint256 oldLevel = warrior.level; uint256 level = oldLevel; if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) { level += (POINTS_TO_LEVEL / 2); warrior.level = uint64(level); }
uint256 oldLevel = warrior.level; uint256 level = oldLevel; if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) { level += (POINTS_TO_LEVEL / 2); warrior.level = uint64(level); }
78,919
1
// Adds the ability to sweep ERC721 tokens to a beneficiary address /
abstract contract SweepERC721 is TokenSweep { /** * @notice Sweep the erc721 tokens to the beneficiary address **/ function _sweepERC721Tokens(address token, uint256 tokenId) internal { require(token != address(this), "SweepERC721: self transfer"); require(token != address(0), "SweepERC721: address zero"); IERC721Upgradeable(token).safeTransferFrom( address(this), tokenSweepBeneficiary(), tokenId ); } }
abstract contract SweepERC721 is TokenSweep { /** * @notice Sweep the erc721 tokens to the beneficiary address **/ function _sweepERC721Tokens(address token, uint256 tokenId) internal { require(token != address(this), "SweepERC721: self transfer"); require(token != address(0), "SweepERC721: address zero"); IERC721Upgradeable(token).safeTransferFrom( address(this), tokenSweepBeneficiary(), tokenId ); } }
17,285