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
12
// Allowing patients to add their ipfshash of medical records
function addRecords(uint256 pid, string memory _ipfsHash) public onlyPatient(pid)
function addRecords(uint256 pid, string memory _ipfsHash) public onlyPatient(pid)
47,596
163
// return dodoPool2.getPendingReward(account,0);
return _balances[account].mul(rewardPerToken2().sub(userRewardPerTokenPaid2[account])).div(1e18).add(rewards2[account]);
return _balances[account].mul(rewardPerToken2().sub(userRewardPerTokenPaid2[account])).div(1e18).add(rewards2[account]);
44,613
5
// close re-entrance gate, prevent double withdrawals
withdrawn[merkleIndex][msg.sender] = true;
withdrawn[merkleIndex][msg.sender] = true;
3,544
0
// Base contract for all Ethernauts contracts holding global constants and functions.
contract EthernautsBase { /*** CONSTANTS USED ACROSS CONTRACTS ***/ /// @dev Used by all contracts that interfaces with Ethernauts /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev due solidity limitation we cannot return dynamic array from methods /// so it creates incompability between functions across different contracts uint8 public constant STATS_SIZE = 10; uint8 public constant SHIP_SLOTS = 5; // Possible state of any asset enum AssetState { Available, UpForLease, Used } // Possible state of any asset // NotValid is to avoid 0 in places where category must be bigger than zero enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember } /// @dev Sector stats enum ShipStats {Level, Attack, Defense, Speed, Range, Luck} /// @notice Possible attributes for each asset /// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. /// 00000010 - Producible - Product of a factory and/or factory contract. /// 00000100 - Explorable- Product of exploration. /// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. /// 00010000 - Permanent - Cannot be removed, always owned by a user. /// 00100000 - Consumable - Destroyed after N exploration expeditions. /// 01000000 - Tradable - Buyable and sellable on the market. /// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 public ATTR_SEEDED = bytes2(2**0); bytes2 public ATTR_PRODUCIBLE = bytes2(2**1); bytes2 public ATTR_EXPLORABLE = bytes2(2**2); bytes2 public ATTR_LEASABLE = bytes2(2**3); bytes2 public ATTR_PERMANENT = bytes2(2**4); bytes2 public ATTR_CONSUMABLE = bytes2(2**5); bytes2 public ATTR_TRADABLE = bytes2(2**6); bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7); }
contract EthernautsBase { /*** CONSTANTS USED ACROSS CONTRACTS ***/ /// @dev Used by all contracts that interfaces with Ethernauts /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev due solidity limitation we cannot return dynamic array from methods /// so it creates incompability between functions across different contracts uint8 public constant STATS_SIZE = 10; uint8 public constant SHIP_SLOTS = 5; // Possible state of any asset enum AssetState { Available, UpForLease, Used } // Possible state of any asset // NotValid is to avoid 0 in places where category must be bigger than zero enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember } /// @dev Sector stats enum ShipStats {Level, Attack, Defense, Speed, Range, Luck} /// @notice Possible attributes for each asset /// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. /// 00000010 - Producible - Product of a factory and/or factory contract. /// 00000100 - Explorable- Product of exploration. /// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. /// 00010000 - Permanent - Cannot be removed, always owned by a user. /// 00100000 - Consumable - Destroyed after N exploration expeditions. /// 01000000 - Tradable - Buyable and sellable on the market. /// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 public ATTR_SEEDED = bytes2(2**0); bytes2 public ATTR_PRODUCIBLE = bytes2(2**1); bytes2 public ATTR_EXPLORABLE = bytes2(2**2); bytes2 public ATTR_LEASABLE = bytes2(2**3); bytes2 public ATTR_PERMANENT = bytes2(2**4); bytes2 public ATTR_CONSUMABLE = bytes2(2**5); bytes2 public ATTR_TRADABLE = bytes2(2**6); bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7); }
10,861
263
// Special properties of Golden Unicorns /
returns (bool) { require(_tokenId < finalSupply, "Property query for nonexistent token"); return _tokenId >= finalSupply / 2 - 1 && _tokenId < finalSupply - 1; }
returns (bool) { require(_tokenId < finalSupply, "Property query for nonexistent token"); return _tokenId >= finalSupply / 2 - 1 && _tokenId < finalSupply - 1; }
38,325
72
// get dynamic fee
if(_useImpactFeeSetter) { uint256 feeBasis = amount.mul(_feeMultiplier); feeBasis = feeBasis.div(balanceOf(uniswapV2Pair).add(amount)); setFee(feeBasis); }
if(_useImpactFeeSetter) { uint256 feeBasis = amount.mul(_feeMultiplier); feeBasis = feeBasis.div(balanceOf(uniswapV2Pair).add(amount)); setFee(feeBasis); }
27,199
356
// KyberSwap Elastic
IFactory public kyber_factory; IBasePositionManager public kyber_positions_mgr; IRouter public kyber_router; ITickFeesReader public kyber_tick_fees_reader;
IFactory public kyber_factory; IBasePositionManager public kyber_positions_mgr; IRouter public kyber_router; ITickFeesReader public kyber_tick_fees_reader;
26,625
25
// Setting Token Symbol to MGO
string public constant symbol = "IPR";
string public constant symbol = "IPR";
26,767
12
// tier pop
function populateTierTokens() public { require((msg.sender == owner) && (initialTiers == false)); scheduleTokens[1] = 5.33696E18; scheduleTokens[2] = 7.69493333E18; scheduleTokens[3] = 4.75684324E18; scheduleTokens[4] = 6.30846753E18; scheduleTokens[5] = 6.21620513E18; scheduleTokens[6] = 5.63157219E18; scheduleTokens[7] = 5.80023669E18; scheduleTokens[8] = 5.04458667E18; scheduleTokens[9] = 4.58042767E18; scheduleTokens[10] = 5E18; scheduleTokens[11] = 5.59421053E18; scheduleTokens[12] = 7.05050888E18; scheduleTokens[13] = 1.93149011E19; scheduleTokens[14] = 5.71055924E18; scheduleTokens[15] = 1.087367665E19; scheduleTokens[16] = 5.4685283E18; scheduleTokens[17] = 7.58236145E18; scheduleTokens[18] = 5.80773184E18; scheduleTokens[19] = 4.74868639E18; scheduleTokens[20] = 6.74810256E18; scheduleTokens[21] = 5.52847682E18; scheduleTokens[22] = 4.96611055E18; scheduleTokens[23] = 5.45818182E18; scheduleTokens[24] = 8.0597095E18; scheduleTokens[25] = 1.459911381E19; scheduleTokens[26] = 8.32598844E18; scheduleTokens[27] = 4.555277509E19; scheduleTokens[28] = 1.395674359E19; scheduleTokens[29] = 9.78908515E18; scheduleTokens[30] = 1.169045087E19; }
function populateTierTokens() public { require((msg.sender == owner) && (initialTiers == false)); scheduleTokens[1] = 5.33696E18; scheduleTokens[2] = 7.69493333E18; scheduleTokens[3] = 4.75684324E18; scheduleTokens[4] = 6.30846753E18; scheduleTokens[5] = 6.21620513E18; scheduleTokens[6] = 5.63157219E18; scheduleTokens[7] = 5.80023669E18; scheduleTokens[8] = 5.04458667E18; scheduleTokens[9] = 4.58042767E18; scheduleTokens[10] = 5E18; scheduleTokens[11] = 5.59421053E18; scheduleTokens[12] = 7.05050888E18; scheduleTokens[13] = 1.93149011E19; scheduleTokens[14] = 5.71055924E18; scheduleTokens[15] = 1.087367665E19; scheduleTokens[16] = 5.4685283E18; scheduleTokens[17] = 7.58236145E18; scheduleTokens[18] = 5.80773184E18; scheduleTokens[19] = 4.74868639E18; scheduleTokens[20] = 6.74810256E18; scheduleTokens[21] = 5.52847682E18; scheduleTokens[22] = 4.96611055E18; scheduleTokens[23] = 5.45818182E18; scheduleTokens[24] = 8.0597095E18; scheduleTokens[25] = 1.459911381E19; scheduleTokens[26] = 8.32598844E18; scheduleTokens[27] = 4.555277509E19; scheduleTokens[28] = 1.395674359E19; scheduleTokens[29] = 9.78908515E18; scheduleTokens[30] = 1.169045087E19; }
50,021
139
// Safe Token // Gets balance of this contract in terms of the underlying This excludes the value of the current message, if anyreturn The quantity of underlying owned by this contract /
function getCashPrior() internal view returns (uint);
function getCashPrior() internal view returns (uint);
4,103
567
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; }
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; }
16,565
17
// Create a dispute. Must be called by the arbitrable contract. Must be paid at least arbitrationCost()._choices Amount of choices the arbitrator can make in this dispute. When ruling ruling<=choices._extraData Can be used to give additional info on the dispute to be created. return disputeID ID of the dispute created. /
function createDispute(uint _choices, bytes _extraData) public payable returns(uint disputeID) { super.createDispute(_choices, _extraData); disputeID = disputes.push(DisputeStruct({ arbitrated: Arbitrable(msg.sender), choices: _choices, fee: msg.value, ruling: 0, status: DisputeStatus.Waiting })) - 1; // Create the dispute and return its number. emit DisputeCreation(disputeID, Arbitrable(msg.sender)); }
function createDispute(uint _choices, bytes _extraData) public payable returns(uint disputeID) { super.createDispute(_choices, _extraData); disputeID = disputes.push(DisputeStruct({ arbitrated: Arbitrable(msg.sender), choices: _choices, fee: msg.value, ruling: 0, status: DisputeStatus.Waiting })) - 1; // Create the dispute and return its number. emit DisputeCreation(disputeID, Arbitrable(msg.sender)); }
23,645
22
// Reduce the total supply.
totalSupply -= burnAmount; emit Transfer(holder, address(0), burnAmount);
totalSupply -= burnAmount; emit Transfer(holder, address(0), burnAmount);
29,510
59
// newHolderFee: 200 = 2.00% /
function setHolderFee(uint256 newHolderFee) public onlyOwner { require(newHolderFee <= _holderFee); _holderFee = newHolderFee; }
function setHolderFee(uint256 newHolderFee) public onlyOwner { require(newHolderFee <= _holderFee); _holderFee = newHolderFee; }
36,225
151
// Whitelist check if whitelist is active
if(whitelist) {
if(whitelist) {
8,142
21
// . Requirements: - `addr` cannot be the zero address. /
function addWhitelisted(address addr) external onlyOwner { whitelist[addr] = true; }
function addWhitelisted(address addr) external onlyOwner { whitelist[addr] = true; }
26,375
82
// how many USD cents get per ETH /
uint public ethUsdRate;
uint public ethUsdRate;
43,822
41
// Check if the matched amount + previously matched trades doesn't exceed the amount specified by the order signee
&& trade.taker_amount + matched[hashes[taker_index]] <= orders[taker_index].sell_amount && trade.maker_amount - trade.maker_rebate + matched[hashes[maker_index]] <= orders[maker_index].sell_amount
&& trade.taker_amount + matched[hashes[taker_index]] <= orders[taker_index].sell_amount && trade.maker_amount - trade.maker_rebate + matched[hashes[maker_index]] <= orders[maker_index].sell_amount
25,269
38
// Lock tokensAccount the address of account to lock amount the amount of money to lock /
function LockTokens(address Account, uint256 amount) onlyOwner public{ LockedTokens[Account]=amount; }
function LockTokens(address Account, uint256 amount) onlyOwner public{ LockedTokens[Account]=amount; }
7,996
10
// RefundableCrowdsale Extension of Crowdsale contract that adds a funding goal, andthe possibility of users getting a refund if goal is not met. /
contract RefundableBeforeSoftCapCrowdsale is Ownable, FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund escrow used to hold funds while crowdsale is running // AfterSoftCapEscrow private escrow; AfterSoftCapEscrow private escrow; /** * @dev Constructor, creates RefundEscrow. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); escrow = new AfterSoftCapEscrow(wallet, rate); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); escrow.withdraw(msg.sender); } /** * @dev Checks escrow wallet balance */ function escrowBalance() public view returns (uint256) { return address(escrow).balance; } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } function updateEscrowGoalReached() onlyOwner public { require(!isFinalized); require(goalReached()); escrow.reachGoal(); } function beneficiaryWithdraw() onlyOwner public { require(goalReached()); escrow.beneficiaryWithdraw(); } /** * @dev escrow finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { escrow.reachGoal(); escrow.beneficiaryWithdraw(); } else { escrow.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { escrow.deposit.value(msg.value)(msg.sender); } }
contract RefundableBeforeSoftCapCrowdsale is Ownable, FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund escrow used to hold funds while crowdsale is running // AfterSoftCapEscrow private escrow; AfterSoftCapEscrow private escrow; /** * @dev Constructor, creates RefundEscrow. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); escrow = new AfterSoftCapEscrow(wallet, rate); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); escrow.withdraw(msg.sender); } /** * @dev Checks escrow wallet balance */ function escrowBalance() public view returns (uint256) { return address(escrow).balance; } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } function updateEscrowGoalReached() onlyOwner public { require(!isFinalized); require(goalReached()); escrow.reachGoal(); } function beneficiaryWithdraw() onlyOwner public { require(goalReached()); escrow.beneficiaryWithdraw(); } /** * @dev escrow finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { escrow.reachGoal(); escrow.beneficiaryWithdraw(); } else { escrow.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { escrow.deposit.value(msg.value)(msg.sender); } }
42,715
21
// Participants list
address[] public addressList;
address[] public addressList;
34,890
105
// Total cards staked
mapping(uint256 => uint256) public totalCards;
mapping(uint256 => uint256) public totalCards;
30,097
413
// VOTING DATA STRUCTURES / Identifies a unique price request for which the Oracle will always return the same value. Tracks ongoing votes as well as the result of the vote.
struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; }
struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; }
9,171
1
// mint a token with no extension. Can only be called by an admin.Returns tokenId minted /
function mintBase(address to) external returns (uint256);
function mintBase(address to) external returns (uint256);
7,633
89
// minimum tokens to initiate a swap
uint256 private constant _minimumTokensToSwap = 10 * 10**3 * 10**_decimals;
uint256 private constant _minimumTokensToSwap = 10 * 10**3 * 10**_decimals;
10,808
35
// See EIP-2981
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view virtual returns (address receiver, uint256 royaltyAmount)
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view virtual returns (address receiver, uint256 royaltyAmount)
9,231
4
// max match rounds that can be played in one day
uint8 public constant MATCH_SCHEDULE_INTERVAL_MAX = 144;
uint8 public constant MATCH_SCHEDULE_INTERVAL_MAX = 144;
28,871
512
// Library containing public functions for pending ops - those will never be inlined to reduce the bytecode size of individual contracts.
library ProtectedBoostableLib { using ECDSA for bytes32; function deleteOpHandle( address user, OpHandle memory opHandle, OpHandle[] storage opHandles, OpCounter storage opCounter, mapping(bytes32 => OpMetadata) storage opMetadata ) public { uint256 length = opHandles.length; assert(length > 0); uint64 minOpId; // becomes next LIFO uint64 maxOpId; // becomes next FIFO // Pending ops are capped to MAX_PENDING_OPS. We always perform // MIN(length, MAX_PENDING_OPS) look-ups to do a "swap-and-pop" and // for updating the opCounter LIFO/FIFO pointers. for (uint256 i = 0; i < length; i++) { uint64 currOpId = opHandles[i].opId; if (currOpId == opHandle.opId) { // Overwrite item at i with last opHandles[i] = opHandles[length - 1]; // Continue, to ignore this opId when updating // minOpId and maxOpId. continue; } // Update minOpId if (minOpId == 0 || currOpId < minOpId) { minOpId = currOpId; } // Update maxOpId if (currOpId > maxOpId) { maxOpId = currOpId; } } // Might be 0 when everything got finalized/reverted opCounter.nextFinalize = minOpId; // Might be 0 when everything got finalized/reverted opCounter.nextRevert = maxOpId; // Remove the last item opHandles.pop(); // Remove metadata delete opMetadata[_getOpKey(user, opHandle.opId)]; } function assertCanFinalize( OpMetadata memory metadata, IOptIn.OptInStatus memory optInStatus ) public view returns (uint64) { // Now there are three valid scenarios remaining: // // - msg.sender is the original booster // - op is expired // - getBoosterAddress returns a different booster than the original booster // // In the second and third case, anyone can call finalize. address originalBooster = metadata.booster; if (originalBooster == msg.sender) { return metadata.createdAt; // First case } address currentBooster = optInStatus.optedInTo; uint256 optOutPeriod = optInStatus.optOutPeriod; bool isExpired = block.timestamp >= metadata.createdAt + optOutPeriod; if (isExpired) { return metadata.createdAt; // Second case } if (currentBooster != originalBooster) { return metadata.createdAt; // Third case } revert("PB-4"); } function verifySignatureForRevert( address user, uint64 opTimestamp, IOptIn.OptInStatus memory optInStatus, bytes memory boosterMessage, address[] memory hasherContracts, Signature memory signature ) public { require(hasherContracts.length > 0, "PB-12"); // Result of hasher contract call uint64 signedAt; bytes32 boosterHash; bool signatureVerified; for (uint256 i = 0; i < hasherContracts.length; i++) { // Call into the hasher contract and take the first non-zero result. // The contract must implement the following function: // // decodeAndHashBoosterMessage( // address targetBooster, // bytes memory boosterMessage // ) // // If it doesn't, then the call will fail (success=false) and we try the next one. // If it succeeds (success = true), then we try to decode the result. // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory result) = address(hasherContracts[i]) .call( // keccak256("decodeAndHashBoosterMessage(address,bytes)") abi.encodeWithSelector( 0xaf6eec54, msg.sender, /* msg.sender becomes the target booster */ boosterMessage ) ); if (!success) { continue; } // The result is exactly 2 words long = 512 bits = 64 bytes // 32 bytes for the expected message hash // 8 bytes (padded to 32 bytes) for the expected timestamp if (result.length != 64) { continue; } // NOTE: A contract with malintent could return any hash that we would // try to recover against. But there is no harm done in doing so since // the user must have signed it. // // However, it might return an unrelated timestamp, that the user hasn't // signed - so it could prolong the expiry of a signature which is a valid // concern whose risk we minimize by using also the op timestamp which guarantees // that a signature eventually expires. // Decode and recover signer (boosterHash, signedAt) = abi.decode(result, (bytes32, uint64)); address signer = ecrecover( boosterHash, signature.v, signature.r, signature.s ); if (user != signer) { // NOTE: Currently, hardware wallets (e.g. Ledger, Trezor) do not support EIP712 signing (specifically `signTypedData_v4`). // However, a user can still sign the EIP712 hash with the caveat that it's signed using `personal_sign` which prepends // the prefix '"\x19Ethereum Signed Message:\n" + len(message)'. // // To still support that, we also add the prefix and try to use the recovered address instead: signer = ecrecover( boosterHash.toEthSignedMessageHash(), signature.v, signature.r, signature.s ); } // If we recovered `user` from the signature, then we have a valid signature. if (user == signer) { signatureVerified = true; break; } // Keep trying } // Revert if signature couldn't be verified with any of the returned hashes require(signatureVerified, "PB-8"); // Lastly, the current time must not be older than: // MIN(opTimestamp, signedAt) + optOutPeriod * 3 uint64 _now = uint64(block.timestamp); // The maximum age is equal to whichever is lowest: // opTimestamp + optOutPeriod * 3 // signedAt + optOutPeriod * 3 uint64 maximumAge; if (opTimestamp > signedAt) { maximumAge = signedAt + uint64(optInStatus.optOutPeriod * 3); } else { maximumAge = opTimestamp + uint64(optInStatus.optOutPeriod * 3); } require(_now <= maximumAge, "PB-11"); } function _getOpKey(address user, uint64 opId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(user, opId)); } }
library ProtectedBoostableLib { using ECDSA for bytes32; function deleteOpHandle( address user, OpHandle memory opHandle, OpHandle[] storage opHandles, OpCounter storage opCounter, mapping(bytes32 => OpMetadata) storage opMetadata ) public { uint256 length = opHandles.length; assert(length > 0); uint64 minOpId; // becomes next LIFO uint64 maxOpId; // becomes next FIFO // Pending ops are capped to MAX_PENDING_OPS. We always perform // MIN(length, MAX_PENDING_OPS) look-ups to do a "swap-and-pop" and // for updating the opCounter LIFO/FIFO pointers. for (uint256 i = 0; i < length; i++) { uint64 currOpId = opHandles[i].opId; if (currOpId == opHandle.opId) { // Overwrite item at i with last opHandles[i] = opHandles[length - 1]; // Continue, to ignore this opId when updating // minOpId and maxOpId. continue; } // Update minOpId if (minOpId == 0 || currOpId < minOpId) { minOpId = currOpId; } // Update maxOpId if (currOpId > maxOpId) { maxOpId = currOpId; } } // Might be 0 when everything got finalized/reverted opCounter.nextFinalize = minOpId; // Might be 0 when everything got finalized/reverted opCounter.nextRevert = maxOpId; // Remove the last item opHandles.pop(); // Remove metadata delete opMetadata[_getOpKey(user, opHandle.opId)]; } function assertCanFinalize( OpMetadata memory metadata, IOptIn.OptInStatus memory optInStatus ) public view returns (uint64) { // Now there are three valid scenarios remaining: // // - msg.sender is the original booster // - op is expired // - getBoosterAddress returns a different booster than the original booster // // In the second and third case, anyone can call finalize. address originalBooster = metadata.booster; if (originalBooster == msg.sender) { return metadata.createdAt; // First case } address currentBooster = optInStatus.optedInTo; uint256 optOutPeriod = optInStatus.optOutPeriod; bool isExpired = block.timestamp >= metadata.createdAt + optOutPeriod; if (isExpired) { return metadata.createdAt; // Second case } if (currentBooster != originalBooster) { return metadata.createdAt; // Third case } revert("PB-4"); } function verifySignatureForRevert( address user, uint64 opTimestamp, IOptIn.OptInStatus memory optInStatus, bytes memory boosterMessage, address[] memory hasherContracts, Signature memory signature ) public { require(hasherContracts.length > 0, "PB-12"); // Result of hasher contract call uint64 signedAt; bytes32 boosterHash; bool signatureVerified; for (uint256 i = 0; i < hasherContracts.length; i++) { // Call into the hasher contract and take the first non-zero result. // The contract must implement the following function: // // decodeAndHashBoosterMessage( // address targetBooster, // bytes memory boosterMessage // ) // // If it doesn't, then the call will fail (success=false) and we try the next one. // If it succeeds (success = true), then we try to decode the result. // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory result) = address(hasherContracts[i]) .call( // keccak256("decodeAndHashBoosterMessage(address,bytes)") abi.encodeWithSelector( 0xaf6eec54, msg.sender, /* msg.sender becomes the target booster */ boosterMessage ) ); if (!success) { continue; } // The result is exactly 2 words long = 512 bits = 64 bytes // 32 bytes for the expected message hash // 8 bytes (padded to 32 bytes) for the expected timestamp if (result.length != 64) { continue; } // NOTE: A contract with malintent could return any hash that we would // try to recover against. But there is no harm done in doing so since // the user must have signed it. // // However, it might return an unrelated timestamp, that the user hasn't // signed - so it could prolong the expiry of a signature which is a valid // concern whose risk we minimize by using also the op timestamp which guarantees // that a signature eventually expires. // Decode and recover signer (boosterHash, signedAt) = abi.decode(result, (bytes32, uint64)); address signer = ecrecover( boosterHash, signature.v, signature.r, signature.s ); if (user != signer) { // NOTE: Currently, hardware wallets (e.g. Ledger, Trezor) do not support EIP712 signing (specifically `signTypedData_v4`). // However, a user can still sign the EIP712 hash with the caveat that it's signed using `personal_sign` which prepends // the prefix '"\x19Ethereum Signed Message:\n" + len(message)'. // // To still support that, we also add the prefix and try to use the recovered address instead: signer = ecrecover( boosterHash.toEthSignedMessageHash(), signature.v, signature.r, signature.s ); } // If we recovered `user` from the signature, then we have a valid signature. if (user == signer) { signatureVerified = true; break; } // Keep trying } // Revert if signature couldn't be verified with any of the returned hashes require(signatureVerified, "PB-8"); // Lastly, the current time must not be older than: // MIN(opTimestamp, signedAt) + optOutPeriod * 3 uint64 _now = uint64(block.timestamp); // The maximum age is equal to whichever is lowest: // opTimestamp + optOutPeriod * 3 // signedAt + optOutPeriod * 3 uint64 maximumAge; if (opTimestamp > signedAt) { maximumAge = signedAt + uint64(optInStatus.optOutPeriod * 3); } else { maximumAge = opTimestamp + uint64(optInStatus.optOutPeriod * 3); } require(_now <= maximumAge, "PB-11"); } function _getOpKey(address user, uint64 opId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(user, opId)); } }
5,386
50
// multiply a UQ112x112 by an int and decode, returning an int reverts on overflow
function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); }
function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); }
21,685
106
// swapAndLiquify takes the balance to be liquified and make sure it is equally distributed in BNB and Harold
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // 1/2 balance is sent to the marketing wallet, 1/2 is added to the liquidity pool uint256 marketingTokenBalance = contractTokenBalance.div(2); uint256 liquidityTokenBalance = contractTokenBalance.sub(marketingTokenBalance); uint256 tokenBalanceToLiquifyAsBNB = liquidityTokenBalance.div(2); uint256 tokenBalanceToLiquify = liquidityTokenBalance.sub(tokenBalanceToLiquifyAsBNB); uint256 initialBalance = address(this).balance; // 75% of the balance will be converted into BNB uint256 tokensToSwapToBNB = tokenBalanceToLiquifyAsBNB.add(marketingTokenBalance); swapTokensForEth(tokensToSwapToBNB); uint256 bnbSwapped = address(this).balance.sub(initialBalance); uint256 bnbToLiquify = bnbSwapped.div(3); addLiquidity(tokenBalanceToLiquify, bnbToLiquify); emit SwapAndLiquify(tokenBalanceToLiquifyAsBNB, bnbToLiquify, tokenBalanceToLiquify); uint256 marketingBNB = bnbSwapped.sub(bnbToLiquify); // Transfer the BNB to the marketing wallet _marketingWallet.transfer(marketingBNB); emit ToMarketing(marketingBNB); }
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // 1/2 balance is sent to the marketing wallet, 1/2 is added to the liquidity pool uint256 marketingTokenBalance = contractTokenBalance.div(2); uint256 liquidityTokenBalance = contractTokenBalance.sub(marketingTokenBalance); uint256 tokenBalanceToLiquifyAsBNB = liquidityTokenBalance.div(2); uint256 tokenBalanceToLiquify = liquidityTokenBalance.sub(tokenBalanceToLiquifyAsBNB); uint256 initialBalance = address(this).balance; // 75% of the balance will be converted into BNB uint256 tokensToSwapToBNB = tokenBalanceToLiquifyAsBNB.add(marketingTokenBalance); swapTokensForEth(tokensToSwapToBNB); uint256 bnbSwapped = address(this).balance.sub(initialBalance); uint256 bnbToLiquify = bnbSwapped.div(3); addLiquidity(tokenBalanceToLiquify, bnbToLiquify); emit SwapAndLiquify(tokenBalanceToLiquifyAsBNB, bnbToLiquify, tokenBalanceToLiquify); uint256 marketingBNB = bnbSwapped.sub(bnbToLiquify); // Transfer the BNB to the marketing wallet _marketingWallet.transfer(marketingBNB); emit ToMarketing(marketingBNB); }
10,560
29
// Fraction of interest currently set aside for reserves /
uint public reserveFactorMantissa;
uint public reserveFactorMantissa;
15,348
45
// can later be changed with {_setPendingOwner} and {_acceptOwner}. /
contract Ownable {
contract Ownable {
52,070
7
// require(_amount > 0 && _amount < 6); uint256 _random = uint256(keccak256(abi.encodePacked(index++, msg.sender, block.timestamp, blockhash(block.number-1)))); uint256 _random = random(string(abi.encodePacked(index++, msg.sender, block.timestamp, blockhash(block.number-1)))); _safeMint(_amount[i], _pickRandomUniqueId(random) uint256 hue = _pickRandomUniqueId(tokenId); _safeMint(msg.sender, hue); uint256 _random = random(string(abi.encodePacked(index++, msg.sender, block.timestamp, blockhash(block.number-1)))); tokenHue[tokenId] = _pickRandomUniqueId(tokenId);string memory tempURI = getURI(tokenHue[tokenId], tokenId); string memory tempURI = getURI(nextTokenIdToMint());
_setTokenURI(nextTokenIdToMint(), getURI(nextTokenIdToMint())); _safeMint(msg.sender, 1, "");
_setTokenURI(nextTokenIdToMint(), getURI(nextTokenIdToMint())); _safeMint(msg.sender, 1, "");
19,974
58
// now we need 5th power
quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta);
quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta);
33,626
26
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt256(wad.mul(RAY).sub(dai) / rate);
dart = toInt256(wad.mul(RAY).sub(dai) / rate);
27,533
102
// Admin Functions
function initialize( address __owner, address __guardian ) public
function initialize( address __owner, address __guardian ) public
6,186
186
// Return Kp/
function sg() external isReader view returns (int256) { return Kp; }
function sg() external isReader view returns (int256) { return Kp; }
24,125
2
// Events. /
event Repay(address indexed from, uint256 amount);
event Repay(address indexed from, uint256 amount);
21,263
70
// Function for use by the admin of the contract to add KYC Admins /
function addKYCAdmin(address KYCAdmin) public returns(uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, FailureInfo.KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED); } KYCAdmins[KYCAdmin] = true; emit KYCAdminAdded(KYCAdmin); return uint(Error.NO_ERROR); }
function addKYCAdmin(address KYCAdmin) public returns(uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, FailureInfo.KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED); } KYCAdmins[KYCAdmin] = true; emit KYCAdminAdded(KYCAdmin); return uint(Error.NO_ERROR); }
34,693
53
// Tells whether an operator is approved by a given owner _owner owner address which you want to query the approval of _operator operator address which you want to query the approval ofreturn bool whether the given operator is approved by the given owner /
function isApprovedForAll( address _owner, address _operator ) public view override returns (bool)
function isApprovedForAll( address _owner, address _operator ) public view override returns (bool)
13,496
32
// Send a notification to destination chain that some tokens were burned on this chain. destinationChainSelector destination chain CCIP selector. messageReceiver contract on destination chain to handle the message.
* @param data encoded burn data from {KreepyKrittersPortalEncoder-encodeBurn}. * @param extraArgs encoded CCIP extraArgs with gasLimit, strict mode and possibly future protocol options. */ function _notifyBurned( uint64 destinationChainSelector, address messageReceiver, bytes memory data, bytes memory extraArgs ) internal { Client.EVM2AnyMessage memory message = Client.EVM2AnyMessage({ receiver: abi.encode(messageReceiver), data: data, tokenAmounts: new Client.EVMTokenAmount[](0), extraArgs: extraArgs, feeToken: link }); bytes32 messageId = IRouterClient(i_router).ccipSend( destinationChainSelector, message ); emit BurnInitiated(msg.sender, destinationChainSelector, messageId); }
* @param data encoded burn data from {KreepyKrittersPortalEncoder-encodeBurn}. * @param extraArgs encoded CCIP extraArgs with gasLimit, strict mode and possibly future protocol options. */ function _notifyBurned( uint64 destinationChainSelector, address messageReceiver, bytes memory data, bytes memory extraArgs ) internal { Client.EVM2AnyMessage memory message = Client.EVM2AnyMessage({ receiver: abi.encode(messageReceiver), data: data, tokenAmounts: new Client.EVMTokenAmount[](0), extraArgs: extraArgs, feeToken: link }); bytes32 messageId = IRouterClient(i_router).ccipSend( destinationChainSelector, message ); emit BurnInitiated(msg.sender, destinationChainSelector, messageId); }
26,002
25
// Sets the values for {name} and {symbol}, initializes {decimals} witha default value of 18. To select a different value for {decimals}, use {_setupDecimals}. All three of these values are immutable: they can only be set once duringconstruction. /
constructor (string memory name, string memory symbol) public {
constructor (string memory name, string memory symbol) public {
41,648
94
// Refund all tokens for crowdsale to refund wallet.
token.transfer(crowdsaleOwner, _value);
token.transfer(crowdsaleOwner, _value);
42,925
79
// Internal function to set the token URI for a given token Reverts if the token ID does not exist _tokenId uint256 ID of the token to set its URI _uri string URI to assign /
function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; }
function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; }
43,415
32
// transmute will mint this token by consuming its transmuteSource tokens.
function transmute(uint256 amount, uint256 transmuteType) public { require(transmuteType == 0 || transmuteType == 1, "EtheleToken: Transmute type should be 0 or 1."); if (transmuteType == 0) { require(_transmuteSource1 != address(0) && _transmuteSource2 != address(0), "EtheleToken: Cannot transmute this."); EtheleToken(_transmuteSource1).burnFrom(msg.sender, amount); EtheleToken(_transmuteSource2).burnFrom(msg.sender, amount); _mint(msg.sender, amount); } else if (transmuteType == 1) { require(_transmuteSource3 != address(0) && _transmuteSource4 != address(0), "EtheleToken: Cannot transmute this."); EtheleToken(_transmuteSource3).burnFrom(msg.sender, amount); EtheleToken(_transmuteSource4).burnFrom(msg.sender, amount); _mint(msg.sender, amount); } }
function transmute(uint256 amount, uint256 transmuteType) public { require(transmuteType == 0 || transmuteType == 1, "EtheleToken: Transmute type should be 0 or 1."); if (transmuteType == 0) { require(_transmuteSource1 != address(0) && _transmuteSource2 != address(0), "EtheleToken: Cannot transmute this."); EtheleToken(_transmuteSource1).burnFrom(msg.sender, amount); EtheleToken(_transmuteSource2).burnFrom(msg.sender, amount); _mint(msg.sender, amount); } else if (transmuteType == 1) { require(_transmuteSource3 != address(0) && _transmuteSource4 != address(0), "EtheleToken: Cannot transmute this."); EtheleToken(_transmuteSource3).burnFrom(msg.sender, amount); EtheleToken(_transmuteSource4).burnFrom(msg.sender, amount); _mint(msg.sender, amount); } }
40,318
196
// Destroys `amount` tokens from `account`. Caller must have the {MinterRole}. /
function fundManagerBurnFrom(address account, uint256 amount) public onlyMinter {
function fundManagerBurnFrom(address account, uint256 amount) public onlyMinter {
2,247
180
// IAlchemistV2State/Alchemix Finance
interface IAlchemistV2State { /// @notice Defines underlying token parameters. struct UnderlyingTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // A coefficient used to normalize the token to a value comparable to the debt token. For example, if the // underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be // 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token. uint256 conversionFactor; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Defines yield token parameters. struct YieldTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // The associated underlying token that can be redeemed for the yield-token. address underlyingToken; // The adapter used by the system to wrap, unwrap, and lookup the conversion rate of this token into its // underlying token. address adapter; // The maximum percentage loss that is acceptable before disabling certain actions. uint256 maximumLoss; // The maximum value of yield tokens that the system can hold, measured in units of the underlying token. uint256 maximumExpectedValue; // The percent of credit that will be unlocked per block. The representation of this value is a 18 decimal // fixed point integer. uint256 creditUnlockRate; // The current balance of yield tokens which are held by users. uint256 activeBalance; // The current balance of yield tokens which are earmarked to be harvested by the system at a later time. uint256 harvestableBalance; // The total number of shares that have been minted for this token. uint256 totalShares; // The expected value of the tokens measured in underlying tokens. This value controls how much of the token // can be harvested. When users deposit yield tokens, it increases the expected value by how much the tokens // are exchangeable for in the underlying token. When users withdraw yield tokens, it decreases the expected // value by how much the tokens are exchangeable for in the underlying token. uint256 expectedValue; // The current amount of credit which is will be distributed over time to depositors. uint256 pendingCredit; // The amount of the pending credit that has been distributed. uint256 distributedCredit; // The block number which the last credit distribution occurred. uint256 lastDistributionBlock; // The total accrued weight. This is used to calculate how much credit a user has been granted over time. The // representation of this value is a 18 decimal fixed point integer. uint256 accruedWeight; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Gets the address of the admin. /// /// @return admin The admin address. function admin() external view returns (address admin); /// @notice Gets the address of the pending administrator. /// /// @return pendingAdmin The pending administrator address. function pendingAdmin() external view returns (address pendingAdmin); /// @notice Gets if an address is a sentinel. /// /// @param sentinel The address to check. /// /// @return isSentinel If the address is a sentinel. function sentinels(address sentinel) external view returns (bool isSentinel); /// @notice Gets if an address is a keeper. /// /// @param keeper The address to check. /// /// @return isKeeper If the address is a keeper function keepers(address keeper) external view returns (bool isKeeper); /// @notice Gets the address of the transmuter. /// /// @return transmuter The transmuter address. function transmuter() external view returns (address transmuter); /// @notice Gets the minimum collateralization. /// /// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt. /// /// @dev The value returned is a 18 decimal fixed point integer. /// /// @return minimumCollateralization The minimum collateralization. function minimumCollateralization() external view returns (uint256 minimumCollateralization); /// @notice Gets the protocol fee. /// /// @return protocolFee The protocol fee. function protocolFee() external view returns (uint256 protocolFee); /// @notice Gets the protocol fee receiver. /// /// @return protocolFeeReceiver The protocol fee receiver. function protocolFeeReceiver() external view returns (address protocolFeeReceiver); /// @notice Gets the address of the whitelist contract. /// /// @return whitelist The address of the whitelist contract. function whitelist() external view returns (address whitelist); /// @notice Gets the conversion rate of underlying tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of underlying tokens per share. function getUnderlyingTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the conversion rate of yield tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of yield tokens per share. function getYieldTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the supported underlying tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported underlying tokens. function getSupportedUnderlyingTokens() external view returns (address[] memory tokens); /// @notice Gets the supported yield tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported yield tokens. function getSupportedYieldTokens() external view returns (address[] memory tokens); /// @notice Gets if an underlying token is supported. /// /// @param underlyingToken The address of the underlying token to check. /// /// @return isSupported If the underlying token is supported. function isSupportedUnderlyingToken(address underlyingToken) external view returns (bool isSupported); /// @notice Gets if a yield token is supported. /// /// @param yieldToken The address of the yield token to check. /// /// @return isSupported If the yield token is supported. function isSupportedYieldToken(address yieldToken) external view returns (bool isSupported); /// @notice Gets information about the account owned by `owner`. /// /// @param owner The address that owns the account. /// /// @return debt The unrealized amount of debt that the account had incurred. /// @return depositedTokens The yield tokens that the owner has deposited. function accounts(address owner) external view returns (int256 debt, address[] memory depositedTokens); /// @notice Gets information about a yield token position for the account owned by `owner`. /// /// @param owner The address that owns the account. /// @param yieldToken The address of the yield token to get the position of. /// /// @return shares The amount of shares of that `owner` owns of the yield token. /// @return lastAccruedWeight The last recorded accrued weight of the yield token. function positions(address owner, address yieldToken) external view returns ( uint256 shares, uint256 lastAccruedWeight ); /// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to mint on behalf of `owner`. /// /// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`. function mintAllowance(address owner, address spender) external view returns (uint256 allowance); /// @notice Gets the amount of shares of `yieldToken` that `spender` is allowed to withdraw on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to withdraw on behalf of `owner`. /// @param yieldToken The address of the yield token. /// /// @return allowance The amount of shares that `spender` can withdraw on behalf of `owner`. function withdrawAllowance(address owner, address spender, address yieldToken) external view returns (uint256 allowance); /// @notice Gets the parameters of an underlying token. /// /// @param underlyingToken The address of the underlying token. /// /// @return params The underlying token parameters. function getUnderlyingTokenParameters(address underlyingToken) external view returns (UnderlyingTokenParams memory params); /// @notice Get the parameters and state of a yield-token. /// /// @param yieldToken The address of the yield token. /// /// @return params The yield token parameters. function getYieldTokenParameters(address yieldToken) external view returns (YieldTokenParams memory params); /// @notice Gets current limit, maximum, and rate of the minting limiter. /// /// @return currentLimit The current amount of debt tokens that can be minted. /// @return rate The maximum possible amount of tokens that can be liquidated at a time. /// @return maximum The highest possible maximum amount of debt tokens that can be minted at a time. function getMintLimitInfo() external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of a repay limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be repaid. /// @return rate The rate at which the the current limit increases back to its maximum in tokens per block. /// @return maximum The maximum possible amount of tokens that can be repaid at a time. function getRepayLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of the liquidation limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be liquidated. /// @return rate The rate at which the function increases back to its maximum limit (tokens / block). /// @return maximum The highest possible maximum amount of debt tokens that can be liquidated at a time. function getLiquidationLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); }
interface IAlchemistV2State { /// @notice Defines underlying token parameters. struct UnderlyingTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // A coefficient used to normalize the token to a value comparable to the debt token. For example, if the // underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be // 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token. uint256 conversionFactor; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Defines yield token parameters. struct YieldTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // The associated underlying token that can be redeemed for the yield-token. address underlyingToken; // The adapter used by the system to wrap, unwrap, and lookup the conversion rate of this token into its // underlying token. address adapter; // The maximum percentage loss that is acceptable before disabling certain actions. uint256 maximumLoss; // The maximum value of yield tokens that the system can hold, measured in units of the underlying token. uint256 maximumExpectedValue; // The percent of credit that will be unlocked per block. The representation of this value is a 18 decimal // fixed point integer. uint256 creditUnlockRate; // The current balance of yield tokens which are held by users. uint256 activeBalance; // The current balance of yield tokens which are earmarked to be harvested by the system at a later time. uint256 harvestableBalance; // The total number of shares that have been minted for this token. uint256 totalShares; // The expected value of the tokens measured in underlying tokens. This value controls how much of the token // can be harvested. When users deposit yield tokens, it increases the expected value by how much the tokens // are exchangeable for in the underlying token. When users withdraw yield tokens, it decreases the expected // value by how much the tokens are exchangeable for in the underlying token. uint256 expectedValue; // The current amount of credit which is will be distributed over time to depositors. uint256 pendingCredit; // The amount of the pending credit that has been distributed. uint256 distributedCredit; // The block number which the last credit distribution occurred. uint256 lastDistributionBlock; // The total accrued weight. This is used to calculate how much credit a user has been granted over time. The // representation of this value is a 18 decimal fixed point integer. uint256 accruedWeight; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Gets the address of the admin. /// /// @return admin The admin address. function admin() external view returns (address admin); /// @notice Gets the address of the pending administrator. /// /// @return pendingAdmin The pending administrator address. function pendingAdmin() external view returns (address pendingAdmin); /// @notice Gets if an address is a sentinel. /// /// @param sentinel The address to check. /// /// @return isSentinel If the address is a sentinel. function sentinels(address sentinel) external view returns (bool isSentinel); /// @notice Gets if an address is a keeper. /// /// @param keeper The address to check. /// /// @return isKeeper If the address is a keeper function keepers(address keeper) external view returns (bool isKeeper); /// @notice Gets the address of the transmuter. /// /// @return transmuter The transmuter address. function transmuter() external view returns (address transmuter); /// @notice Gets the minimum collateralization. /// /// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt. /// /// @dev The value returned is a 18 decimal fixed point integer. /// /// @return minimumCollateralization The minimum collateralization. function minimumCollateralization() external view returns (uint256 minimumCollateralization); /// @notice Gets the protocol fee. /// /// @return protocolFee The protocol fee. function protocolFee() external view returns (uint256 protocolFee); /// @notice Gets the protocol fee receiver. /// /// @return protocolFeeReceiver The protocol fee receiver. function protocolFeeReceiver() external view returns (address protocolFeeReceiver); /// @notice Gets the address of the whitelist contract. /// /// @return whitelist The address of the whitelist contract. function whitelist() external view returns (address whitelist); /// @notice Gets the conversion rate of underlying tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of underlying tokens per share. function getUnderlyingTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the conversion rate of yield tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of yield tokens per share. function getYieldTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the supported underlying tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported underlying tokens. function getSupportedUnderlyingTokens() external view returns (address[] memory tokens); /// @notice Gets the supported yield tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported yield tokens. function getSupportedYieldTokens() external view returns (address[] memory tokens); /// @notice Gets if an underlying token is supported. /// /// @param underlyingToken The address of the underlying token to check. /// /// @return isSupported If the underlying token is supported. function isSupportedUnderlyingToken(address underlyingToken) external view returns (bool isSupported); /// @notice Gets if a yield token is supported. /// /// @param yieldToken The address of the yield token to check. /// /// @return isSupported If the yield token is supported. function isSupportedYieldToken(address yieldToken) external view returns (bool isSupported); /// @notice Gets information about the account owned by `owner`. /// /// @param owner The address that owns the account. /// /// @return debt The unrealized amount of debt that the account had incurred. /// @return depositedTokens The yield tokens that the owner has deposited. function accounts(address owner) external view returns (int256 debt, address[] memory depositedTokens); /// @notice Gets information about a yield token position for the account owned by `owner`. /// /// @param owner The address that owns the account. /// @param yieldToken The address of the yield token to get the position of. /// /// @return shares The amount of shares of that `owner` owns of the yield token. /// @return lastAccruedWeight The last recorded accrued weight of the yield token. function positions(address owner, address yieldToken) external view returns ( uint256 shares, uint256 lastAccruedWeight ); /// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to mint on behalf of `owner`. /// /// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`. function mintAllowance(address owner, address spender) external view returns (uint256 allowance); /// @notice Gets the amount of shares of `yieldToken` that `spender` is allowed to withdraw on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to withdraw on behalf of `owner`. /// @param yieldToken The address of the yield token. /// /// @return allowance The amount of shares that `spender` can withdraw on behalf of `owner`. function withdrawAllowance(address owner, address spender, address yieldToken) external view returns (uint256 allowance); /// @notice Gets the parameters of an underlying token. /// /// @param underlyingToken The address of the underlying token. /// /// @return params The underlying token parameters. function getUnderlyingTokenParameters(address underlyingToken) external view returns (UnderlyingTokenParams memory params); /// @notice Get the parameters and state of a yield-token. /// /// @param yieldToken The address of the yield token. /// /// @return params The yield token parameters. function getYieldTokenParameters(address yieldToken) external view returns (YieldTokenParams memory params); /// @notice Gets current limit, maximum, and rate of the minting limiter. /// /// @return currentLimit The current amount of debt tokens that can be minted. /// @return rate The maximum possible amount of tokens that can be liquidated at a time. /// @return maximum The highest possible maximum amount of debt tokens that can be minted at a time. function getMintLimitInfo() external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of a repay limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be repaid. /// @return rate The rate at which the the current limit increases back to its maximum in tokens per block. /// @return maximum The maximum possible amount of tokens that can be repaid at a time. function getRepayLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of the liquidation limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be liquidated. /// @return rate The rate at which the function increases back to its maximum limit (tokens / block). /// @return maximum The highest possible maximum amount of debt tokens that can be liquidated at a time. function getLiquidationLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); }
56,733
9
// Quickly check the Ether balance, as well as the balance of each/ supplied ERC20 token, for a collection of accounts./0age
contract AccountWatcherV2 is AccountWatcherInterface { function balancesOf( ERC20Interface[] calldata tokens, address[] calldata accounts ) external view override returns (Account[] memory) { Account[] memory accountBalances = new Account[](accounts.length); for (uint256 i = 0; i < accounts.length; i++) { address account = accounts[i]; TokenBalance[] memory tokenBalances = new TokenBalance[](tokens.length); for (uint256 j = 0; j < tokens.length; j++) { ERC20Interface token = tokens[j]; (bool success, bytes memory returnData) = address(token).staticcall( abi.encodeWithSelector(token.balanceOf.selector, account) ); if (success && returnData.length >= 32) { TokenBalance memory tokenBalance; tokenBalance.callSuccess = true; tokenBalance.balance = abi.decode(returnData, (uint256)); tokenBalances[j] = tokenBalance; } } accountBalances[i].etherBalance = account.balance; accountBalances[i].tokenBalances = tokenBalances; } return accountBalances; } }
contract AccountWatcherV2 is AccountWatcherInterface { function balancesOf( ERC20Interface[] calldata tokens, address[] calldata accounts ) external view override returns (Account[] memory) { Account[] memory accountBalances = new Account[](accounts.length); for (uint256 i = 0; i < accounts.length; i++) { address account = accounts[i]; TokenBalance[] memory tokenBalances = new TokenBalance[](tokens.length); for (uint256 j = 0; j < tokens.length; j++) { ERC20Interface token = tokens[j]; (bool success, bytes memory returnData) = address(token).staticcall( abi.encodeWithSelector(token.balanceOf.selector, account) ); if (success && returnData.length >= 32) { TokenBalance memory tokenBalance; tokenBalance.callSuccess = true; tokenBalance.balance = abi.decode(returnData, (uint256)); tokenBalances[j] = tokenBalance; } } accountBalances[i].etherBalance = account.balance; accountBalances[i].tokenBalances = tokenBalances; } return accountBalances; } }
21,055
2
// helpers
function __i (uint256 i1, string memory s) internal pure returns (string memory) { return string(abi.encodePacked(i1, s)); }
function __i (uint256 i1, string memory s) internal pure returns (string memory) { return string(abi.encodePacked(i1, s)); }
42,854
401
// Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
9,547
5
// Burns user variable debt- Only callable by the LendingPool user The user whose debt is getting burned amount The amount getting burned index The variable debt index of the reserve /
) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); }
) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); }
50,173
12
// Super Token Factory// Get the super token factoryreturn factory The factory /
function getSuperTokenFactory() external view returns (ISuperTokenFactory factory);
function getSuperTokenFactory() external view returns (ISuperTokenFactory factory);
6,098
162
// DataExchange Wibson Development Team <developers@wibson.org> `DataExchange` is the core contract of the Wibson Protocol.This allows the creation, management, and tracking of DataOrders. This contract also contains some helper methods to access the data needed by the different parties involved in the Protocol. /
contract DataExchange is TokenDestructible, Pausable { using SafeMath for uint256; using MultiMap for MultiMap.MapStorage; event NotaryRegistered(address indexed notary); event NotaryUpdated(address indexed notary); event NotaryUnregistered(address indexed notary); event NewOrder(address indexed orderAddr); event NotaryAddedToOrder(address indexed orderAddr, address indexed notary); event DataAdded(address indexed orderAddr, address indexed seller); event TransactionCompleted(address indexed orderAddr, address indexed seller); event RefundedToBuyer(address indexed orderAddr, address indexed buyer); event OrderClosed(address indexed orderAddr); struct NotaryInfo { address addr; string name; string notaryUrl; string publicKey; } MultiMap.MapStorage openOrders; MultiMap.MapStorage allowedNotaries; mapping(address => address[]) public ordersBySeller; mapping(address => address[]) public ordersByNotary; mapping(address => address[]) public ordersByBuyer; mapping(address => NotaryInfo) internal notaryInfo; // Tracks the orders created by this contract. mapping(address => bool) private orders; // @dev buyerBalance Keeps track of the buyer's balance per order-seller. // TODO: Is there a better way to do this? mapping( address => mapping(address => mapping(address => uint256)) ) public buyerBalance; // @dev buyerRemainingBudgetForAudits Keeps track of the buyer's remaining // budget from the initial one set on the `DataOrder` mapping(address => mapping(address => uint256)) public buyerRemainingBudgetForAudits; modifier validAddress(address addr) { require(addr != address(0)); require(addr != address(this)); _; } modifier isOrderLegit(address order) { require(orders[order]); _; } // @dev token A WIBToken implementation of an ERC20 standard token. WIBToken token; // @dev The minimum for initial budget for audits per `DataOrder`. uint256 public minimumInitialBudgetForAudits; /** * @notice Contract constructor. * @param tokenAddress Address of the WIBToken token address. * @param ownerAddress Address of the DataExchange owner. */ constructor( address tokenAddress, address ownerAddress ) public validAddress(tokenAddress) validAddress(ownerAddress) { require(tokenAddress != ownerAddress); token = WIBToken(tokenAddress); minimumInitialBudgetForAudits = 0; transferOwnership(ownerAddress); } /** * @notice Registers a new notary or replaces an already existing one. * @dev At least one notary is needed to enable `DataExchange` operation. * @param notary Address of a Notary to add. * @param name Name Of the Notary. * @param notaryUrl Public URL of the notary where the data must be sent. * @param publicKey PublicKey used by the Notary. * @return true if the notary was successfully registered, reverts otherwise. */ function registerNotary( address notary, string name, string notaryUrl, string publicKey ) public onlyOwner whenNotPaused validAddress(notary) returns (bool) { bool isNew = notaryInfo[notary].addr == address(0); require(allowedNotaries.insert(notary)); notaryInfo[notary] = NotaryInfo( notary, name, notaryUrl, publicKey ); if (isNew) { emit NotaryRegistered(notary); } else { emit NotaryUpdated(notary); } return true; } /** * @notice Unregisters an existing notary. * @param notary Address of a Notary to unregister. * @return true if the notary was successfully unregistered, reverts otherwise. */ function unregisterNotary( address notary ) public onlyOwner whenNotPaused validAddress(notary) returns (bool) { require(allowedNotaries.remove(notary)); emit NotaryUnregistered(notary); return true; } /** * @notice Sets the minimum initial budget for audits to be placed by a buyer * on DataOrder creation. * @dev The initial budget for audit is used as a preventive method to reduce * spam DataOrders in the network. * @param _minimumInitialBudgetForAudits The new minimum for initial budget for * audits per DataOrder. * @return true if the value was successfully set, reverts otherwise. */ function setMinimumInitialBudgetForAudits( uint256 _minimumInitialBudgetForAudits ) public onlyOwner whenNotPaused returns (bool) { minimumInitialBudgetForAudits = _minimumInitialBudgetForAudits; return true; } /** * @notice Creates a new DataOrder. * @dev The `msg.sender` will become the buyer of the order. * @param filters Target audience of the order. * @param dataRequest Requested data type (Geolocation, Facebook, etc). * @param price Price per added Data Response. * @param initialBudgetForAudits The initial budget set for future audits. * @param termsAndConditions Buyer's terms and conditions for the order. * @param buyerURL Public URL of the buyer where the data must be sent. * @param publicKey Public Key of the buyer, which will be used to encrypt the * data to be sent. * @return The address of the newly created DataOrder. If the DataOrder could * not be created, reverts. */ function newOrder( string filters, string dataRequest, uint256 price, uint256 initialBudgetForAudits, string termsAndConditions, string buyerURL, string publicKey ) public whenNotPaused returns (address) { require(initialBudgetForAudits >= minimumInitialBudgetForAudits); require(token.allowance(msg.sender, this) >= initialBudgetForAudits); address newOrderAddr = new DataOrder( msg.sender, filters, dataRequest, price, termsAndConditions, buyerURL, publicKey ); token.transferFrom(msg.sender, this, initialBudgetForAudits); buyerRemainingBudgetForAudits[msg.sender][newOrderAddr] = initialBudgetForAudits; ordersByBuyer[msg.sender].push(newOrderAddr); orders[newOrderAddr] = true; emit NewOrder(newOrderAddr); return newOrderAddr; } /** * @notice Adds a notary to the Data Order. * @dev The `msg.sender` must be the buyer. * @param orderAddr Order Address to accept notarize. * @param notary Notary address. * @param responsesPercentage Percentage of `DataResponses` to audit per DataOrder. * Value must be between 0 and 100. * @param notarizationFee Fee to be charged per validation done. * @param notarizationTermsOfService Notary's terms and conditions for the order. * @param notarySignature Notary's signature over the other arguments. * @return true if the Notary was added successfully, reverts otherwise. */ function addNotaryToOrder( address orderAddr, address notary, uint256 responsesPercentage, uint256 notarizationFee, string notarizationTermsOfService, bytes notarySignature ) public whenNotPaused isOrderLegit(orderAddr) validAddress(notary) returns (bool) { DataOrder order = DataOrder(orderAddr); address buyer = order.buyer(); require(msg.sender == buyer); require(!order.hasNotaryBeenAdded(notary)); require(allowedNotaries.exist(notary)); require( CryptoUtils.isNotaryAdditionValid( orderAddr, notary, responsesPercentage, notarizationFee, notarizationTermsOfService, notarySignature ) ); bool okay = order.addNotary( notary, responsesPercentage, notarizationFee, notarizationTermsOfService ); if (okay) { openOrders.insert(orderAddr); ordersByNotary[notary].push(orderAddr); emit NotaryAddedToOrder(order, notary); } return okay; } /** * @notice Adds a new DataResponse to the given order. * @dev 1. The `msg.sender` must be the buyer of the order. * 2. The buyer must allow the DataExchange to withdraw the price of the * order. * @param orderAddr Order address where the DataResponse must be added. * @param seller Address of the Seller. * @param notary Notary address that the Seller chose to use as notarizer, * this must be one within the allowed notaries and within the * DataOrder's notaries. * @param dataHash Hash of the data that must be sent, this is a SHA256. * @param signature Signature of DataResponse. * @return true if the DataResponse was set successfully, reverts otherwise. */ function addDataResponseToOrder( address orderAddr, address seller, address notary, string dataHash, bytes signature ) public whenNotPaused isOrderLegit(orderAddr) returns (bool) { DataOrder order = DataOrder(orderAddr); address buyer = order.buyer(); require(msg.sender == buyer); allDistinct( [ orderAddr, buyer, seller, notary, address(this) ] ); require(order.hasNotaryBeenAdded(notary)); require( CryptoUtils.isDataResponseValid( orderAddr, seller, notary, dataHash, signature ) ); bool okay = order.addDataResponse( seller, notary, dataHash ); require(okay); chargeBuyer(order, seller); ordersBySeller[seller].push(orderAddr); emit DataAdded(order, seller); return true; } /** * @notice Closes a DataResponse. * @dev Once the buyer receives the seller's data and checks that it is valid * or not, he must close the DataResponse signaling the result. * 1. This method requires an offline signature from the notary set in * the DataResponse, which will indicate the audit result or if * the data was not audited at all. * - If the notary did not audit the data or it verifies that it was * valid, funds will be sent to the Seller. * - If the notary signals the data as invalid, funds will be * handed back to the Buyer. * - Otherwise, funds will be locked at the `DataExchange` contract * until the issue is solved. * 2. This also works as a pause mechanism in case the system is * working under abnormal scenarios while allowing the parties to keep * exchanging information without losing their funds until the system * is back up. * 3. The `msg.sender` must be the buyer or the notary in case the * former does not show up. Only through the notary's signature it is * decided who must receive the funds. * @param orderAddr Order address where the DataResponse belongs to. * @param seller Seller address. * @param wasAudited Indicates whether the data was audited or not. * @param isDataValid Indicates the result of the audit, if happened. * @param notarySignature Off-chain Notary signature * @return true if the DataResponse was successfully closed, reverts otherwise. */ function closeDataResponse( address orderAddr, address seller, bool wasAudited, bool isDataValid, bytes notarySignature ) public whenNotPaused isOrderLegit(orderAddr) returns (bool) { DataOrder order = DataOrder(orderAddr); address buyer = order.buyer(); require(order.hasSellerBeenAccepted(seller)); address notary = order.getNotaryForSeller(seller); require(msg.sender == buyer || msg.sender == notary); require( CryptoUtils.isNotaryVeredictValid( orderAddr, seller, notary, wasAudited, isDataValid, notarySignature ) ); bool transactionCompleted = !wasAudited || isDataValid; require(order.closeDataResponse(seller, transactionCompleted)); payPlayers( order, buyer, seller, notary, wasAudited, isDataValid ); if (transactionCompleted) { emit TransactionCompleted(order, seller); } else { emit RefundedToBuyer(order, buyer); } return true; } /** * @notice Closes the DataOrder. * @dev Onces the data is closed it will no longer accept new DataResponses. * The `msg.sender` must be the buyer of the order or the owner of the * contract in a emergency case. * @param orderAddr Order address to close. * @return true if the DataOrder was successfully closed, reverts otherwise. */ function closeOrder( address orderAddr ) public whenNotPaused isOrderLegit(orderAddr) returns (bool) { require(openOrders.exist(orderAddr)); DataOrder order = DataOrder(orderAddr); address buyer = order.buyer(); require(msg.sender == buyer || msg.sender == owner); bool okay = order.close(); if (okay) { // remaining budget for audits go back to buyer. uint256 remainingBudget = buyerRemainingBudgetForAudits[buyer][order]; buyerRemainingBudgetForAudits[buyer][order] = 0; require(token.transfer(buyer, remainingBudget)); openOrders.remove(orderAddr); emit OrderClosed(orderAddr); } return okay; } /** * @notice Gets all the data orders associated with a notary. * @param notary Notary address to get orders for. * @return A list of DataOrder addresses. */ function getOrdersForNotary( address notary ) public view validAddress(notary) returns (address[]) { return ordersByNotary[notary]; } /** * @notice Gets all the data orders associated with a seller. * @param seller Seller address to get orders for. * @return List of DataOrder addresses. */ function getOrdersForSeller( address seller ) public view validAddress(seller) returns (address[]) { return ordersBySeller[seller]; } /** * @notice Gets all the data orders associated with a buyer. * @param buyer Buyer address to get orders for. * @return List of DataOrder addresses. */ function getOrdersForBuyer( address buyer ) public view validAddress(buyer) returns (address[]) { return ordersByBuyer[buyer]; } /** * @notice Gets all the open data orders, that is all the DataOrders that are * still receiving new DataResponses. * @return List of DataOrder addresses. */ function getOpenOrders() public view returns (address[]) { return openOrders.addresses; } /** * @dev Gets the list of allowed notaries. * @return List of notary addresses. */ function getAllowedNotaries() public view returns (address[]) { return allowedNotaries.addresses; } /** * @dev Gets information about a give notary. * @param notary Notary address to get info for. * @return Notary information (address, name, notaryUrl, publicKey, isActive). */ function getNotaryInfo( address notary ) public view validAddress(notary) returns (address, string, string, string, bool) { NotaryInfo memory info = notaryInfo[notary]; return ( info.addr, info.name, info.notaryUrl, info.publicKey, allowedNotaries.exist(notary) ); } /** * @dev Requires that five addresses are distinct between themselves and zero. * @param addresses array of five addresses to explore. */ function allDistinct(address[5] addresses) private pure { for (uint i = 0; i < addresses.length; i++) { require(addresses[i] != address(0)); for (uint j = i + 1; j < addresses.length; j++) { // solium-disable-line zeppelin/no-arithmetic-operations require(addresses[i] != addresses[j]); } } } /** * @dev Charges a buyer the final charges for a given `DataResponse`. * @notice 1. Tokens are held in the DataExchange contract until players are paid. * 2. This function follows a basic invoice flow: * * DataOrder price * + Notarization fee * ------------------ * Total charges * - Prepaid charges (Minimum between Notarization fee and Buyer remaining budget) * ------------------ * Final charges * * @param order DataOrder to which the DataResponse applies. * @param seller Address of the Seller. */ function chargeBuyer(DataOrder order, address seller) private whenNotPaused { address buyer = order.buyer(); address notary = order.getNotaryForSeller(seller); uint256 remainingBudget = buyerRemainingBudgetForAudits[buyer][order]; uint256 orderPrice = order.price(); (,, uint256 notarizationFee,,) = order.getNotaryInfo(notary); uint256 totalCharges = orderPrice.add(notarizationFee); uint256 prePaid = Math.min256(notarizationFee, remainingBudget); uint256 finalCharges = totalCharges.sub(prePaid); buyerRemainingBudgetForAudits[buyer][order] = remainingBudget.sub(prePaid); require(token.transferFrom(buyer, this, finalCharges)); // Bookkeeping of the available tokens paid by the Buyer and now in control // of the DataExchange takes into account the total charges (final + pre-paid) buyerBalance[buyer][order][seller] = buyerBalance[buyer][order][seller].add(totalCharges); } /** * @dev Pays the seller, notary and/or buyer according to the notary's veredict. * @param order DataOrder to which the payments apply. * @param buyer Address of the Buyer. * @param seller Address of the Seller. * @param notary Address of the Notary. * @param wasAudited Indicates whether the data was audited or not. * @param isDataValid Indicates the result of the audit, if happened. */ function payPlayers( DataOrder order, address buyer, address seller, address notary, bool wasAudited, bool isDataValid ) private whenNotPaused { uint256 orderPrice = order.price(); (,, uint256 notarizationFee,,) = order.getNotaryInfo(notary); uint256 totalCharges = orderPrice.add(notarizationFee); require(buyerBalance[buyer][order][seller] >= totalCharges); buyerBalance[buyer][order][seller] = buyerBalance[buyer][order][seller].sub(totalCharges); // if no notarization was done, notarization fee tokens go back to buyer. address notarizationFeeReceiver = wasAudited ? notary : buyer; // if no notarization was done or data is valid, tokens go to the seller address orderPriceReceiver = (!wasAudited || isDataValid) ? seller : buyer; require(token.transfer(notarizationFeeReceiver, notarizationFee)); require(token.transfer(orderPriceReceiver, orderPrice)); } }
contract DataExchange is TokenDestructible, Pausable { using SafeMath for uint256; using MultiMap for MultiMap.MapStorage; event NotaryRegistered(address indexed notary); event NotaryUpdated(address indexed notary); event NotaryUnregistered(address indexed notary); event NewOrder(address indexed orderAddr); event NotaryAddedToOrder(address indexed orderAddr, address indexed notary); event DataAdded(address indexed orderAddr, address indexed seller); event TransactionCompleted(address indexed orderAddr, address indexed seller); event RefundedToBuyer(address indexed orderAddr, address indexed buyer); event OrderClosed(address indexed orderAddr); struct NotaryInfo { address addr; string name; string notaryUrl; string publicKey; } MultiMap.MapStorage openOrders; MultiMap.MapStorage allowedNotaries; mapping(address => address[]) public ordersBySeller; mapping(address => address[]) public ordersByNotary; mapping(address => address[]) public ordersByBuyer; mapping(address => NotaryInfo) internal notaryInfo; // Tracks the orders created by this contract. mapping(address => bool) private orders; // @dev buyerBalance Keeps track of the buyer's balance per order-seller. // TODO: Is there a better way to do this? mapping( address => mapping(address => mapping(address => uint256)) ) public buyerBalance; // @dev buyerRemainingBudgetForAudits Keeps track of the buyer's remaining // budget from the initial one set on the `DataOrder` mapping(address => mapping(address => uint256)) public buyerRemainingBudgetForAudits; modifier validAddress(address addr) { require(addr != address(0)); require(addr != address(this)); _; } modifier isOrderLegit(address order) { require(orders[order]); _; } // @dev token A WIBToken implementation of an ERC20 standard token. WIBToken token; // @dev The minimum for initial budget for audits per `DataOrder`. uint256 public minimumInitialBudgetForAudits; /** * @notice Contract constructor. * @param tokenAddress Address of the WIBToken token address. * @param ownerAddress Address of the DataExchange owner. */ constructor( address tokenAddress, address ownerAddress ) public validAddress(tokenAddress) validAddress(ownerAddress) { require(tokenAddress != ownerAddress); token = WIBToken(tokenAddress); minimumInitialBudgetForAudits = 0; transferOwnership(ownerAddress); } /** * @notice Registers a new notary or replaces an already existing one. * @dev At least one notary is needed to enable `DataExchange` operation. * @param notary Address of a Notary to add. * @param name Name Of the Notary. * @param notaryUrl Public URL of the notary where the data must be sent. * @param publicKey PublicKey used by the Notary. * @return true if the notary was successfully registered, reverts otherwise. */ function registerNotary( address notary, string name, string notaryUrl, string publicKey ) public onlyOwner whenNotPaused validAddress(notary) returns (bool) { bool isNew = notaryInfo[notary].addr == address(0); require(allowedNotaries.insert(notary)); notaryInfo[notary] = NotaryInfo( notary, name, notaryUrl, publicKey ); if (isNew) { emit NotaryRegistered(notary); } else { emit NotaryUpdated(notary); } return true; } /** * @notice Unregisters an existing notary. * @param notary Address of a Notary to unregister. * @return true if the notary was successfully unregistered, reverts otherwise. */ function unregisterNotary( address notary ) public onlyOwner whenNotPaused validAddress(notary) returns (bool) { require(allowedNotaries.remove(notary)); emit NotaryUnregistered(notary); return true; } /** * @notice Sets the minimum initial budget for audits to be placed by a buyer * on DataOrder creation. * @dev The initial budget for audit is used as a preventive method to reduce * spam DataOrders in the network. * @param _minimumInitialBudgetForAudits The new minimum for initial budget for * audits per DataOrder. * @return true if the value was successfully set, reverts otherwise. */ function setMinimumInitialBudgetForAudits( uint256 _minimumInitialBudgetForAudits ) public onlyOwner whenNotPaused returns (bool) { minimumInitialBudgetForAudits = _minimumInitialBudgetForAudits; return true; } /** * @notice Creates a new DataOrder. * @dev The `msg.sender` will become the buyer of the order. * @param filters Target audience of the order. * @param dataRequest Requested data type (Geolocation, Facebook, etc). * @param price Price per added Data Response. * @param initialBudgetForAudits The initial budget set for future audits. * @param termsAndConditions Buyer's terms and conditions for the order. * @param buyerURL Public URL of the buyer where the data must be sent. * @param publicKey Public Key of the buyer, which will be used to encrypt the * data to be sent. * @return The address of the newly created DataOrder. If the DataOrder could * not be created, reverts. */ function newOrder( string filters, string dataRequest, uint256 price, uint256 initialBudgetForAudits, string termsAndConditions, string buyerURL, string publicKey ) public whenNotPaused returns (address) { require(initialBudgetForAudits >= minimumInitialBudgetForAudits); require(token.allowance(msg.sender, this) >= initialBudgetForAudits); address newOrderAddr = new DataOrder( msg.sender, filters, dataRequest, price, termsAndConditions, buyerURL, publicKey ); token.transferFrom(msg.sender, this, initialBudgetForAudits); buyerRemainingBudgetForAudits[msg.sender][newOrderAddr] = initialBudgetForAudits; ordersByBuyer[msg.sender].push(newOrderAddr); orders[newOrderAddr] = true; emit NewOrder(newOrderAddr); return newOrderAddr; } /** * @notice Adds a notary to the Data Order. * @dev The `msg.sender` must be the buyer. * @param orderAddr Order Address to accept notarize. * @param notary Notary address. * @param responsesPercentage Percentage of `DataResponses` to audit per DataOrder. * Value must be between 0 and 100. * @param notarizationFee Fee to be charged per validation done. * @param notarizationTermsOfService Notary's terms and conditions for the order. * @param notarySignature Notary's signature over the other arguments. * @return true if the Notary was added successfully, reverts otherwise. */ function addNotaryToOrder( address orderAddr, address notary, uint256 responsesPercentage, uint256 notarizationFee, string notarizationTermsOfService, bytes notarySignature ) public whenNotPaused isOrderLegit(orderAddr) validAddress(notary) returns (bool) { DataOrder order = DataOrder(orderAddr); address buyer = order.buyer(); require(msg.sender == buyer); require(!order.hasNotaryBeenAdded(notary)); require(allowedNotaries.exist(notary)); require( CryptoUtils.isNotaryAdditionValid( orderAddr, notary, responsesPercentage, notarizationFee, notarizationTermsOfService, notarySignature ) ); bool okay = order.addNotary( notary, responsesPercentage, notarizationFee, notarizationTermsOfService ); if (okay) { openOrders.insert(orderAddr); ordersByNotary[notary].push(orderAddr); emit NotaryAddedToOrder(order, notary); } return okay; } /** * @notice Adds a new DataResponse to the given order. * @dev 1. The `msg.sender` must be the buyer of the order. * 2. The buyer must allow the DataExchange to withdraw the price of the * order. * @param orderAddr Order address where the DataResponse must be added. * @param seller Address of the Seller. * @param notary Notary address that the Seller chose to use as notarizer, * this must be one within the allowed notaries and within the * DataOrder's notaries. * @param dataHash Hash of the data that must be sent, this is a SHA256. * @param signature Signature of DataResponse. * @return true if the DataResponse was set successfully, reverts otherwise. */ function addDataResponseToOrder( address orderAddr, address seller, address notary, string dataHash, bytes signature ) public whenNotPaused isOrderLegit(orderAddr) returns (bool) { DataOrder order = DataOrder(orderAddr); address buyer = order.buyer(); require(msg.sender == buyer); allDistinct( [ orderAddr, buyer, seller, notary, address(this) ] ); require(order.hasNotaryBeenAdded(notary)); require( CryptoUtils.isDataResponseValid( orderAddr, seller, notary, dataHash, signature ) ); bool okay = order.addDataResponse( seller, notary, dataHash ); require(okay); chargeBuyer(order, seller); ordersBySeller[seller].push(orderAddr); emit DataAdded(order, seller); return true; } /** * @notice Closes a DataResponse. * @dev Once the buyer receives the seller's data and checks that it is valid * or not, he must close the DataResponse signaling the result. * 1. This method requires an offline signature from the notary set in * the DataResponse, which will indicate the audit result or if * the data was not audited at all. * - If the notary did not audit the data or it verifies that it was * valid, funds will be sent to the Seller. * - If the notary signals the data as invalid, funds will be * handed back to the Buyer. * - Otherwise, funds will be locked at the `DataExchange` contract * until the issue is solved. * 2. This also works as a pause mechanism in case the system is * working under abnormal scenarios while allowing the parties to keep * exchanging information without losing their funds until the system * is back up. * 3. The `msg.sender` must be the buyer or the notary in case the * former does not show up. Only through the notary's signature it is * decided who must receive the funds. * @param orderAddr Order address where the DataResponse belongs to. * @param seller Seller address. * @param wasAudited Indicates whether the data was audited or not. * @param isDataValid Indicates the result of the audit, if happened. * @param notarySignature Off-chain Notary signature * @return true if the DataResponse was successfully closed, reverts otherwise. */ function closeDataResponse( address orderAddr, address seller, bool wasAudited, bool isDataValid, bytes notarySignature ) public whenNotPaused isOrderLegit(orderAddr) returns (bool) { DataOrder order = DataOrder(orderAddr); address buyer = order.buyer(); require(order.hasSellerBeenAccepted(seller)); address notary = order.getNotaryForSeller(seller); require(msg.sender == buyer || msg.sender == notary); require( CryptoUtils.isNotaryVeredictValid( orderAddr, seller, notary, wasAudited, isDataValid, notarySignature ) ); bool transactionCompleted = !wasAudited || isDataValid; require(order.closeDataResponse(seller, transactionCompleted)); payPlayers( order, buyer, seller, notary, wasAudited, isDataValid ); if (transactionCompleted) { emit TransactionCompleted(order, seller); } else { emit RefundedToBuyer(order, buyer); } return true; } /** * @notice Closes the DataOrder. * @dev Onces the data is closed it will no longer accept new DataResponses. * The `msg.sender` must be the buyer of the order or the owner of the * contract in a emergency case. * @param orderAddr Order address to close. * @return true if the DataOrder was successfully closed, reverts otherwise. */ function closeOrder( address orderAddr ) public whenNotPaused isOrderLegit(orderAddr) returns (bool) { require(openOrders.exist(orderAddr)); DataOrder order = DataOrder(orderAddr); address buyer = order.buyer(); require(msg.sender == buyer || msg.sender == owner); bool okay = order.close(); if (okay) { // remaining budget for audits go back to buyer. uint256 remainingBudget = buyerRemainingBudgetForAudits[buyer][order]; buyerRemainingBudgetForAudits[buyer][order] = 0; require(token.transfer(buyer, remainingBudget)); openOrders.remove(orderAddr); emit OrderClosed(orderAddr); } return okay; } /** * @notice Gets all the data orders associated with a notary. * @param notary Notary address to get orders for. * @return A list of DataOrder addresses. */ function getOrdersForNotary( address notary ) public view validAddress(notary) returns (address[]) { return ordersByNotary[notary]; } /** * @notice Gets all the data orders associated with a seller. * @param seller Seller address to get orders for. * @return List of DataOrder addresses. */ function getOrdersForSeller( address seller ) public view validAddress(seller) returns (address[]) { return ordersBySeller[seller]; } /** * @notice Gets all the data orders associated with a buyer. * @param buyer Buyer address to get orders for. * @return List of DataOrder addresses. */ function getOrdersForBuyer( address buyer ) public view validAddress(buyer) returns (address[]) { return ordersByBuyer[buyer]; } /** * @notice Gets all the open data orders, that is all the DataOrders that are * still receiving new DataResponses. * @return List of DataOrder addresses. */ function getOpenOrders() public view returns (address[]) { return openOrders.addresses; } /** * @dev Gets the list of allowed notaries. * @return List of notary addresses. */ function getAllowedNotaries() public view returns (address[]) { return allowedNotaries.addresses; } /** * @dev Gets information about a give notary. * @param notary Notary address to get info for. * @return Notary information (address, name, notaryUrl, publicKey, isActive). */ function getNotaryInfo( address notary ) public view validAddress(notary) returns (address, string, string, string, bool) { NotaryInfo memory info = notaryInfo[notary]; return ( info.addr, info.name, info.notaryUrl, info.publicKey, allowedNotaries.exist(notary) ); } /** * @dev Requires that five addresses are distinct between themselves and zero. * @param addresses array of five addresses to explore. */ function allDistinct(address[5] addresses) private pure { for (uint i = 0; i < addresses.length; i++) { require(addresses[i] != address(0)); for (uint j = i + 1; j < addresses.length; j++) { // solium-disable-line zeppelin/no-arithmetic-operations require(addresses[i] != addresses[j]); } } } /** * @dev Charges a buyer the final charges for a given `DataResponse`. * @notice 1. Tokens are held in the DataExchange contract until players are paid. * 2. This function follows a basic invoice flow: * * DataOrder price * + Notarization fee * ------------------ * Total charges * - Prepaid charges (Minimum between Notarization fee and Buyer remaining budget) * ------------------ * Final charges * * @param order DataOrder to which the DataResponse applies. * @param seller Address of the Seller. */ function chargeBuyer(DataOrder order, address seller) private whenNotPaused { address buyer = order.buyer(); address notary = order.getNotaryForSeller(seller); uint256 remainingBudget = buyerRemainingBudgetForAudits[buyer][order]; uint256 orderPrice = order.price(); (,, uint256 notarizationFee,,) = order.getNotaryInfo(notary); uint256 totalCharges = orderPrice.add(notarizationFee); uint256 prePaid = Math.min256(notarizationFee, remainingBudget); uint256 finalCharges = totalCharges.sub(prePaid); buyerRemainingBudgetForAudits[buyer][order] = remainingBudget.sub(prePaid); require(token.transferFrom(buyer, this, finalCharges)); // Bookkeeping of the available tokens paid by the Buyer and now in control // of the DataExchange takes into account the total charges (final + pre-paid) buyerBalance[buyer][order][seller] = buyerBalance[buyer][order][seller].add(totalCharges); } /** * @dev Pays the seller, notary and/or buyer according to the notary's veredict. * @param order DataOrder to which the payments apply. * @param buyer Address of the Buyer. * @param seller Address of the Seller. * @param notary Address of the Notary. * @param wasAudited Indicates whether the data was audited or not. * @param isDataValid Indicates the result of the audit, if happened. */ function payPlayers( DataOrder order, address buyer, address seller, address notary, bool wasAudited, bool isDataValid ) private whenNotPaused { uint256 orderPrice = order.price(); (,, uint256 notarizationFee,,) = order.getNotaryInfo(notary); uint256 totalCharges = orderPrice.add(notarizationFee); require(buyerBalance[buyer][order][seller] >= totalCharges); buyerBalance[buyer][order][seller] = buyerBalance[buyer][order][seller].sub(totalCharges); // if no notarization was done, notarization fee tokens go back to buyer. address notarizationFeeReceiver = wasAudited ? notary : buyer; // if no notarization was done or data is valid, tokens go to the seller address orderPriceReceiver = (!wasAudited || isDataValid) ? seller : buyer; require(token.transfer(notarizationFeeReceiver, notarizationFee)); require(token.transfer(orderPriceReceiver, orderPrice)); } }
36,381
44
// This event is fired whenever the owner changes the maximumLockupDurationInBlocks. /newMaximumLockoutDurationInBlocksTo prevent users from accidentally locking up ether for an eternity, the lockout /period of all bounties is capped using this variable, which is inially set to 4 weeks. This is measured in blocks, which /are created roughly once every 15 seconds. If the community expresses that they would like a longer maximumLockoutDuration,/the creator will adjust this variable.
event MaximumLockoutDurationInBlocksUpdated(uint256 newMaximumLockoutDurationInBlocks);
event MaximumLockoutDurationInBlocksUpdated(uint256 newMaximumLockoutDurationInBlocks);
43,372
467
// Get the timestamp of the last issue this account made
return flexibleStorage().getUIntValue(CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)));
return flexibleStorage().getUIntValue(CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)));
24,685
11
// Checks ifaccount has the role. /
function isBurner(address account) public view returns (bool) { return _burners.has(account); }
function isBurner(address account) public view returns (bool) { return _burners.has(account); }
48,197
283
// update the maximum time an option can be created for nMT_ the time (in seconds) of maximum possible bet /
function uMXOT(uint256 nMT_) external tierOneDelegation { BinaryOptions protocol = BinaryOptions(pA); protocol.setMaxT(nMT_); }
function uMXOT(uint256 nMT_) external tierOneDelegation { BinaryOptions protocol = BinaryOptions(pA); protocol.setMaxT(nMT_); }
27,214
2
// anyFRAX -> L1 FRAX Swapout AnySwap Bridge
IAnyswapV5ERC20(address(anyFRAX)).Swapout(token_amount, address_to_send_to);
IAnyswapV5ERC20(address(anyFRAX)).Swapout(token_amount, address_to_send_to);
32,179
80
// claim pending bid rewards only
_accrueRewards(msg.sender, claim);
_accrueRewards(msg.sender, claim);
5,983
14
// Build random card data
bytes32[] memory cards = new bytes32[](10); for (uint256 i; i < 10; ++i) { cards[i] = keccak256(abi.encodePacked(user, pack, i)); }
bytes32[] memory cards = new bytes32[](10); for (uint256 i; i < 10; ++i) { cards[i] = keccak256(abi.encodePacked(user, pack, i)); }
40,193
10
// if someones sends Ether directly to the contract - fail it! /
function /* fallback */ () public payable { revert(); }
function /* fallback */ () public payable { revert(); }
36,206
113
// Timestamp at which the contract was created
uint32 public startTime;
uint32 public startTime;
13,658
2
// if (!halted) throw;
require(halted); _;
require(halted); _;
38,998
4
// Handle negative z
if (z < 0) { responseValue = uint256(100000).sub(responseValue); }
if (z < 0) { responseValue = uint256(100000).sub(responseValue); }
75,508
69
// ! Not need to check state since changes at 02.2018 inState(State.Setup)
onlyOwner public
onlyOwner public
78,934
144
// We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there will be at least one available slot due to how the memory scratch space works. We can safely overwrite whatever is stored in this slot as we will revert immediately after that.
let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount)
let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount)
32,859
6
// Adds an address to the blocklist account The address to addreturn true if the operation succeeded Fails if the address was already blocklisted /
function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; }
function _addToBlocklist(address account) private onlyNotInBlocklist(account) returns(bool) { _userIndex[account] = _userList.length; _userList.push(account); emit addedToBlocklist(account, msg.sender); return true; }
10,863
12
// Calculate and deposit owedToken
uint256 maxHeldTokenFromSell = MathHelpers.maxUint256(); if (!transaction.depositInHeldToken) { transaction.depositAmount = getOwedTokenDeposit(transaction, collateralToAdd, orderData); BorrowShared.doDepositOwedToken(state, transaction); maxHeldTokenFromSell = collateralToAdd; }
uint256 maxHeldTokenFromSell = MathHelpers.maxUint256(); if (!transaction.depositInHeldToken) { transaction.depositAmount = getOwedTokenDeposit(transaction, collateralToAdd, orderData); BorrowShared.doDepositOwedToken(state, transaction); maxHeldTokenFromSell = collateralToAdd; }
52,969
2
// 余额
mapping(address => uint) balanceOf;
mapping(address => uint) balanceOf;
50,891
17
// looping over the number of items created (if number has not been sold pupulte the array)
MarketToken[] memory items = new MarketToken[](unsoldItemCount); for(uint i = 0; i < itemCount; i++) { if(idToMarketToken[i+1].owner == address(0)) { uint currentId = i + 1; MarketToken storage currentItem = idToMarketToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; }
MarketToken[] memory items = new MarketToken[](unsoldItemCount); for(uint i = 0; i < itemCount; i++) { if(idToMarketToken[i+1].owner == address(0)) { uint currentId = i + 1; MarketToken storage currentItem = idToMarketToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; }
9,532
26
// the consumer release payment to receiver_paymentId the integer identifier of payment return valid Boolean indication of payment is released/
function releasePayment(bytes32 _paymentId) public isLocked(_paymentId) isAuthContract() returns (bool) { // payment must not be paused require(mPayments[_paymentId].paused == false, 'Payment is paused'); // update state to avoid re-entry attack mPayments[_paymentId].state = PaymentState.Released; require(mToken.transfer(mPayments[_paymentId].receiver, mPayments[_paymentId].amount), 'Token transfer failed.'); emit PaymentReleased(_paymentId, mPayments[_paymentId].receiver); return true; }
function releasePayment(bytes32 _paymentId) public isLocked(_paymentId) isAuthContract() returns (bool) { // payment must not be paused require(mPayments[_paymentId].paused == false, 'Payment is paused'); // update state to avoid re-entry attack mPayments[_paymentId].state = PaymentState.Released; require(mToken.transfer(mPayments[_paymentId].receiver, mPayments[_paymentId].amount), 'Token transfer failed.'); emit PaymentReleased(_paymentId, mPayments[_paymentId].receiver); return true; }
6,773
122
// set the offer hash as cancelled
_cancelledOrCompletedOffers[_offer_hash]=true; emit OfferCancelled(_offer_hash);
_cancelledOrCompletedOffers[_offer_hash]=true; emit OfferCancelled(_offer_hash);
43,563
30
// Allows contract owner to mint new tokens, prevents numerical overflow
function mintToken(address target, uint256 mintedAmount) onlyOwner returns (bool success) { require(mintedAmount > 0); uint256 addTokens = mintedAmount; balance[target] += addTokens; totalSupply += addTokens; Transfer(0, target, addTokens); return true; }
function mintToken(address target, uint256 mintedAmount) onlyOwner returns (bool success) { require(mintedAmount > 0); uint256 addTokens = mintedAmount; balance[target] += addTokens; totalSupply += addTokens; Transfer(0, target, addTokens); return true; }
15,980
228
// PUBLIC STATES
IDfWalletFactory public dfWalletFactory; uint256 private DELETED_fee; // DELETED state mapping(address => UserData) public wallets;
IDfWalletFactory public dfWalletFactory; uint256 private DELETED_fee; // DELETED state mapping(address => UserData) public wallets;
30,350
154
// Reentrancy Guard // Prevents a contract from calling itself, directly or indirectly. /
modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul }
modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul }
9,481
35
// /
function getWinner() public onlyContractCreator returns (uint256[]) { uint i; //Loop to generate 5 random hero IDs from 55 heroes for(i=0;i<=4;i++){ //Block timestamp and number used to generate the random number winners.push(uint256(sha256(block.timestamp, block.number-i-1)) % heroMax); } return winners; }
function getWinner() public onlyContractCreator returns (uint256[]) { uint i; //Loop to generate 5 random hero IDs from 55 heroes for(i=0;i<=4;i++){ //Block timestamp and number used to generate the random number winners.push(uint256(sha256(block.timestamp, block.number-i-1)) % heroMax); } return winners; }
44,192
27
// verify that ETH was passed with the call if needed
verifyEthAmount(reserveToken.isNativeToken() ? amount : 0); return addBaseTokenLiquidity(owner, poolAnchor, reserveToken, amount);
verifyEthAmount(reserveToken.isNativeToken() ? amount : 0); return addBaseTokenLiquidity(owner, poolAnchor, reserveToken, amount);
55,788
59
// Set a new metadata renderer/newRenderer new renderer address to use/setupRenderer data to setup new renderer with
function setMetadataRenderer( IMetadataRenderer newRenderer, bytes memory setupRenderer
function setMetadataRenderer( IMetadataRenderer newRenderer, bytes memory setupRenderer
19,007
13
// Inits the module for a wallet by logging an event.The method can only be called by the wallet itself. _wallet The wallet. /
function init(BaseWallet _wallet) external onlyWallet(_wallet) { emit ModuleInitialised(_wallet); }
function init(BaseWallet _wallet) external onlyWallet(_wallet) { emit ModuleInitialised(_wallet); }
19,008
17
// Get Matrix Upline Depth/
function getMatrix() internal view virtual returns (uint8) { return getSettings().matrix; }
function getMatrix() internal view virtual returns (uint8) { return getSettings().matrix; }
29,261
155
// Minimum between two uint256 numbers
function uint256Min(uint256 a, uint256 b) pure internal returns (uint256) { return a > b ? b : a; }
function uint256Min(uint256 a, uint256 b) pure internal returns (uint256) { return a > b ? b : a; }
14,485
47
// Upgrade agent interface inspired by Lunyr. Upgrade agent transfers tokens to a new contract.Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. /
contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; }
contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; }
25,630
66
// calculates the amount of ETH belonging to the LP-Pair and converts them to LP
if(tokenForLiquidity>0){ uint liqETH = (newETH*LiqHalf)/swapToken; _addLiquidity(LiqHalf, liqETH); }
if(tokenForLiquidity>0){ uint liqETH = (newETH*LiqHalf)/swapToken; _addLiquidity(LiqHalf, liqETH); }
43,594
77
// Get asset 0 twapUses Uni V3 oracle, reading the TWAP from twap periodor the earliest oracle observation time if twap period is not set /
function getAsset0Price() public view returns (int128) { return UniswapLibrary.getAsset0Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); }
function getAsset0Price() public view returns (int128) { return UniswapLibrary.getAsset0Price( uniContracts.pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); }
81,799
45
// Withdraws bought tokens, or returns commitment if the sale is unsuccessful.
function withdrawTokens() public { withdrawTokens(msg.sender); }
function withdrawTokens() public { withdrawTokens(msg.sender); }
60,410
30
// They may have been whitelisted to mint 10, but if only 2 remain in supply, then they will only get 2
_mintAmount(amountMint, _msgSender()); return true;
_mintAmount(amountMint, _msgSender()); return true;
9,877
35
// link group ID ---> Group structure /
mapping (uint => Group) public lockup;
mapping (uint => Group) public lockup;
41,767
0
// Common interface for L1 and L2 Gateway Routers /
interface IGatewayRouter is ITokenGateway { function defaultGateway() external view returns (address gateway); event TransferRouted( address indexed token, address indexed _userFrom, address indexed _userTo, address gateway ); event GatewaySet(address indexed l1Token, address indexed gateway); event DefaultGatewayUpdated(address newDefaultGateway); function getGateway(address _token) external view returns (address gateway); }
interface IGatewayRouter is ITokenGateway { function defaultGateway() external view returns (address gateway); event TransferRouted( address indexed token, address indexed _userFrom, address indexed _userTo, address gateway ); event GatewaySet(address indexed l1Token, address indexed gateway); event DefaultGatewayUpdated(address newDefaultGateway); function getGateway(address _token) external view returns (address gateway); }
22,401
109
// Gets the DMM token for the provided underlying token. For example, sending DAI returns DMM: DAI. /
function getDmmTokenForUnderlying(address underlyingToken) external view returns (address);
function getDmmTokenForUnderlying(address underlyingToken) external view returns (address);
24,724
196
// the total borrows of the reserve at a stable rate. Expressed in the currency decimals
uint256 totalBorrowsStable;
uint256 totalBorrowsStable;
24,249
24
// Optional: A simple email validation function (not suitable for all cases)
function isValidEmail(string memory email) internal pure returns (bool) { // Perform basic email format check here (e.g., check for '@' symbol and valid domain) // This example is just for demonstration purposes and is not exhaustive. bytes memory emailBytes = bytes(email); bool hasAtSymbol = false; bool hasDot = false; for (uint i = 0; i < emailBytes.length; i++) { if (emailBytes[i] == "@") { hasAtSymbol = true; } if (emailBytes[i] == ".") { hasDot = true; } } return hasAtSymbol && hasDot; }
function isValidEmail(string memory email) internal pure returns (bool) { // Perform basic email format check here (e.g., check for '@' symbol and valid domain) // This example is just for demonstration purposes and is not exhaustive. bytes memory emailBytes = bytes(email); bool hasAtSymbol = false; bool hasDot = false; for (uint i = 0; i < emailBytes.length; i++) { if (emailBytes[i] == "@") { hasAtSymbol = true; } if (emailBytes[i] == ".") { hasDot = true; } } return hasAtSymbol && hasDot; }
22,914
16
// Computes the winning proposal taking all previous votes into account.return winningProposal_ index of winning proposal in the proposals array /
function winningProposal() public view returns (uint256 winningProposal_)
function winningProposal() public view returns (uint256 winningProposal_)
37,703
13
// sale in ERC20
if (sale.tokenWant != address(0)) { IERC20 tokenWant = IERC20(sale.tokenWant); require (tokenTotalAmount <= tokenWant.balanceOf(msg.sender), 'Balance of token want too low'); tokenWant.safeTransferFrom(msg.sender, sale.creator, tokenTotalAmount); } else {
if (sale.tokenWant != address(0)) { IERC20 tokenWant = IERC20(sale.tokenWant); require (tokenTotalAmount <= tokenWant.balanceOf(msg.sender), 'Balance of token want too low'); tokenWant.safeTransferFrom(msg.sender, sale.creator, tokenTotalAmount); } else {
34,323
318
// pool信息
address pool;
address pool;
7,087
6
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
string memory str = new string(32);
1,913
57
// ================================================================== operations ==================================================================
function grantRole(bytes32 role, address account) public override onlyOwner
function grantRole(bytes32 role, address account) public override onlyOwner
13,273
20
// Returns the symbol of the token. /
function symbol() external view returns (string memory);
function symbol() external view returns (string memory);
809
15
// Get the denominator This is the denominator used for calculating feesreturn The denominator /
function getDenominator() external pure returns (uint256);
function getDenominator() external pure returns (uint256);
10,982
35
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Helper::transferFrom: transferFrom failed' );
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Helper::transferFrom: transferFrom failed' );
15,895
23
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
event NewResolver(bytes32 indexed node, address resolver);
17,243