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
86
// localethereum.com/localethereum.com
contract LocalEthereumEscrows { /*********************** + Global settings + ***********************/ // Address of the arbitrator (currently always localethereum staff) address public arbitrator; // Address of the owner (who can withdraw collected fees) address public owner; // Address of the relayer (who is allowed to forward signed instructions from parties) address public relayer; uint32 public requestCancellationMinimumTime; // Cumulative balance of collected fees uint256 public feesAvailableForWithdraw; /*********************** + Instruction types + ***********************/ // Called when the buyer marks payment as sent. Locks funds in escrow uint8 constant INSTRUCTION_SELLER_CANNOT_CANCEL = 0x01; // Buyer cancelling uint8 constant INSTRUCTION_BUYER_CANCEL = 0x02; // Seller cancelling uint8 constant INSTRUCTION_SELLER_CANCEL = 0x03; // Seller requesting to cancel. Begins a window for buyer to object uint8 constant INSTRUCTION_SELLER_REQUEST_CANCEL = 0x04; // Seller releasing funds to the buyer uint8 constant INSTRUCTION_RELEASE = 0x05; // Either party permitting the arbitrator to resolve a dispute uint8 constant INSTRUCTION_RESOLVE = 0x06; /*********************** + Events + ***********************/ event Created(bytes32 indexed _tradeHash); event SellerCancelDisabled(bytes32 indexed _tradeHash); event SellerRequestedCancel(bytes32 indexed _tradeHash); event CancelledBySeller(bytes32 indexed _tradeHash); event CancelledByBuyer(bytes32 indexed _tradeHash); event Released(bytes32 indexed _tradeHash); event DisputeResolved(bytes32 indexed _tradeHash); struct Escrow { // So we know the escrow exists bool exists; // This is the timestamp in whic hthe seller can cancel the escrow after. // It has two special values: // 0 : Permanently locked by the buyer (i.e. marked as paid; the seller can never cancel) // 1 : The seller can only request to cancel, which will change this value to a timestamp. // This option is avaialble for complex trade terms such as cash-in-person where a // payment window is inappropriate uint32 sellerCanCancelAfter; // Cumulative cost of gas incurred by the relayer. This amount will be refunded to the owner // in the way of fees once the escrow has completed uint128 totalGasFeesSpentByRelayer; } // Mapping of active trades. The key here is a hash of the trade proprties mapping (bytes32 => Escrow) public escrows; modifier onlyOwner() { require(msg.sender == owner, "Must be owner"); _; } modifier onlyArbitrator() { require(msg.sender == arbitrator, "Must be arbitrator"); _; } /// @notice Initialize the contract. constructor() public { owner = msg.sender; arbitrator = msg.sender; relayer = msg.sender; requestCancellationMinimumTime = 2 hours; } /// @notice Create and fund a new escrow. /// @param _tradeID The unique ID of the trade, generated by localethereum.com /// @param _seller The selling party /// @param _buyer The buying party /// @param _value The amount of the escrow, exclusive of the fee /// @param _fee Localethereum's commission in 1/10000ths /// @param _paymentWindowInSeconds The time in seconds from escrow creation that the seller can cancel after /// @param _expiry This transaction must be created before this time /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component function createEscrow( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint32 _paymentWindowInSeconds, uint32 _expiry, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // The trade hash is created by tightly-concatenating and hashing properties of the trade. // This hash becomes the identifier of the escrow, and hence all these variables must be // supplied on future contract calls bytes32 _tradeHash = keccak256(abi.encodePacked(_tradeID, _seller, _buyer, _value, _fee)); // Require that trade does not already exist require(!escrows[_tradeHash].exists, "Trade already exists"); // A signature (v, r and s) must come from localethereum to open an escrow bytes32 _invitationHash = keccak256(abi.encodePacked( _tradeHash, _paymentWindowInSeconds, _expiry )); require(recoverAddress(_invitationHash, _v, _r, _s) == relayer, "Must be relayer"); // These signatures come with an expiry stamp require(block.timestamp < _expiry, "Signature has expired"); // Check transaction value against signed _value and make sure is not 0 require(msg.value == _value && msg.value > 0, "Incorrect ether sent"); uint32 _sellerCanCancelAfter = _paymentWindowInSeconds == 0 ? 1 : uint32(block.timestamp) + _paymentWindowInSeconds; // Add the escrow to the public mapping escrows[_tradeHash] = Escrow(true, _sellerCanCancelAfter, 0); emit Created(_tradeHash); } uint16 constant GAS_doResolveDispute = 36100; /// @notice Called by the arbitrator to resolve a dispute. Requires a signature from either party. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component /// @param _buyerPercent What % should be distributed to the buyer (this is usually 0 or 100) function resolveDispute( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint8 _v, bytes32 _r, bytes32 _s, uint8 _buyerPercent ) external onlyArbitrator { address _signature = recoverAddress(keccak256(abi.encodePacked( _tradeID, INSTRUCTION_RESOLVE )), _v, _r, _s); require(_signature == _buyer || _signature == _seller, "Must be buyer or seller"); Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); require(_escrow.exists, "Escrow does not exist"); require(_buyerPercent <= 100, "_buyerPercent must be 100 or lower"); uint256 _totalFees = _escrow.totalGasFeesSpentByRelayer + (GAS_doResolveDispute * uint128(tx.gasprice)); require(_value - _totalFees <= _value, "Overflow error"); // Prevent underflow feesAvailableForWithdraw += _totalFees; // Add the the pot for localethereum to withdraw delete escrows[_tradeHash]; emit DisputeResolved(_tradeHash); if (_buyerPercent > 0) _buyer.transfer((_value - _totalFees) * _buyerPercent / 100); if (_buyerPercent < 100) _seller.transfer((_value - _totalFees) * (100 - _buyerPercent) / 100); } /// @notice Release ether in escrow to the buyer. Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function release( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool){ require(msg.sender == _seller, "Must be seller"); return doRelease(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Disable the seller from cancelling (i.e. "mark as paid"). Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function disableSellerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool) { require(msg.sender == _buyer, "Must be buyer"); return doDisableSellerCancel(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Cancel the escrow as a buyer. Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function buyerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool) { require(msg.sender == _buyer, "Must be buyer"); return doBuyerCancel(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Cancel the escrow as a seller. Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function sellerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool) { require(msg.sender == _seller, "Must be seller"); return doSellerCancel(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Request to cancel as a seller. Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function sellerRequestCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool) { require(msg.sender == _seller, "Must be seller"); return doSellerRequestCancel(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Relay multiple signed instructions from parties of escrows. /// @param _tradeID List of _tradeID values /// @param _seller List of _seller values /// @param _buyer List of _buyer values /// @param _value List of _value values /// @param _fee List of _fee values /// @param _maximumGasPrice List of _maximumGasPrice values /// @param _v List of signature "v" components /// @param _r List of signature "r" components /// @param _s List of signature "s" components /// @param _instructionByte List of _instructionByte values /// @return bool List of results uint16 constant GAS_batchRelayBaseCost = 28500; function batchRelay( bytes16[] _tradeID, address[] _seller, address[] _buyer, uint256[] _value, uint16[] _fee, uint128[] _maximumGasPrice, uint8[] _v, bytes32[] _r, bytes32[] _s, uint8[] _instructionByte ) public returns (bool[]) { bool[] memory _results = new bool[](_tradeID.length); uint128 _additionalGas = uint128(msg.sender == relayer ? GAS_batchRelayBaseCost / _tradeID.length : 0); for (uint8 i=0; i<_tradeID.length; i++) { _results[i] = relay( _tradeID[i], _seller[i], _buyer[i], _value[i], _fee[i], _maximumGasPrice[i], _v[i], _r[i], _s[i], _instructionByte[i], _additionalGas ); } return _results; } /// @notice Withdraw fees collected by the contract. Only the owner can call this. /// @param _to Address to withdraw fees in to /// @param _amount Amount to withdraw function withdrawFees(address _to, uint256 _amount) onlyOwner external { // This check also prevents underflow require(_amount <= feesAvailableForWithdraw, "Amount is higher than amount available"); feesAvailableForWithdraw -= _amount; _to.transfer(_amount); } /// @notice Set the arbitrator to a new address. Only the owner can call this. /// @param _newArbitrator Address of the replacement arbitrator function setArbitrator(address _newArbitrator) onlyOwner external { arbitrator = _newArbitrator; } /// @notice Change the owner to a new address. Only the owner can call this. /// @param _newOwner Address of the replacement owner function setOwner(address _newOwner) onlyOwner external { owner = _newOwner; } /// @notice Change the relayer to a new address. Only the owner can call this. /// @param _newRelayer Address of the replacement relayer function setRelayer(address _newRelayer) onlyOwner external { relayer = _newRelayer; } /// @notice Change the requestCancellationMinimumTime. Only the owner can call this. /// @param _newRequestCancellationMinimumTime Replacement function setRequestCancellationMinimumTime( uint32 _newRequestCancellationMinimumTime ) onlyOwner external { requestCancellationMinimumTime = _newRequestCancellationMinimumTime; } /// @notice Send ERC20 tokens away. This function allows the owner to withdraw stuck ERC20 tokens. /// @param _tokenContract Token contract /// @param _transferTo Recipient /// @param _value Value function transferToken( Token _tokenContract, address _transferTo, uint256 _value ) onlyOwner external { _tokenContract.transfer(_transferTo, _value); } /// @notice Send ERC20 tokens away. This function allows the owner to withdraw stuck ERC20 tokens. /// @param _tokenContract Token contract /// @param _transferTo Recipient /// @param _transferFrom Sender /// @param _value Value function transferTokenFrom( Token _tokenContract, address _transferTo, address _transferFrom, uint256 _value ) onlyOwner external { _tokenContract.transferFrom(_transferTo, _transferFrom, _value); } /// @notice Send ERC20 tokens away. This function allows the owner to withdraw stuck ERC20 tokens. /// @param _tokenContract Token contract /// @param _spender Spender address /// @param _value Value function approveToken( Token _tokenContract, address _spender, uint256 _value ) onlyOwner external { _tokenContract.approve(_spender, _value); } /// @notice Relay a signed instruction from a party of an escrow. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _maximumGasPrice Maximum gas price permitted for the relayer (set by the instructor) /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function relay( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _maximumGasPrice, uint8 _v, bytes32 _r, bytes32 _s, uint8 _instructionByte, uint128 _additionalGas ) private returns (bool) { address _relayedSender = getRelayedSender( _tradeID, _instructionByte, _maximumGasPrice, _v, _r, _s ); if (_relayedSender == _buyer) { // Buyer's instructions: if (_instructionByte == INSTRUCTION_SELLER_CANNOT_CANCEL) { // Disable seller from cancelling return doDisableSellerCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } else if (_instructionByte == INSTRUCTION_BUYER_CANCEL) { // Cancel return doBuyerCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } } else if (_relayedSender == _seller) { // Seller's instructions: if (_instructionByte == INSTRUCTION_RELEASE) { // Release return doRelease(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } else if (_instructionByte == INSTRUCTION_SELLER_CANCEL) { // Cancel return doSellerCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } else if (_instructionByte == INSTRUCTION_SELLER_REQUEST_CANCEL){ // Request to cancel return doSellerRequestCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } } else { require(msg.sender == _seller, "Unrecognised party"); return false; } } /// @notice Increase the amount of gas to be charged later on completion of an escrow /// @param _tradeHash Trade hash /// @param _gas Gas cost function increaseGasSpent(bytes32 _tradeHash, uint128 _gas) private { escrows[_tradeHash].totalGasFeesSpentByRelayer += _gas * uint128(tx.gasprice); } /// @notice Transfer the value of an escrow, minus the fees, minus the gas costs incurred by relay /// @param _to Recipient address /// @param _value Value of the transfer /// @param _totalGasFeesSpentByRelayer Total gas fees spent by the relayer /// @param _fee Commission in 1/10000ths function transferMinusFees( address _to, uint256 _value, uint128 _totalGasFeesSpentByRelayer, uint16 _fee ) private { uint256 _totalFees = (_value * _fee / 10000) + _totalGasFeesSpentByRelayer; // Prevent underflow if(_value - _totalFees > _value) { return; } // Add fees to the pot for localethereum to withdraw feesAvailableForWithdraw += _totalFees; _to.transfer(_value - _totalFees); } uint16 constant GAS_doRelease = 46588; /// @notice Release escrow to the buyer. This completes it and removes it from the mapping. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doRelease( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) return false; uint128 _gasFees = _escrow.totalGasFeesSpentByRelayer + (msg.sender == relayer ? (GAS_doRelease + _additionalGas ) * uint128(tx.gasprice) : 0 ); delete escrows[_tradeHash]; emit Released(_tradeHash); transferMinusFees(_buyer, _value, _gasFees, _fee); return true; } uint16 constant GAS_doDisableSellerCancel = 28944; /// @notice Prevents the seller from cancelling an escrow. Used to "mark as paid" by the buyer. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doDisableSellerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) return false; if(_escrow.sellerCanCancelAfter == 0) return false; escrows[_tradeHash].sellerCanCancelAfter = 0; emit SellerCancelDisabled(_tradeHash); if (msg.sender == relayer) { increaseGasSpent(_tradeHash, GAS_doDisableSellerCancel + _additionalGas); } return true; } uint16 constant GAS_doBuyerCancel = 46255; /// @notice Cancels the trade and returns the ether to the seller. Can only be called the buyer. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doBuyerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) { return false; } uint128 _gasFees = _escrow.totalGasFeesSpentByRelayer + (msg.sender == relayer ? (GAS_doBuyerCancel + _additionalGas ) * uint128(tx.gasprice) : 0 ); delete escrows[_tradeHash]; emit CancelledByBuyer(_tradeHash); transferMinusFees(_seller, _value, _gasFees, 0); return true; } uint16 constant GAS_doSellerCancel = 46815; /// @notice Returns the ether in escrow to the seller. Called by the seller. Sometimes unavailable. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doSellerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) { return false; } if(_escrow.sellerCanCancelAfter <= 1 || _escrow.sellerCanCancelAfter > block.timestamp) { return false; } uint128 _gasFees = _escrow.totalGasFeesSpentByRelayer + (msg.sender == relayer ? (GAS_doSellerCancel + _additionalGas ) * uint128(tx.gasprice) : 0 ); delete escrows[_tradeHash]; emit CancelledBySeller(_tradeHash); transferMinusFees(_seller, _value, _gasFees, 0); return true; } uint16 constant GAS_doSellerRequestCancel = 29507; /// @notice Request to cancel. Used if the buyer is unresponsive. Begins a countdown timer. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doSellerRequestCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { // Called on unlimited payment window trades where the buyer is not responding Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) { return false; } if(_escrow.sellerCanCancelAfter != 1) { return false; } escrows[_tradeHash].sellerCanCancelAfter = uint32(block.timestamp) + requestCancellationMinimumTime; emit SellerRequestedCancel(_tradeHash); if (msg.sender == relayer) { increaseGasSpent(_tradeHash, GAS_doSellerRequestCancel + _additionalGas); } return true; } /// @notice Get the sender of the signed instruction. /// @param _tradeID Identifier of the trade /// @param _instructionByte Identifier of the instruction /// @param _maximumGasPrice Maximum gas price permitted by the sender /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component /// @return address function getRelayedSender( bytes16 _tradeID, uint8 _instructionByte, uint128 _maximumGasPrice, uint8 _v, bytes32 _r, bytes32 _s ) view private returns (address) { bytes32 _hash = keccak256(abi.encodePacked( _tradeID, _instructionByte, _maximumGasPrice )); if(tx.gasprice > _maximumGasPrice) { return; } return recoverAddress(_hash, _v, _r, _s); } /// @notice Hashes the values and returns the matching escrow object and trade hash. /// @dev Returns an empty escrow struct and 0 _tradeHash if not found. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return Escrow function getEscrowAndHash( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) view private returns (Escrow, bytes32) { bytes32 _tradeHash = keccak256(abi.encodePacked( _tradeID, _seller, _buyer, _value, _fee )); return (escrows[_tradeHash], _tradeHash); } /// @notice Returns an empty escrow struct and 0 _tradeHash if not found. /// @param _h Data to be hashed /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component /// @return address function recoverAddress( bytes32 _h, uint8 _v, bytes32 _r, bytes32 _s ) private pure returns (address) { bytes memory _prefix = "\x19Ethereum Signed Message:\n32"; bytes32 _prefixedHash = keccak256(abi.encodePacked(_prefix, _h)); return ecrecover(_prefixedHash, _v, _r, _s); } }
contract LocalEthereumEscrows { /*********************** + Global settings + ***********************/ // Address of the arbitrator (currently always localethereum staff) address public arbitrator; // Address of the owner (who can withdraw collected fees) address public owner; // Address of the relayer (who is allowed to forward signed instructions from parties) address public relayer; uint32 public requestCancellationMinimumTime; // Cumulative balance of collected fees uint256 public feesAvailableForWithdraw; /*********************** + Instruction types + ***********************/ // Called when the buyer marks payment as sent. Locks funds in escrow uint8 constant INSTRUCTION_SELLER_CANNOT_CANCEL = 0x01; // Buyer cancelling uint8 constant INSTRUCTION_BUYER_CANCEL = 0x02; // Seller cancelling uint8 constant INSTRUCTION_SELLER_CANCEL = 0x03; // Seller requesting to cancel. Begins a window for buyer to object uint8 constant INSTRUCTION_SELLER_REQUEST_CANCEL = 0x04; // Seller releasing funds to the buyer uint8 constant INSTRUCTION_RELEASE = 0x05; // Either party permitting the arbitrator to resolve a dispute uint8 constant INSTRUCTION_RESOLVE = 0x06; /*********************** + Events + ***********************/ event Created(bytes32 indexed _tradeHash); event SellerCancelDisabled(bytes32 indexed _tradeHash); event SellerRequestedCancel(bytes32 indexed _tradeHash); event CancelledBySeller(bytes32 indexed _tradeHash); event CancelledByBuyer(bytes32 indexed _tradeHash); event Released(bytes32 indexed _tradeHash); event DisputeResolved(bytes32 indexed _tradeHash); struct Escrow { // So we know the escrow exists bool exists; // This is the timestamp in whic hthe seller can cancel the escrow after. // It has two special values: // 0 : Permanently locked by the buyer (i.e. marked as paid; the seller can never cancel) // 1 : The seller can only request to cancel, which will change this value to a timestamp. // This option is avaialble for complex trade terms such as cash-in-person where a // payment window is inappropriate uint32 sellerCanCancelAfter; // Cumulative cost of gas incurred by the relayer. This amount will be refunded to the owner // in the way of fees once the escrow has completed uint128 totalGasFeesSpentByRelayer; } // Mapping of active trades. The key here is a hash of the trade proprties mapping (bytes32 => Escrow) public escrows; modifier onlyOwner() { require(msg.sender == owner, "Must be owner"); _; } modifier onlyArbitrator() { require(msg.sender == arbitrator, "Must be arbitrator"); _; } /// @notice Initialize the contract. constructor() public { owner = msg.sender; arbitrator = msg.sender; relayer = msg.sender; requestCancellationMinimumTime = 2 hours; } /// @notice Create and fund a new escrow. /// @param _tradeID The unique ID of the trade, generated by localethereum.com /// @param _seller The selling party /// @param _buyer The buying party /// @param _value The amount of the escrow, exclusive of the fee /// @param _fee Localethereum's commission in 1/10000ths /// @param _paymentWindowInSeconds The time in seconds from escrow creation that the seller can cancel after /// @param _expiry This transaction must be created before this time /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component function createEscrow( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint32 _paymentWindowInSeconds, uint32 _expiry, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // The trade hash is created by tightly-concatenating and hashing properties of the trade. // This hash becomes the identifier of the escrow, and hence all these variables must be // supplied on future contract calls bytes32 _tradeHash = keccak256(abi.encodePacked(_tradeID, _seller, _buyer, _value, _fee)); // Require that trade does not already exist require(!escrows[_tradeHash].exists, "Trade already exists"); // A signature (v, r and s) must come from localethereum to open an escrow bytes32 _invitationHash = keccak256(abi.encodePacked( _tradeHash, _paymentWindowInSeconds, _expiry )); require(recoverAddress(_invitationHash, _v, _r, _s) == relayer, "Must be relayer"); // These signatures come with an expiry stamp require(block.timestamp < _expiry, "Signature has expired"); // Check transaction value against signed _value and make sure is not 0 require(msg.value == _value && msg.value > 0, "Incorrect ether sent"); uint32 _sellerCanCancelAfter = _paymentWindowInSeconds == 0 ? 1 : uint32(block.timestamp) + _paymentWindowInSeconds; // Add the escrow to the public mapping escrows[_tradeHash] = Escrow(true, _sellerCanCancelAfter, 0); emit Created(_tradeHash); } uint16 constant GAS_doResolveDispute = 36100; /// @notice Called by the arbitrator to resolve a dispute. Requires a signature from either party. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component /// @param _buyerPercent What % should be distributed to the buyer (this is usually 0 or 100) function resolveDispute( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint8 _v, bytes32 _r, bytes32 _s, uint8 _buyerPercent ) external onlyArbitrator { address _signature = recoverAddress(keccak256(abi.encodePacked( _tradeID, INSTRUCTION_RESOLVE )), _v, _r, _s); require(_signature == _buyer || _signature == _seller, "Must be buyer or seller"); Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); require(_escrow.exists, "Escrow does not exist"); require(_buyerPercent <= 100, "_buyerPercent must be 100 or lower"); uint256 _totalFees = _escrow.totalGasFeesSpentByRelayer + (GAS_doResolveDispute * uint128(tx.gasprice)); require(_value - _totalFees <= _value, "Overflow error"); // Prevent underflow feesAvailableForWithdraw += _totalFees; // Add the the pot for localethereum to withdraw delete escrows[_tradeHash]; emit DisputeResolved(_tradeHash); if (_buyerPercent > 0) _buyer.transfer((_value - _totalFees) * _buyerPercent / 100); if (_buyerPercent < 100) _seller.transfer((_value - _totalFees) * (100 - _buyerPercent) / 100); } /// @notice Release ether in escrow to the buyer. Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function release( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool){ require(msg.sender == _seller, "Must be seller"); return doRelease(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Disable the seller from cancelling (i.e. "mark as paid"). Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function disableSellerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool) { require(msg.sender == _buyer, "Must be buyer"); return doDisableSellerCancel(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Cancel the escrow as a buyer. Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function buyerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool) { require(msg.sender == _buyer, "Must be buyer"); return doBuyerCancel(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Cancel the escrow as a seller. Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function sellerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool) { require(msg.sender == _seller, "Must be seller"); return doSellerCancel(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Request to cancel as a seller. Direct call option. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return bool function sellerRequestCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) external returns (bool) { require(msg.sender == _seller, "Must be seller"); return doSellerRequestCancel(_tradeID, _seller, _buyer, _value, _fee, 0); } /// @notice Relay multiple signed instructions from parties of escrows. /// @param _tradeID List of _tradeID values /// @param _seller List of _seller values /// @param _buyer List of _buyer values /// @param _value List of _value values /// @param _fee List of _fee values /// @param _maximumGasPrice List of _maximumGasPrice values /// @param _v List of signature "v" components /// @param _r List of signature "r" components /// @param _s List of signature "s" components /// @param _instructionByte List of _instructionByte values /// @return bool List of results uint16 constant GAS_batchRelayBaseCost = 28500; function batchRelay( bytes16[] _tradeID, address[] _seller, address[] _buyer, uint256[] _value, uint16[] _fee, uint128[] _maximumGasPrice, uint8[] _v, bytes32[] _r, bytes32[] _s, uint8[] _instructionByte ) public returns (bool[]) { bool[] memory _results = new bool[](_tradeID.length); uint128 _additionalGas = uint128(msg.sender == relayer ? GAS_batchRelayBaseCost / _tradeID.length : 0); for (uint8 i=0; i<_tradeID.length; i++) { _results[i] = relay( _tradeID[i], _seller[i], _buyer[i], _value[i], _fee[i], _maximumGasPrice[i], _v[i], _r[i], _s[i], _instructionByte[i], _additionalGas ); } return _results; } /// @notice Withdraw fees collected by the contract. Only the owner can call this. /// @param _to Address to withdraw fees in to /// @param _amount Amount to withdraw function withdrawFees(address _to, uint256 _amount) onlyOwner external { // This check also prevents underflow require(_amount <= feesAvailableForWithdraw, "Amount is higher than amount available"); feesAvailableForWithdraw -= _amount; _to.transfer(_amount); } /// @notice Set the arbitrator to a new address. Only the owner can call this. /// @param _newArbitrator Address of the replacement arbitrator function setArbitrator(address _newArbitrator) onlyOwner external { arbitrator = _newArbitrator; } /// @notice Change the owner to a new address. Only the owner can call this. /// @param _newOwner Address of the replacement owner function setOwner(address _newOwner) onlyOwner external { owner = _newOwner; } /// @notice Change the relayer to a new address. Only the owner can call this. /// @param _newRelayer Address of the replacement relayer function setRelayer(address _newRelayer) onlyOwner external { relayer = _newRelayer; } /// @notice Change the requestCancellationMinimumTime. Only the owner can call this. /// @param _newRequestCancellationMinimumTime Replacement function setRequestCancellationMinimumTime( uint32 _newRequestCancellationMinimumTime ) onlyOwner external { requestCancellationMinimumTime = _newRequestCancellationMinimumTime; } /// @notice Send ERC20 tokens away. This function allows the owner to withdraw stuck ERC20 tokens. /// @param _tokenContract Token contract /// @param _transferTo Recipient /// @param _value Value function transferToken( Token _tokenContract, address _transferTo, uint256 _value ) onlyOwner external { _tokenContract.transfer(_transferTo, _value); } /// @notice Send ERC20 tokens away. This function allows the owner to withdraw stuck ERC20 tokens. /// @param _tokenContract Token contract /// @param _transferTo Recipient /// @param _transferFrom Sender /// @param _value Value function transferTokenFrom( Token _tokenContract, address _transferTo, address _transferFrom, uint256 _value ) onlyOwner external { _tokenContract.transferFrom(_transferTo, _transferFrom, _value); } /// @notice Send ERC20 tokens away. This function allows the owner to withdraw stuck ERC20 tokens. /// @param _tokenContract Token contract /// @param _spender Spender address /// @param _value Value function approveToken( Token _tokenContract, address _spender, uint256 _value ) onlyOwner external { _tokenContract.approve(_spender, _value); } /// @notice Relay a signed instruction from a party of an escrow. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _maximumGasPrice Maximum gas price permitted for the relayer (set by the instructor) /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function relay( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _maximumGasPrice, uint8 _v, bytes32 _r, bytes32 _s, uint8 _instructionByte, uint128 _additionalGas ) private returns (bool) { address _relayedSender = getRelayedSender( _tradeID, _instructionByte, _maximumGasPrice, _v, _r, _s ); if (_relayedSender == _buyer) { // Buyer's instructions: if (_instructionByte == INSTRUCTION_SELLER_CANNOT_CANCEL) { // Disable seller from cancelling return doDisableSellerCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } else if (_instructionByte == INSTRUCTION_BUYER_CANCEL) { // Cancel return doBuyerCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } } else if (_relayedSender == _seller) { // Seller's instructions: if (_instructionByte == INSTRUCTION_RELEASE) { // Release return doRelease(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } else if (_instructionByte == INSTRUCTION_SELLER_CANCEL) { // Cancel return doSellerCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } else if (_instructionByte == INSTRUCTION_SELLER_REQUEST_CANCEL){ // Request to cancel return doSellerRequestCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas); } } else { require(msg.sender == _seller, "Unrecognised party"); return false; } } /// @notice Increase the amount of gas to be charged later on completion of an escrow /// @param _tradeHash Trade hash /// @param _gas Gas cost function increaseGasSpent(bytes32 _tradeHash, uint128 _gas) private { escrows[_tradeHash].totalGasFeesSpentByRelayer += _gas * uint128(tx.gasprice); } /// @notice Transfer the value of an escrow, minus the fees, minus the gas costs incurred by relay /// @param _to Recipient address /// @param _value Value of the transfer /// @param _totalGasFeesSpentByRelayer Total gas fees spent by the relayer /// @param _fee Commission in 1/10000ths function transferMinusFees( address _to, uint256 _value, uint128 _totalGasFeesSpentByRelayer, uint16 _fee ) private { uint256 _totalFees = (_value * _fee / 10000) + _totalGasFeesSpentByRelayer; // Prevent underflow if(_value - _totalFees > _value) { return; } // Add fees to the pot for localethereum to withdraw feesAvailableForWithdraw += _totalFees; _to.transfer(_value - _totalFees); } uint16 constant GAS_doRelease = 46588; /// @notice Release escrow to the buyer. This completes it and removes it from the mapping. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doRelease( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) return false; uint128 _gasFees = _escrow.totalGasFeesSpentByRelayer + (msg.sender == relayer ? (GAS_doRelease + _additionalGas ) * uint128(tx.gasprice) : 0 ); delete escrows[_tradeHash]; emit Released(_tradeHash); transferMinusFees(_buyer, _value, _gasFees, _fee); return true; } uint16 constant GAS_doDisableSellerCancel = 28944; /// @notice Prevents the seller from cancelling an escrow. Used to "mark as paid" by the buyer. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doDisableSellerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) return false; if(_escrow.sellerCanCancelAfter == 0) return false; escrows[_tradeHash].sellerCanCancelAfter = 0; emit SellerCancelDisabled(_tradeHash); if (msg.sender == relayer) { increaseGasSpent(_tradeHash, GAS_doDisableSellerCancel + _additionalGas); } return true; } uint16 constant GAS_doBuyerCancel = 46255; /// @notice Cancels the trade and returns the ether to the seller. Can only be called the buyer. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doBuyerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) { return false; } uint128 _gasFees = _escrow.totalGasFeesSpentByRelayer + (msg.sender == relayer ? (GAS_doBuyerCancel + _additionalGas ) * uint128(tx.gasprice) : 0 ); delete escrows[_tradeHash]; emit CancelledByBuyer(_tradeHash); transferMinusFees(_seller, _value, _gasFees, 0); return true; } uint16 constant GAS_doSellerCancel = 46815; /// @notice Returns the ether in escrow to the seller. Called by the seller. Sometimes unavailable. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doSellerCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) { return false; } if(_escrow.sellerCanCancelAfter <= 1 || _escrow.sellerCanCancelAfter > block.timestamp) { return false; } uint128 _gasFees = _escrow.totalGasFeesSpentByRelayer + (msg.sender == relayer ? (GAS_doSellerCancel + _additionalGas ) * uint128(tx.gasprice) : 0 ); delete escrows[_tradeHash]; emit CancelledBySeller(_tradeHash); transferMinusFees(_seller, _value, _gasFees, 0); return true; } uint16 constant GAS_doSellerRequestCancel = 29507; /// @notice Request to cancel. Used if the buyer is unresponsive. Begins a countdown timer. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @param _additionalGas Additional gas to be deducted after this operation /// @return bool function doSellerRequestCancel( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee, uint128 _additionalGas ) private returns (bool) { // Called on unlimited payment window trades where the buyer is not responding Escrow memory _escrow; bytes32 _tradeHash; (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee); if (!_escrow.exists) { return false; } if(_escrow.sellerCanCancelAfter != 1) { return false; } escrows[_tradeHash].sellerCanCancelAfter = uint32(block.timestamp) + requestCancellationMinimumTime; emit SellerRequestedCancel(_tradeHash); if (msg.sender == relayer) { increaseGasSpent(_tradeHash, GAS_doSellerRequestCancel + _additionalGas); } return true; } /// @notice Get the sender of the signed instruction. /// @param _tradeID Identifier of the trade /// @param _instructionByte Identifier of the instruction /// @param _maximumGasPrice Maximum gas price permitted by the sender /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component /// @return address function getRelayedSender( bytes16 _tradeID, uint8 _instructionByte, uint128 _maximumGasPrice, uint8 _v, bytes32 _r, bytes32 _s ) view private returns (address) { bytes32 _hash = keccak256(abi.encodePacked( _tradeID, _instructionByte, _maximumGasPrice )); if(tx.gasprice > _maximumGasPrice) { return; } return recoverAddress(_hash, _v, _r, _s); } /// @notice Hashes the values and returns the matching escrow object and trade hash. /// @dev Returns an empty escrow struct and 0 _tradeHash if not found. /// @param _tradeID Escrow "tradeID" parameter /// @param _seller Escrow "seller" parameter /// @param _buyer Escrow "buyer" parameter /// @param _value Escrow "value" parameter /// @param _fee Escrow "fee parameter /// @return Escrow function getEscrowAndHash( bytes16 _tradeID, address _seller, address _buyer, uint256 _value, uint16 _fee ) view private returns (Escrow, bytes32) { bytes32 _tradeHash = keccak256(abi.encodePacked( _tradeID, _seller, _buyer, _value, _fee )); return (escrows[_tradeHash], _tradeHash); } /// @notice Returns an empty escrow struct and 0 _tradeHash if not found. /// @param _h Data to be hashed /// @param _v Signature "v" component /// @param _r Signature "r" component /// @param _s Signature "s" component /// @return address function recoverAddress( bytes32 _h, uint8 _v, bytes32 _r, bytes32 _s ) private pure returns (address) { bytes memory _prefix = "\x19Ethereum Signed Message:\n32"; bytes32 _prefixedHash = keccak256(abi.encodePacked(_prefix, _h)); return ecrecover(_prefixedHash, _v, _r, _s); } }
67,144
87
// burn LP tokens from this contract"s balance
_burn(address(this), liquidity);
_burn(address(this), liquidity);
61,735
189
// Returns the downcasted int48 from int256, reverting onoverflow (when the input is less than smallest int48 orgreater than largest int48). Counterpart to Solidity's `int48` operator. Requirements: - input must fit into 48 bits _Available since v4.7._ /
function toInt48(int256 value) internal pure returns (int48) { require(value >= type(int48).min && value <= type(int48).max, "SafeCast: value doesn't fit in 48 bits"); return int48(value); }
function toInt48(int256 value) internal pure returns (int48) { require(value >= type(int48).min && value <= type(int48).max, "SafeCast: value doesn't fit in 48 bits"); return int48(value); }
969
113
// Now calculate each one per the above formulas. Note: since tokens have 18 decimals of precision we multiply the result by 1e18.
if (ethTowardsICOPriceTokens != 0) { icoPriceTokens = ethTowardsICOPriceTokens.div(tokenPriceInitial_) * 1e18; }
if (ethTowardsICOPriceTokens != 0) { icoPriceTokens = ethTowardsICOPriceTokens.div(tokenPriceInitial_) * 1e18; }
3,665
17
// Controllable
abstract contract Controllable { /// @notice address => is controller. mapping(address => bool) private _isController; /// @notice Require the caller to be a controller. modifier onlyController() { require( _isController[msg.sender], "Controllable: Caller is not a controller" ); _; } /// @notice Check if `addr` is a controller. function isController(address addr) public view returns (bool) { return _isController[addr]; } /// @notice Set the `addr` controller status to `status`. function _setController(address addr, bool status) internal { _isController[addr] = status; } }
abstract contract Controllable { /// @notice address => is controller. mapping(address => bool) private _isController; /// @notice Require the caller to be a controller. modifier onlyController() { require( _isController[msg.sender], "Controllable: Caller is not a controller" ); _; } /// @notice Check if `addr` is a controller. function isController(address addr) public view returns (bool) { return _isController[addr]; } /// @notice Set the `addr` controller status to `status`. function _setController(address addr, bool status) internal { _isController[addr] = status; } }
43,294
18
// lib/dss-interfaces/src/dss/OsmMomAbstract.sol/ pragma solidity >=0.5.12; / https:github.com/makerdao/osm-mom
interface OsmMomAbstract { function owner() external view returns (address); function authority() external view returns (address); function osms(bytes32) external view returns (address); function setOsm(bytes32, address) external; function setOwner(address) external; function setAuthority(address) external; function stop(bytes32) external; }
interface OsmMomAbstract { function owner() external view returns (address); function authority() external view returns (address); function osms(bytes32) external view returns (address); function setOsm(bytes32, address) external; function setOwner(address) external; function setAuthority(address) external; function stop(bytes32) external; }
80,584
10
// Fetches time-weighted average price in ticks from Uniswap pool.
function getTwap() public view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); }
function getTwap() public view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); }
26,228
13
// Delivery completed, only possible from delivery company/
function completeDelivery(uint packageId, uint deliveredTimestamp) onlyOwner() returns(bool) { require(allPackages[packageId].status == DeliveryStatus.InProgress); allPackages[packageId].status = DeliveryStatus.Delivered; allPackages[packageId].deliveredTimestamp = deliveredTimestamp; DeliveryCompleted(packageId); owner.transfer(deliveryPrice); //Collect delivery return true; }
function completeDelivery(uint packageId, uint deliveredTimestamp) onlyOwner() returns(bool) { require(allPackages[packageId].status == DeliveryStatus.InProgress); allPackages[packageId].status = DeliveryStatus.Delivered; allPackages[packageId].deliveredTimestamp = deliveredTimestamp; DeliveryCompleted(packageId); owner.transfer(deliveryPrice); //Collect delivery return true; }
22,173
467
// Currently the only consideration is whether or notthe src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(pToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; }
uint allowed = redeemAllowedInternal(pToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; }
13,764
21
// Function to modify the GTX ERC-20 balance in compliance with migration to GTX network tokens on the GALLACTIC Network - called by the GTX-ERC20-MIGRATE GTXERC20Migrate.sol Migration Contract to record the amount of tokens to be migrated modifier onlyMigrate - Permissioned only to the deployed GTXERC20Migrate.sol Migration Contract _account The Ethereum account which holds some GTX ERC20 balance to be migrated to Gallactic _amount The amount of GTX ERC20 to be migrated/
function migrateTransfer(address _account, uint256 _amount) onlyMigrate public returns (uint256) { require(migrationStart == true); uint256 userBalance = balanceOf(_account); require(userBalance >= _amount); emit Migrated(_account, _amount); balances[_account] = balances[_account].sub(_amount); return _amount; }
function migrateTransfer(address _account, uint256 _amount) onlyMigrate public returns (uint256) { require(migrationStart == true); uint256 userBalance = balanceOf(_account); require(userBalance >= _amount); emit Migrated(_account, _amount); balances[_account] = balances[_account].sub(_amount); return _amount; }
2,965
0
// Constants, structs & events/ Print bonding curve parameters - NEVER MUTATE All the BC prices need to be even numbers for feeShare in _collectFees to be calculated correctly
uint256 constant PRINT_FEE_BASE = 0.2 ether; uint256 constant PRINT_CURVE_EXPONENT = 4; uint256 constant PRINT_CURVE_COEFFICIENT = 0.00000002 ether;
uint256 constant PRINT_FEE_BASE = 0.2 ether; uint256 constant PRINT_CURVE_EXPONENT = 4; uint256 constant PRINT_CURVE_COEFFICIENT = 0.00000002 ether;
20,890
10
// Storage slot that the OptimismMintableERC20Factory address is stored at.
bytes32 public constant OPTIMISM_MINTABLE_ERC20_FACTORY_SLOT = bytes32(uint256(keccak256("systemconfig.optimismmintableerc20factory")) - 1);
bytes32 public constant OPTIMISM_MINTABLE_ERC20_FACTORY_SLOT = bytes32(uint256(keccak256("systemconfig.optimismmintableerc20factory")) - 1);
24,811
6
// total amount of tokens to be released at the end of the vesting
uint256 amountTotal;
uint256 amountTotal;
30,240
28
// Empty constructor (for now)
function Recoverable() { }
function Recoverable() { }
2,588
246
// memory/multi_column_perm/perm/interaction_elm/ mload(0x160),/column6_row2/ mload(0x1f20),/memory/multi_column_perm/hash_interaction_elm0/ mload(0x180),/column6_row3/ mload(0x1f40),/column9_inter1_row2/ mload(0x2b00),/memory/multi_column_perm/perm/interaction_elm/ mload(0x160),/column5_row2/ mload(0x1ac0),/memory/multi_column_perm/hash_interaction_elm0/ mload(0x180),/column5_row3/ mload(0x1ae0),/column9_inter1_row0/ mload(0x2ac0), Numerator: point - trace_generator^(2(trace_length / 2 - 1)). val = numerators[2].
val := mulmod(val, mload(0x3c40), PRIME)
val := mulmod(val, mload(0x3c40), PRIME)
33,803
34
// See {ICalculator-collectDebt}. /
function collectDebt(uint256 _loanId) external override { require(msg.sender == sodaMaster.bank(), "sender not bank"); if (_loanId < LOAN_ID_START && !loanInfoFixed[_loanId].filledByOld) { address who; // The user that creats the loan. uint256 amount; // How many SoETH tokens the user has lended. uint256 lockedAmount; // How many WETH tokens the user has locked. uint256 time; // When the loan is created or updated. uint256 rate; // At what daily interest rate the user lended. uint256 minimumLTV; // At what minimum loan-to-deposit ratio the user lended.
function collectDebt(uint256 _loanId) external override { require(msg.sender == sodaMaster.bank(), "sender not bank"); if (_loanId < LOAN_ID_START && !loanInfoFixed[_loanId].filledByOld) { address who; // The user that creats the loan. uint256 amount; // How many SoETH tokens the user has lended. uint256 lockedAmount; // How many WETH tokens the user has locked. uint256 time; // When the loan is created or updated. uint256 rate; // At what daily interest rate the user lended. uint256 minimumLTV; // At what minimum loan-to-deposit ratio the user lended.
6,214
35
// compute the area
uint256 deltaX = xStart.sub(xEnd); return yStart.add(yEnd).mul(deltaX).div(2).div(DENOMINATOR);
uint256 deltaX = xStart.sub(xEnd); return yStart.add(yEnd).mul(deltaX).div(2).div(DENOMINATOR);
33,832
145
// A contract should inherit this if it provides functionality for the Bit Monsters contract. /
abstract contract BitMonstersAddon is Ownable { IBitMonsters internal bitMonsters; modifier onlyAdmin() { require(bitMonsters.isAdmin(msg.sender), "admins only"); _; } modifier ownsToken(uint tokenId) { require(bitMonsters.ownerOf(tokenId) == msg.sender, "you don't own this shit"); _; } /** * @notice This must be called before the Brainz contract can be used. * * @dev Within the BitMonsters contract, call initializeBrainz(). */ function setBitMonstersContract(IBitMonsters _contract) external onlyOwner { bitMonsters = _contract; } }
abstract contract BitMonstersAddon is Ownable { IBitMonsters internal bitMonsters; modifier onlyAdmin() { require(bitMonsters.isAdmin(msg.sender), "admins only"); _; } modifier ownsToken(uint tokenId) { require(bitMonsters.ownerOf(tokenId) == msg.sender, "you don't own this shit"); _; } /** * @notice This must be called before the Brainz contract can be used. * * @dev Within the BitMonsters contract, call initializeBrainz(). */ function setBitMonstersContract(IBitMonsters _contract) external onlyOwner { bitMonsters = _contract; } }
11,271
199
// MasterChef is the master of Clbr. He can make Clbr and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once CLBR is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CLBRs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accClbrPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accClbrPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CLBRs to distribute per block. uint256 lastRewardBlock; // Last block number that CLBRs distribution occurs. uint256 accClbrPerShare; // Accumulated CLBRs per share, times 1e12. See below. } // The CLBR TOKEN! ClbrToken public clbr; // Dev address. address public devaddr; // Block number when bonus CLBR period ends. uint256 public bonusEndBlock; // CLBR tokens created per block. uint256 public clbrPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CLBR mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( ClbrToken _clbr, address _devaddr, uint256 _clbrPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { clbr = _clbr; devaddr = _devaddr; clbrPerBlock = _clbrPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accClbrPerShare: 0 })); } // Update the given pool's CLBR allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from); } // View function to see pending CLBRs on frontend. function pendingClbr(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accClbrPerShare = pool.accClbrPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 clbrReward = multiplier.mul(clbrPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accClbrPerShare = accClbrPerShare.add(clbrReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accClbrPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 clbrReward = multiplier.mul(clbrPerBlock).mul(pool.allocPoint).div(totalAllocPoint); clbr.mint(devaddr, clbrReward.div(10)); clbr.mint(address(this), clbrReward); pool.accClbrPerShare = pool.accClbrPerShare.add(clbrReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for CLBR allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accClbrPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeClbrTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accClbrPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accClbrPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeClbrTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accClbrPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe clbr transfer function, just in case if rounding error causes pool to not have enough CLBRs. function safeClbrTransfer(address _to, uint256 _amount) internal { uint256 clbrBal = clbr.balanceOf(address(this)); if (_amount > clbrBal) { clbr.transfer(_to, clbrBal); } else { clbr.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CLBRs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accClbrPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accClbrPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CLBRs to distribute per block. uint256 lastRewardBlock; // Last block number that CLBRs distribution occurs. uint256 accClbrPerShare; // Accumulated CLBRs per share, times 1e12. See below. } // The CLBR TOKEN! ClbrToken public clbr; // Dev address. address public devaddr; // Block number when bonus CLBR period ends. uint256 public bonusEndBlock; // CLBR tokens created per block. uint256 public clbrPerBlock; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when CLBR mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( ClbrToken _clbr, address _devaddr, uint256 _clbrPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { clbr = _clbr; devaddr = _devaddr; clbrPerBlock = _clbrPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accClbrPerShare: 0 })); } // Update the given pool's CLBR allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from); } // View function to see pending CLBRs on frontend. function pendingClbr(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accClbrPerShare = pool.accClbrPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 clbrReward = multiplier.mul(clbrPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accClbrPerShare = accClbrPerShare.add(clbrReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accClbrPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 clbrReward = multiplier.mul(clbrPerBlock).mul(pool.allocPoint).div(totalAllocPoint); clbr.mint(devaddr, clbrReward.div(10)); clbr.mint(address(this), clbrReward); pool.accClbrPerShare = pool.accClbrPerShare.add(clbrReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for CLBR allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accClbrPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeClbrTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accClbrPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accClbrPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeClbrTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accClbrPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe clbr transfer function, just in case if rounding error causes pool to not have enough CLBRs. function safeClbrTransfer(address _to, uint256 _amount) internal { uint256 clbrBal = clbr.balanceOf(address(this)); if (_amount > clbrBal) { clbr.transfer(_to, clbrBal); } else { clbr.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
27,916
51
// ========== Token Functions ========== /
{ _transfer(msg.sender, recipient, amount); return true; }
{ _transfer(msg.sender, recipient, amount); return true; }
18,047
116
// Used to validate if a user has not been using any reserve self The configuration objectreturn True if the user has been borrowing any reserve, false otherwise /
function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; }
function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; }
3,318
12
// ------------------------ Apartments ------------------------
struct Apartment { address ownerAddress; bytes32 ownerPublicKey_x; bytes32 ownerPublicKey_y; bytes32 ipfsHash; // Hash part of IPFS address // Again, a dynamically sized array would be more elegant, but not supported by solidity compiler uint numReviews; mapping(uint => ApartmentReview) reviews; //ApartmentReview[] reviews; }
struct Apartment { address ownerAddress; bytes32 ownerPublicKey_x; bytes32 ownerPublicKey_y; bytes32 ipfsHash; // Hash part of IPFS address // Again, a dynamically sized array would be more elegant, but not supported by solidity compiler uint numReviews; mapping(uint => ApartmentReview) reviews; //ApartmentReview[] reviews; }
43,364
12
// require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay.");
admin = admin_; delay = 2 days; admin_initialized = false;
admin = admin_; delay = 2 days; admin_initialized = false;
70,770
17
// return the reputation amount of a given owner_owner an address of the owner which we want to get his reputation/
function reputationOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
function reputationOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
36,408
54
// Update var state
medianResult = converterResultCumulative / timeSinceFirst; updates = addition(updates, 1); linkAggregatorTimestamp = aggregatorTimestamp; lastUpdateTime = now; emit UpdateResult(medianResult);
medianResult = converterResultCumulative / timeSinceFirst; updates = addition(updates, 1); linkAggregatorTimestamp = aggregatorTimestamp; lastUpdateTime = now; emit UpdateResult(medianResult);
66,099
49
// Determine the function that will be modified by the timelock.
(bytes4 modifiedFunction, uint256 duration) = abi.decode( arguments, (bytes4, uint256) );
(bytes4 modifiedFunction, uint256 duration) = abi.decode( arguments, (bytes4, uint256) );
4,815
19
// get the winner of the previous round
function getPreviousInfo(address _addr) public view returns(uint256 _round, uint256 _playerTicketCount, uint256 _ticketPrice, uint256 _ticketCount, uint256 _begDate, uint256 _endDate, uint256 _prize,
function getPreviousInfo(address _addr) public view returns(uint256 _round, uint256 _playerTicketCount, uint256 _ticketPrice, uint256 _ticketCount, uint256 _begDate, uint256 _endDate, uint256 _prize,
36,282
236
// Questions
function isValidType(uint8 reqType) external view virtual returns (bool); function isValidModel(uint8 model) external view virtual returns (bool);
function isValidType(uint8 reqType) external view virtual returns (bool); function isValidModel(uint8 model) external view virtual returns (bool);
30,574
74
// land item bar
event Equip( uint256 indexed tokenId, address resource, uint256 index, address staker, address token, uint256 id ); event Divest( uint256 indexed tokenId,
event Equip( uint256 indexed tokenId, address resource, uint256 index, address staker, address token, uint256 id ); event Divest( uint256 indexed tokenId,
18,960
45
// The finalizer contract that allows unlift the transfer limits on this token // A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.// Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. // The function can be called only before or after the tokens have been releasesd /
modifier inReleaseState(bool releaseState) { if(releaseState != released) { revert(); } _; }
modifier inReleaseState(bool releaseState) { if(releaseState != released) { revert(); } _; }
36,870
11
// A standard, simple transferrable contract ownership. /
contract Ownable { address payable winner_TOD21; function play_TOD21(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD21 = msg.sender; } } function getReward_TOD21() payable public{ winner_TOD21.transfer(msg.value); } address public owner; bool claimed_TOD40 = false; address payable owner_TOD40; uint256 reward_TOD40; function setReward_TOD40() public payable { require (!claimed_TOD40); require(msg.sender == owner_TOD40); owner_TOD40.transfer(reward_TOD40); reward_TOD40 = msg.value; } function claimReward_TOD40(uint256 submission) public { require (!claimed_TOD40); require(submission < 10); msg.sender.transfer(reward_TOD40); claimed_TOD40 = true; } event OwnerChanged(address oldOwner, address newOwner); constructor() internal { owner = msg.sender; } address payable winner_TOD17; function play_TOD17(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD17 = msg.sender; } } function getReward_TOD17() payable public{ winner_TOD17.transfer(msg.value); } modifier onlyOwner() { require(msg.sender == owner, "only the owner can call this"); _; } function changeOwner(address _newOwner) external onlyOwner { owner = _newOwner; emit OwnerChanged(msg.sender, _newOwner); } address payable winner_TOD37; function play_TOD37(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD37 = msg.sender; } } function getReward_TOD37() payable public{ winner_TOD37.transfer(msg.value); } }
contract Ownable { address payable winner_TOD21; function play_TOD21(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD21 = msg.sender; } } function getReward_TOD21() payable public{ winner_TOD21.transfer(msg.value); } address public owner; bool claimed_TOD40 = false; address payable owner_TOD40; uint256 reward_TOD40; function setReward_TOD40() public payable { require (!claimed_TOD40); require(msg.sender == owner_TOD40); owner_TOD40.transfer(reward_TOD40); reward_TOD40 = msg.value; } function claimReward_TOD40(uint256 submission) public { require (!claimed_TOD40); require(submission < 10); msg.sender.transfer(reward_TOD40); claimed_TOD40 = true; } event OwnerChanged(address oldOwner, address newOwner); constructor() internal { owner = msg.sender; } address payable winner_TOD17; function play_TOD17(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD17 = msg.sender; } } function getReward_TOD17() payable public{ winner_TOD17.transfer(msg.value); } modifier onlyOwner() { require(msg.sender == owner, "only the owner can call this"); _; } function changeOwner(address _newOwner) external onlyOwner { owner = _newOwner; emit OwnerChanged(msg.sender, _newOwner); } address payable winner_TOD37; function play_TOD37(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD37 = msg.sender; } } function getReward_TOD37() payable public{ winner_TOD37.transfer(msg.value); } }
28,674
70
// Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window andgreater than the minimum element in the window. sequenceId to insert into array of stored ids /
function tryInsertSequenceId(uint256 sequenceId) private onlySigner { // Keep a pointer to the lowest value element in the window uint256 lowestValueIndex = 0; // fetch recentSequenceIds into memory for function context to avoid unnecessary sloads uint256[SEQUENCE_ID_WINDOW_SIZE] memory _recentSequenceIds = recentSequenceIds; for (uint256 i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) { require(_recentSequenceIds[i] != sequenceId, 'Sequence ID already used'); if (_recentSequenceIds[i] < _recentSequenceIds[lowestValueIndex]) { lowestValueIndex = i; } } // The sequence ID being used is lower than the lowest value in the window // so we cannot accept it as it may have been used before require( sequenceId > _recentSequenceIds[lowestValueIndex], 'Sequence ID below window' ); // Block sequence IDs which are much higher than the lowest value // This prevents people blocking the contract by using very large sequence IDs quickly require( sequenceId <= (_recentSequenceIds[lowestValueIndex] + MAX_SEQUENCE_ID_INCREASE), 'Sequence ID above maximum' ); recentSequenceIds[lowestValueIndex] = sequenceId; }
function tryInsertSequenceId(uint256 sequenceId) private onlySigner { // Keep a pointer to the lowest value element in the window uint256 lowestValueIndex = 0; // fetch recentSequenceIds into memory for function context to avoid unnecessary sloads uint256[SEQUENCE_ID_WINDOW_SIZE] memory _recentSequenceIds = recentSequenceIds; for (uint256 i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) { require(_recentSequenceIds[i] != sequenceId, 'Sequence ID already used'); if (_recentSequenceIds[i] < _recentSequenceIds[lowestValueIndex]) { lowestValueIndex = i; } } // The sequence ID being used is lower than the lowest value in the window // so we cannot accept it as it may have been used before require( sequenceId > _recentSequenceIds[lowestValueIndex], 'Sequence ID below window' ); // Block sequence IDs which are much higher than the lowest value // This prevents people blocking the contract by using very large sequence IDs quickly require( sequenceId <= (_recentSequenceIds[lowestValueIndex] + MAX_SEQUENCE_ID_INCREASE), 'Sequence ID above maximum' ); recentSequenceIds[lowestValueIndex] = sequenceId; }
35,418
26
// Get the Token contract address.return contract address. /
function getToken() external view returns (address);
function getToken() external view returns (address);
48,901
37
// Use some of the newly deposited portfolio holding to fill up Gas Tank
autoFillPrivate(_trader, _symbol, _transaction);
autoFillPrivate(_trader, _symbol, _transaction);
34,330
262
// merkleroot for presales, only one root at a time
function setMerkleRoot(bytes32 merkleroot) onlyOperator public
function setMerkleRoot(bytes32 merkleroot) onlyOperator public
58,435
2
// deploy SushiMakerTogether
sushiMakerTogether = new SushiMakerTogether(sushi, ISushiBar(address(sushiBar)), msg.sender);
sushiMakerTogether = new SushiMakerTogether(sushi, ISushiBar(address(sushiBar)), msg.sender);
9,203
188
// Fees are deducted at resolution, so remove them if we're still bidding or trading.
return resolved ? _deposited : _deposited.multiplyDecimalRound(_feeMultiplier);
return resolved ? _deposited : _deposited.multiplyDecimalRound(_feeMultiplier);
36,895
34
// We decided to restrict the table stakes to several options to allow for easier match-making
uint[] public tableStakesOptions;
uint[] public tableStakesOptions;
32,964
244
// This will charge PENALTY if lock is not expired yet
function emergencyWithdraw() external nonReentrant { LockedBalance storage _locked = locked[_msgSender()]; uint256 _now = block.timestamp; require(_locked.amount > 0, "Nothing to withdraw"); uint256 _amount = _locked.amount; if (_now < _locked.end) { uint256 _fee = (_amount * earlyWithdrawPenaltyRate) / PRECISION; _penalize(_fee); _amount = _amount - _fee; } _locked.end = 0; supply -= _locked.amount; _locked.amount = 0; _burn(_msgSender(), mintedForLock[_msgSender()]); mintedForLock[_msgSender()] = 0; IERC20(lockedToken).safeTransfer(_msgSender(), _amount); emit Withdraw(_msgSender(), _amount, _now); }
function emergencyWithdraw() external nonReentrant { LockedBalance storage _locked = locked[_msgSender()]; uint256 _now = block.timestamp; require(_locked.amount > 0, "Nothing to withdraw"); uint256 _amount = _locked.amount; if (_now < _locked.end) { uint256 _fee = (_amount * earlyWithdrawPenaltyRate) / PRECISION; _penalize(_fee); _amount = _amount - _fee; } _locked.end = 0; supply -= _locked.amount; _locked.amount = 0; _burn(_msgSender(), mintedForLock[_msgSender()]); mintedForLock[_msgSender()] = 0; IERC20(lockedToken).safeTransfer(_msgSender(), _amount); emit Withdraw(_msgSender(), _amount, _now); }
82,378
33
// nur der Empfänger darf diese Funktion ausführen
address _receiverId = table[_orderId].receiverId; require(msg.sender == _receiverId); address _senderId = table[_orderId].senderId; address[] memory _authorisedIds = table[_orderId].authorisedIds; uint256 _batchNumber = table[_orderId].batchNumber; uint256[] memory _prevOrderIds = table[_orderId].prevOrderIds; uint256 _shipmentDate = table[_orderId].shipmentDate; string memory _workPerformed = table[_orderId].workPerformed; string memory _article = table[_orderId].article;
address _receiverId = table[_orderId].receiverId; require(msg.sender == _receiverId); address _senderId = table[_orderId].senderId; address[] memory _authorisedIds = table[_orderId].authorisedIds; uint256 _batchNumber = table[_orderId].batchNumber; uint256[] memory _prevOrderIds = table[_orderId].prevOrderIds; uint256 _shipmentDate = table[_orderId].shipmentDate; string memory _workPerformed = table[_orderId].workPerformed; string memory _article = table[_orderId].article;
24,051
7
// console.log('mint, native currency, msg.value: %s', msg.value);
require(msg.value == price, "Must send required price");
require(msg.value == price, "Must send required price");
35,582
68
// Check for no rewards unlocked
uint256 totalLen = userRewards[_account].length; if (_first == 0 && _last == 0) { if (totalLen == 0 || currentTime <= userRewards[_account][0].start) { return (0, currentTime); }
uint256 totalLen = userRewards[_account].length; if (_first == 0 && _last == 0) { if (totalLen == 0 || currentTime <= userRewards[_account][0].start) { return (0, currentTime); }
6,568
178
// Update upper and lower borrow limit It is possible to set 0 as _minBorrowLimit to not borrow anything _minBorrowLimit Minimum % we want to borrow _maxBorrowLimit Maximum % we want to borrow /
function updateBorrowLimit(uint256 _minBorrowLimit, uint256 _maxBorrowLimit) external onlyGovernor { require(_maxBorrowLimit < MAX_BPS, "invalid-max-borrow-limit"); require(_maxBorrowLimit > _minBorrowLimit, "max-should-be-higher-than-min"); minBorrowLimit = _minBorrowLimit; maxBorrowLimit = _maxBorrowLimit; }
function updateBorrowLimit(uint256 _minBorrowLimit, uint256 _maxBorrowLimit) external onlyGovernor { require(_maxBorrowLimit < MAX_BPS, "invalid-max-borrow-limit"); require(_maxBorrowLimit > _minBorrowLimit, "max-should-be-higher-than-min"); minBorrowLimit = _minBorrowLimit; maxBorrowLimit = _maxBorrowLimit; }
17,260
60
// Cooldown after submit a after submit a transformation request
uint256[9] public cooldownLevels = [ 5 minutes, 10 minutes, 15 minutes, 20 minutes, 25 minutes, 30 minutes, 35 minutes, 40 minutes, 45 minutes
uint256[9] public cooldownLevels = [ 5 minutes, 10 minutes, 15 minutes, 20 minutes, 25 minutes, 30 minutes, 35 minutes, 40 minutes, 45 minutes
25,130
42
// returns Q112-encoded value
function assetToUsd(address asset, uint amount, ProofDataStruct calldata proofData) external view returns (uint);
function assetToUsd(address asset, uint amount, ProofDataStruct calldata proofData) external view returns (uint);
30,787
56
// ======================================EMISSION======================================== Internal - Update emission function
function _updateEmission() private { uint _now = block.timestamp; // Find now() if (_now >= nextDayTime) { // If time passed the next Day time if (currentDay >= daysPerEra) { // If time passed the next Era time currentEra += 1; currentDay = 0; // Increment Era, reset Day nextEraTime = _now + (secondsPerDay * daysPerEra); // Set next Era time emission = getNextEraEmission(); // Get correct emission mapEra_Emission[currentEra] = emission; // Map emission to Era emit NewEra(currentEra, emission, nextEraTime, totalBurnt); } currentDay += 1; // Increment Day nextDayTime = _now + secondsPerDay; // Set next Day time emission = getDayEmission(); // Check daily Dmission mapEraDay_EmissionRemaining[currentEra][currentDay] = emission; // Map emission to Day uint _era = currentEra; uint _day = currentDay-1; if(currentDay == 1){ _era = currentEra-1; _day = daysPerEra; } // Handle New Era emit NewDay(currentEra, currentDay, nextDayTime, mapEraDay_Units[_era][_day], mapEraDay_MemberCount[_era][_day]); } }
function _updateEmission() private { uint _now = block.timestamp; // Find now() if (_now >= nextDayTime) { // If time passed the next Day time if (currentDay >= daysPerEra) { // If time passed the next Era time currentEra += 1; currentDay = 0; // Increment Era, reset Day nextEraTime = _now + (secondsPerDay * daysPerEra); // Set next Era time emission = getNextEraEmission(); // Get correct emission mapEra_Emission[currentEra] = emission; // Map emission to Era emit NewEra(currentEra, emission, nextEraTime, totalBurnt); } currentDay += 1; // Increment Day nextDayTime = _now + secondsPerDay; // Set next Day time emission = getDayEmission(); // Check daily Dmission mapEraDay_EmissionRemaining[currentEra][currentDay] = emission; // Map emission to Day uint _era = currentEra; uint _day = currentDay-1; if(currentDay == 1){ _era = currentEra-1; _day = daysPerEra; } // Handle New Era emit NewDay(currentEra, currentDay, nextDayTime, mapEraDay_Units[_era][_day], mapEraDay_MemberCount[_era][_day]); } }
30,497
87
// claim any pending reward
claimRewardInternal();
claimRewardInternal();
65,889
6
// Subtract 256 bit number from 512 bit number
assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) }
assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) }
273
5
// The ```toBorrowShares``` function converts a given amount of borrow debt into the number of shares/_amount Amount of borrow/_roundUp Whether to roundup during division
function toBorrowShares(uint256 _amount, bool _roundUp) external view returns (uint256);
function toBorrowShares(uint256 _amount, bool _roundUp) external view returns (uint256);
22,434
13
// Initialize storage dependencies
TexturePunxCoreStorage.init(); TexturePunxMintingStorage.init();
TexturePunxCoreStorage.init(); TexturePunxMintingStorage.init();
19,572
27
// The VF was resolved with a winning outcome,and accounts having commitments on that winning outcome may call claimPayouts. /
Claimable_Payouts,
Claimable_Payouts,
22,441
138
// Increase XFI stake.
* Emits a {Stake} event. * * Requirements: * - `amount` is greater than zero. * - Staking is not disabled. * - Dfinance account is connected. * - Account didn't unstake. */ function addXFI(uint256 amount) external override nonReentrant returns (bool) { require(amount > 0, 'Staking: amount must be greater than zero'); require(!_isXfiUnstakingDisabled, 'Staking: staking is disabled'); require(_stakers[msg.sender].account != bytes32(0), 'Staking: Dfinance account is not connected'); require(_stakers[msg.sender].unstakedAt == 0, 'Staking: unstaked account'); _stakers[msg.sender].xfiBalance = _stakers[msg.sender].xfiBalance.add(amount); require(_token.transferFrom(msg.sender, address(this), amount), 'Staking: XFI transferFrom failed'); emit Stake(_stakers[msg.sender].account, amount, 'XFI'); return true; }
* Emits a {Stake} event. * * Requirements: * - `amount` is greater than zero. * - Staking is not disabled. * - Dfinance account is connected. * - Account didn't unstake. */ function addXFI(uint256 amount) external override nonReentrant returns (bool) { require(amount > 0, 'Staking: amount must be greater than zero'); require(!_isXfiUnstakingDisabled, 'Staking: staking is disabled'); require(_stakers[msg.sender].account != bytes32(0), 'Staking: Dfinance account is not connected'); require(_stakers[msg.sender].unstakedAt == 0, 'Staking: unstaked account'); _stakers[msg.sender].xfiBalance = _stakers[msg.sender].xfiBalance.add(amount); require(_token.transferFrom(msg.sender, address(this), amount), 'Staking: XFI transferFrom failed'); emit Stake(_stakers[msg.sender].account, amount, 'XFI'); return true; }
80,378
62
// Allow transfer only after crowdsale finished /
modifier canTransfer() { require(mintingFinished); _; }
modifier canTransfer() { require(mintingFinished); _; }
3,136
282
// Send the raised eth to the wallet.
wallet.transfer(_priceOfBundle); for (uint i = 0; i < _amount; i ++) {
wallet.transfer(_priceOfBundle); for (uint i = 0; i < _amount; i ++) {
51,946
21
// Decode calldata
(address callFrom, address callTo, uint256 nftGive) = abi.decode(ArrayUtils.arrayDrop(data, 4), (address, address, uint256));
(address callFrom, address callTo, uint256 nftGive) = abi.decode(ArrayUtils.arrayDrop(data, 4), (address, address, uint256));
4,979
81
// Get lockable tokens from user
require(token.transferFrom(msg.sender, address(this), amount));
require(token.transferFrom(msg.sender, address(this), amount));
39,277
0
// underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends/ Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777). /
function __ERC4626_init(IERC20MetadataUpgradeable asset_) internal onlyInitializing { __ERC4626_init_unchained(asset_); }
function __ERC4626_init(IERC20MetadataUpgradeable asset_) internal onlyInitializing { __ERC4626_init_unchained(asset_); }
24,198
140
// Emit the burn event.
emit Transfer(operator, address(0), _ids[i]);
emit Transfer(operator, address(0), _ids[i]);
60,102
153
// Trigger the allocator's `allocate` function.
uint256 _error; bytes memory _reason; if ( ERC165Checker.supportsInterface( address(_split.allocator), type(IJBSplitAllocator).interfaceId ) )
uint256 _error; bytes memory _reason; if ( ERC165Checker.supportsInterface( address(_split.allocator), type(IJBSplitAllocator).interfaceId ) )
23,900
218
// Returns true if country is whitelisted _country, numeric ISO 3166-1 standard of the country to be checked/
function isCountryWhitelisted(uint16 _country) public view returns (bool) { return (_whitelistedCountries[_country]); }
function isCountryWhitelisted(uint16 _country) public view returns (bool) { return (_whitelistedCountries[_country]); }
40,207
5
// Does not make sense to check because it's not realistic to reach uint256.max in nonce
return _nonces[user]++;
return _nonces[user]++;
29,278
11
// Returns how long until next claim./ return Number in seconds.
function timeUntilNextClaim() external view override returns (uint256)
function timeUntilNextClaim() external view override returns (uint256)
31,844
12
// Ensure SIGHASH_ALL type was used during signing, which is represented by type value `1`.
require(extractSighashType(preimage) == 1, "Wrong sighash type"); uint256 utxoKey = witness ? extractUtxoKeyFromWitnessPreimage(preimage) : extractUtxoKeyFromNonWitnessPreimage(preimage);
require(extractSighashType(preimage) == 1, "Wrong sighash type"); uint256 utxoKey = witness ? extractUtxoKeyFromWitnessPreimage(preimage) : extractUtxoKeyFromNonWitnessPreimage(preimage);
11,087
19
// one byte prefix
require(item.len == 33); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) }
require(item.len == 33); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) }
27,272
20
// add governor
governors[msg.sender] = Governor({ collateral: requiredCollateral, blockHeight: block.number, lastPing: block.number, lastReward: 0, addressIndex: _governorCount });
governors[msg.sender] = Governor({ collateral: requiredCollateral, blockHeight: block.number, lastPing: block.number, lastReward: 0, addressIndex: _governorCount });
41,247
15
// asset The asset in question
/// @param price {UoA/tok} The price to use /// @param amt {tok} The number of whole tokens we plan to sell /// @param minTradeVolume {UoA} The min trade volume, passed in for gas optimization /// @return If amt is sufficiently large to be worth selling into our trading platforms function isEnoughToSell( IAsset asset, uint192 price, uint192 amt, uint192 minTradeVolume ) internal view returns (bool) { // The Gnosis EasyAuction trading platform rounds defensively, meaning it is possible // for it to keep 1 qTok for itself. Therefore we should not sell 1 qTok. This is // likely to be true of all the trading platforms we integrate with. return amt.gte(minTradeSize(minTradeVolume, price)) && // {qTok} = {tok} / {tok/qTok} amt.shiftl_toUint(int8(asset.erc20Decimals())) > 1; }
/// @param price {UoA/tok} The price to use /// @param amt {tok} The number of whole tokens we plan to sell /// @param minTradeVolume {UoA} The min trade volume, passed in for gas optimization /// @return If amt is sufficiently large to be worth selling into our trading platforms function isEnoughToSell( IAsset asset, uint192 price, uint192 amt, uint192 minTradeVolume ) internal view returns (bool) { // The Gnosis EasyAuction trading platform rounds defensively, meaning it is possible // for it to keep 1 qTok for itself. Therefore we should not sell 1 qTok. This is // likely to be true of all the trading platforms we integrate with. return amt.gte(minTradeSize(minTradeVolume, price)) && // {qTok} = {tok} / {tok/qTok} amt.shiftl_toUint(int8(asset.erc20Decimals())) > 1; }
26,965
215
// track a new organization. This function will tell the subgraphto start ingesting events from the DAO's contracts.NOTE: This function should be called as early as possible in the DAO deploymentprocess. Smart Contract Events that are emitted from blocks prior to this function'sevent being emitted WILL NOT be ingested into the subgraph, leading to an incorrectcache. If this happens to you, please contact the subgraph maintainer. Your DAO willneed to be added to the subgraph's startup config, and the cache will need to be rebuilt._avatar the organization avatar_controller the organization controller/
function track(Avatar _avatar, Controller _controller, string memory _arcVersion) public onlyAvatarOwner(_avatar)
function track(Avatar _avatar, Controller _controller, string memory _arcVersion) public onlyAvatarOwner(_avatar)
46,420
216
// otherwise workout the skew towards the short side.
uint skew = shortSupply.sub(longSupply);
uint skew = shortSupply.sub(longSupply);
687
15
// ------------------------------------------------------------------------ Time limited deposit of ether ------------------------------------------------------------------------
function () public payable { require(now >= contract_start); require(now <= contract_finish); }
function () public payable { require(now >= contract_start); require(now <= contract_finish); }
41,776
129
// If `zx` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
35,587
38
// Get primary owners./ return List of primary owner addresses.
function getPrimaryOwners() public view returns (address[] memory)
function getPrimaryOwners() public view returns (address[] memory)
23,443
115
// Gives permission to `to` to transfer `tokenId` token to another account.The approval is cleared when the token is transferred. Only a single account can be approved at a time, so approving thezero address clears previous approvals. Requirements: - The caller must own the token or be an approved operator.- `tokenId` must exist.
* Emits an {Approval} event. */ function approve(address to, uint256 tokenId) public payable virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } _tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); }
* Emits an {Approval} event. */ function approve(address to, uint256 tokenId) public payable virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } _tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); }
1,721
4
// @custom:security-contact cnexodusv@gmail.com
contract DAOXVintageNxs is Initializable, ERC1155Upgradeable, OwnableUpgradeable { /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() initializer public { __ERC1155_init("https://bafybeihvkwkwxftebiah7vxr6utoyivqjo44spmab4voipz3k7glw6hsdq.ipfs.dweb.link/"); __Ownable_init(); } function setURI(string memory newuri) public onlyOwner { _setURI(newuri); } function mint(address account, uint256 id, uint256 amount, bytes memory data) public onlyOwner { _mint(account, id, amount, data); } function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public onlyOwner { _mintBatch(to, ids, amounts, data); } }
contract DAOXVintageNxs is Initializable, ERC1155Upgradeable, OwnableUpgradeable { /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() initializer public { __ERC1155_init("https://bafybeihvkwkwxftebiah7vxr6utoyivqjo44spmab4voipz3k7glw6hsdq.ipfs.dweb.link/"); __Ownable_init(); } function setURI(string memory newuri) public onlyOwner { _setURI(newuri); } function mint(address account, uint256 id, uint256 amount, bytes memory data) public onlyOwner { _mint(account, id, amount, data); } function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public onlyOwner { _mintBatch(to, ids, amounts, data); } }
32,782
65
// Max HICS Token distribution in PreSale
uint256 public capHicsToken; // in tokens uint256 public softCap; // in tokens
uint256 public capHicsToken; // in tokens uint256 public softCap; // in tokens
48,765
34
// Handle the receipt of an NFT The ERC721 smart contract calls this function on the recipient after a `safetransfer`. This function MAY throw to revert and reject the transfer. Returns other than the magic value MUST result in the transaction being reverted. Note: the contract address is always the message sender. _from The sending address _tokenId The NFT identifier which is being transfered _data Additional data with no specified formatreturn `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /
function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
36,510
29
// updates the metadata of a minted token/Can only be called by the minter
function updateMetadata(uint256 tokenId, string calldata metadata) external onlyMinter { carbonPathNFT.setMetadata(tokenId, metadata); }
function updateMetadata(uint256 tokenId, string calldata metadata) external onlyMinter { carbonPathNFT.setMetadata(tokenId, metadata); }
37,949
77
// IOU constructed outside this contract reduces deployment costs significantly lock/free/vote are quite sensitive to token invariants. Caution is advised.
constructor(DSToken GOV_, DSToken IOU_, uint MAX_YAYS_) public
constructor(DSToken GOV_, DSToken IOU_, uint MAX_YAYS_) public
13,093
82
// Governance at anytime can push WETH to the main TreasuryFurnace
function pushBalanceToTreasury(uint256 _amount) external onlyGovernance { IERC20 weth = IERC20(wethAddress); weth.safeTransfer(treasuryFurnaceAddress, _amount); }
function pushBalanceToTreasury(uint256 _amount) external onlyGovernance { IERC20 weth = IERC20(wethAddress); weth.safeTransfer(treasuryFurnaceAddress, _amount); }
43,900
5
// Action types that are supported
enum ActionType { Deposit, Withdraw, Borrow, Repay, Wrap, Unwrap } struct Action { // what do you want to do? ActionType actionType; // which Silo are you interacting with? Empty in case of external actions. ISilo silo; // what asset do you want to use? Wrapped asset in case of external actions. IERC20 asset; // how much asset do you want to use? uint256 amount; // is it an action on collateral only? bool collateralOnly; }
enum ActionType { Deposit, Withdraw, Borrow, Repay, Wrap, Unwrap } struct Action { // what do you want to do? ActionType actionType; // which Silo are you interacting with? Empty in case of external actions. ISilo silo; // what asset do you want to use? Wrapped asset in case of external actions. IERC20 asset; // how much asset do you want to use? uint256 amount; // is it an action on collateral only? bool collateralOnly; }
19,490
37
// initialise the next claim if it was the first stake for this staker or if the next claim was re-initialised (ie. rewards were claimed until the last staker snapshot and the last staker snapshot has no stake)
if (nextClaims[owner].period == 0) { uint16 currentPeriod = _getPeriod(currentCycle, periodLengthInCycles_); nextClaims[owner] = NextClaim(currentPeriod, uint64(globalHistory.length - 1), 0); }
if (nextClaims[owner].period == 0) { uint16 currentPeriod = _getPeriod(currentCycle, periodLengthInCycles_); nextClaims[owner] = NextClaim(currentPeriod, uint64(globalHistory.length - 1), 0); }
31,187
59
// // FlightSurety Smart Contract// /
contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint256 private constant AIRLINES_THRESHOLD = 4; uint256 public constant MAX_PREMIUM = 1 ether; uint256 public constant PERCENTAGE_PAY = 150; uint256 public constant MIN_FUND = 10 ether; address private contractOwner; // Account used to deploy contract struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } mapping(bytes32 => Flight) private flights; FlightSuretyData internal flightSuretyData; struct Voting { address[] voters; mapping(address => bool) hasVoted; uint256 gotVotes; } mapping(address => Voting) private votes; event FlightRegistered( address airlineAccount, string airlineName, uint256 departureTime ); event RegisterAirlineSuccess( bool success, uint256 gotVotes ); event InsurancePurchaseSuccess( address indexed passengerAccount, uint256 premium, address airlineAccount, string airlineName, uint256 departureTime ); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(flightSuretyData.isOperational(), "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireIsAirlineRegistered() { require(flightSuretyData.isAirlineRegistered(msg.sender), "Caller is not registered airline"); _; } modifier requireIsAirlineFunded() { require(flightSuretyData.isAirlineFunded(msg.sender), "Caller airline is not funded"); _; } modifier requireIsFutureFlight(uint256 _departureTime) { require(_departureTime > now, "Flight is not in future"); _; } modifier requireIsMinFunded() { require(msg.value >= MIN_FUND, "Not enough fund"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor( address _dataContract ) public { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(_dataContract); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { return flightSuretyData.isOperational(); // Modify to call data contract's status } function isAirlineRegistered(address _airlineAccount) public view returns(bool) { return flightSuretyData.isAirlineRegistered(_airlineAccount); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function addVote( address _airlineAccount, address _voterAirlineAccount) internal { //To avoid double counting if (votes[_airlineAccount].hasVoted[_voterAirlineAccount] == false) { votes[_airlineAccount].hasVoted[_voterAirlineAccount] = true; votes[_airlineAccount].voters.push(_voterAirlineAccount); votes[_airlineAccount].gotVotes = votes[_airlineAccount].gotVotes.add(1); } } function registerAirline( address _airlineAccount, string _airlineName ) external requireIsOperational requireIsAirlineRegistered requireIsAirlineFunded returns(bool _success, uint256 _votes){ require(!isAirlineRegistered(_airlineAccount), "Already registered"); _success = false; _votes =0; uint256 airlinesCount = flightSuretyData.getAirlinesCount(); if (airlinesCount < AIRLINES_THRESHOLD) { flightSuretyData.registerAirline(_airlineAccount, _airlineName); _success = true; } else { uint256 votesNeeded = airlinesCount.mul(100).div(2); addVote(_airlineAccount, msg.sender); _votes = votes[_airlineAccount].gotVotes; if (_votes.mul(100) >= votesNeeded) { flightSuretyData.registerAirline(_airlineAccount, _airlineName); _success = true; } } emit RegisterAirlineSuccess(_success, _votes); } function fund() external payable requireIsOperational requireIsAirlineRegistered { require(msg.value >= MIN_FUND,"Airline funding requires at least 10 Ether"); // dataContractAddress.transfer(msg.value); flightSuretyData.fund.value(msg.value)(msg.sender); } /** * @dev Register a future flight for insuring. * */ function registerFlight( string _airlineName, uint256 _departureTime ) external requireIsOperational requireIsAirlineRegistered requireIsAirlineFunded requireIsFutureFlight(_departureTime) { bytes32 flightKey = getFlightKey(msg.sender, _airlineName, _departureTime); flights[flightKey] = Flight(true, STATUS_CODE_UNKNOWN, now, msg.sender); emit FlightRegistered(msg.sender, _airlineName, _departureTime); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus( address _airlineAccount, string memory _airlineName, uint256 _departureTime, uint8 _statusCode ) internal { bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _departureTime); flights[flightKey].updatedTimestamp = now; flights[flightKey].statusCode = _statusCode; } // Generate a request for oracles to fetch flight information function fetchFlightStatus( address _airlineAccount, string _airlineName, uint256 _departureTime ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, _airlineAccount, _airlineName, _departureTime)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, _airlineAccount, _airlineName, _departureTime); } function buyInsurance(address _airlineAccount, string _airlineName, uint256 _departureTime ) external payable requireIsOperational { require(!isAirlineRegistered(msg.sender), "Caller is airline account"); require(now < _departureTime, "Insurance is not available after flight departure"); require(msg.value <= MAX_PREMIUM, "Max premium 1 Ether"); bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _departureTime); require(flights[flightKey].isRegistered == true, "Airline is not registered"); // dataContractAddress.transfer(msg.value); flightSuretyData.buy.value(msg.value)(msg.sender,_airlineAccount,_airlineName,_departureTime); emit InsurancePurchaseSuccess(msg.sender, msg.value, _airlineAccount,_airlineName,_departureTime); } function claimCredit(address _airlineAccount, string _airlineName, uint256 _departureTime ) external requireIsOperational { bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _departureTime); require(flights[flightKey].statusCode == STATUS_CODE_LATE_AIRLINE, "Flight is not delayed due to any issues caused by the airline"); require(now > flights[flightKey].updatedTimestamp, "Plz wait for flight status to be updated"); flightSuretyData.creditInsurees(PERCENTAGE_PAY,_airlineAccount,_airlineName,_departureTime); } function withdrawCredits() external requireIsOperational { require(flightSuretyData.getPassengerTotalCredits(msg.sender) > 0, "No credits available"); flightSuretyData.pay(msg.sender); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes ( ) view external returns(uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey ( address airline, string flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint256 private constant AIRLINES_THRESHOLD = 4; uint256 public constant MAX_PREMIUM = 1 ether; uint256 public constant PERCENTAGE_PAY = 150; uint256 public constant MIN_FUND = 10 ether; address private contractOwner; // Account used to deploy contract struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } mapping(bytes32 => Flight) private flights; FlightSuretyData internal flightSuretyData; struct Voting { address[] voters; mapping(address => bool) hasVoted; uint256 gotVotes; } mapping(address => Voting) private votes; event FlightRegistered( address airlineAccount, string airlineName, uint256 departureTime ); event RegisterAirlineSuccess( bool success, uint256 gotVotes ); event InsurancePurchaseSuccess( address indexed passengerAccount, uint256 premium, address airlineAccount, string airlineName, uint256 departureTime ); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(flightSuretyData.isOperational(), "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireIsAirlineRegistered() { require(flightSuretyData.isAirlineRegistered(msg.sender), "Caller is not registered airline"); _; } modifier requireIsAirlineFunded() { require(flightSuretyData.isAirlineFunded(msg.sender), "Caller airline is not funded"); _; } modifier requireIsFutureFlight(uint256 _departureTime) { require(_departureTime > now, "Flight is not in future"); _; } modifier requireIsMinFunded() { require(msg.value >= MIN_FUND, "Not enough fund"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor( address _dataContract ) public { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(_dataContract); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { return flightSuretyData.isOperational(); // Modify to call data contract's status } function isAirlineRegistered(address _airlineAccount) public view returns(bool) { return flightSuretyData.isAirlineRegistered(_airlineAccount); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function addVote( address _airlineAccount, address _voterAirlineAccount) internal { //To avoid double counting if (votes[_airlineAccount].hasVoted[_voterAirlineAccount] == false) { votes[_airlineAccount].hasVoted[_voterAirlineAccount] = true; votes[_airlineAccount].voters.push(_voterAirlineAccount); votes[_airlineAccount].gotVotes = votes[_airlineAccount].gotVotes.add(1); } } function registerAirline( address _airlineAccount, string _airlineName ) external requireIsOperational requireIsAirlineRegistered requireIsAirlineFunded returns(bool _success, uint256 _votes){ require(!isAirlineRegistered(_airlineAccount), "Already registered"); _success = false; _votes =0; uint256 airlinesCount = flightSuretyData.getAirlinesCount(); if (airlinesCount < AIRLINES_THRESHOLD) { flightSuretyData.registerAirline(_airlineAccount, _airlineName); _success = true; } else { uint256 votesNeeded = airlinesCount.mul(100).div(2); addVote(_airlineAccount, msg.sender); _votes = votes[_airlineAccount].gotVotes; if (_votes.mul(100) >= votesNeeded) { flightSuretyData.registerAirline(_airlineAccount, _airlineName); _success = true; } } emit RegisterAirlineSuccess(_success, _votes); } function fund() external payable requireIsOperational requireIsAirlineRegistered { require(msg.value >= MIN_FUND,"Airline funding requires at least 10 Ether"); // dataContractAddress.transfer(msg.value); flightSuretyData.fund.value(msg.value)(msg.sender); } /** * @dev Register a future flight for insuring. * */ function registerFlight( string _airlineName, uint256 _departureTime ) external requireIsOperational requireIsAirlineRegistered requireIsAirlineFunded requireIsFutureFlight(_departureTime) { bytes32 flightKey = getFlightKey(msg.sender, _airlineName, _departureTime); flights[flightKey] = Flight(true, STATUS_CODE_UNKNOWN, now, msg.sender); emit FlightRegistered(msg.sender, _airlineName, _departureTime); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus( address _airlineAccount, string memory _airlineName, uint256 _departureTime, uint8 _statusCode ) internal { bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _departureTime); flights[flightKey].updatedTimestamp = now; flights[flightKey].statusCode = _statusCode; } // Generate a request for oracles to fetch flight information function fetchFlightStatus( address _airlineAccount, string _airlineName, uint256 _departureTime ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, _airlineAccount, _airlineName, _departureTime)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, _airlineAccount, _airlineName, _departureTime); } function buyInsurance(address _airlineAccount, string _airlineName, uint256 _departureTime ) external payable requireIsOperational { require(!isAirlineRegistered(msg.sender), "Caller is airline account"); require(now < _departureTime, "Insurance is not available after flight departure"); require(msg.value <= MAX_PREMIUM, "Max premium 1 Ether"); bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _departureTime); require(flights[flightKey].isRegistered == true, "Airline is not registered"); // dataContractAddress.transfer(msg.value); flightSuretyData.buy.value(msg.value)(msg.sender,_airlineAccount,_airlineName,_departureTime); emit InsurancePurchaseSuccess(msg.sender, msg.value, _airlineAccount,_airlineName,_departureTime); } function claimCredit(address _airlineAccount, string _airlineName, uint256 _departureTime ) external requireIsOperational { bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _departureTime); require(flights[flightKey].statusCode == STATUS_CODE_LATE_AIRLINE, "Flight is not delayed due to any issues caused by the airline"); require(now > flights[flightKey].updatedTimestamp, "Plz wait for flight status to be updated"); flightSuretyData.creditInsurees(PERCENTAGE_PAY,_airlineAccount,_airlineName,_departureTime); } function withdrawCredits() external requireIsOperational { require(flightSuretyData.getPassengerTotalCredits(msg.sender) > 0, "No credits available"); flightSuretyData.pay(msg.sender); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes ( ) view external returns(uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey ( address airline, string flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
4,381
83
// See {ERC1155-_burn}. /
function _burn(address account, uint256 id, uint256 amount) internal virtual override { super._burn(account, id, amount); _totalSupply[id] -= amount; }
function _burn(address account, uint256 id, uint256 amount) internal virtual override { super._burn(account, id, amount); _totalSupply[id] -= amount; }
7,073
150
// Function for user to bet on launch outcome
function bet(uint option) public payable { require(canBet() == true); require(msg.value >= MIN_BET); require(betterInfo[msg.sender].betAmount == 0 || betterInfo[msg.sender].betOption == option); // Add better to better list if they // aren't already in it if (betterInfo[msg.sender].betAmount == 0) { betterInfo[msg.sender].betOption = option; numberOfBets[option]++; betters.push(msg.sender); } // Perform bet betterInfo[msg.sender].betAmount += msg.value; totalBetAmount += msg.value; totalAmountsBet[option] += msg.value; BetMade(); // Trigger event }
function bet(uint option) public payable { require(canBet() == true); require(msg.value >= MIN_BET); require(betterInfo[msg.sender].betAmount == 0 || betterInfo[msg.sender].betOption == option); // Add better to better list if they // aren't already in it if (betterInfo[msg.sender].betAmount == 0) { betterInfo[msg.sender].betOption = option; numberOfBets[option]++; betters.push(msg.sender); } // Perform bet betterInfo[msg.sender].betAmount += msg.value; totalBetAmount += msg.value; totalAmountsBet[option] += msg.value; BetMade(); // Trigger event }
52,268
61
// Zero out the Entry
h.deed = Deed(0); h.registrationDate = 0; h.value = 0; h.highestBid = 0;
h.deed = Deed(0); h.registrationDate = 0; h.value = 0; h.highestBid = 0;
39,064
328
// check for sufficient balance
require( IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount), "UniversalVault: insufficient balance" );
require( IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount), "UniversalVault: insufficient balance" );
11,688
15
// Verifier contract. Used to verify aggregated proof for blocks
Verifier verifier;
Verifier verifier;
11,582
336
// Authorize Partnership.Before submitting this TX, we must have encrypted oursymetric encryption key on his asymetric encryption public key. /
function authorizePartnership(address _hisContract, bytes _ourSymetricKey) external onlyIdentityPurpose(1)
function authorizePartnership(address _hisContract, bytes _ourSymetricKey) external onlyIdentityPurpose(1)
14,995
187
// ^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ /
function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); }
function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); }
32,677
222
// Constructor, takes crowdsale opening and closing times. openingTime Crowdsale opening time closingTime Crowdsale closing time /
constructor (uint256 openingTime, uint256 closingTime) public { // solhint-disable-next-line not-rely-on-time require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time"); // solhint-disable-next-line max-line-length require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time"); _openingTime = openingTime; _closingTime = closingTime; }
constructor (uint256 openingTime, uint256 closingTime) public { // solhint-disable-next-line not-rely-on-time require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time"); // solhint-disable-next-line max-line-length require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time"); _openingTime = openingTime; _closingTime = closingTime; }
26,274
20
// Module cannot be added twice.
require(modules[module] == address(0), "GS102"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module);
require(modules[module] == address(0), "GS102"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module);
7,978
9
// Transfer the tokens under the control of the vault contract
require(IUniswapV2ERC20(token).transferFrom(locker, address(this), amount), "Vault::lockTokens: transfer failed"); uint256 lockStartTime = startTime == 0 ? block.timestamp : startTime; Lock memory lock = Lock({ token: token, receiver: receiver, startTime: lockStartTime, amount: amount, duration: lockDurationInDays,
require(IUniswapV2ERC20(token).transferFrom(locker, address(this), amount), "Vault::lockTokens: transfer failed"); uint256 lockStartTime = startTime == 0 ? block.timestamp : startTime; Lock memory lock = Lock({ token: token, receiver: receiver, startTime: lockStartTime, amount: amount, duration: lockDurationInDays,
27,677
205
// Performs a Solidity function call using a low level `call`. Aplain `call` is an unsafe replacement for a function call: use thisfunction instead. If `target` reverts with a revert reason, it is bubbled up by thisfunction (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract.- calling `target` with `data` must not revert. _Available since v3.1._ /
function functionCall( address target, bytes memory data
function functionCall( address target, bytes memory data
11,395
17
// nami presale contract
address public namiPresale;
address public namiPresale;
40,432
15
// list of balancer pairs to gulp
address[] public balGulpPairs;
address[] public balGulpPairs;
33,823
40
// sub from from
_itokenBalances[from] = _itokenBalances[from].sub(itokenValue); _itokenBalances[to] = _itokenBalances[to].add(itokenValue); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], itokenValue); return true;
_itokenBalances[from] = _itokenBalances[from].sub(itokenValue); _itokenBalances[to] = _itokenBalances[to].add(itokenValue); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], itokenValue); return true;
10,834
119
// for admin func
function AddBlackList(address[] memory addrs) public
function AddBlackList(address[] memory addrs) public
10,991
4
// (Solitaire3D long only) fired whenever a player tries a buy after round timer hit zero, and causes end round to be ran.
event onBuyAndDistribute ( address playerAddress, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, uint256 amountWon, uint256 newPot, uint256 genAmount
event onBuyAndDistribute ( address playerAddress, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, uint256 amountWon, uint256 newPot, uint256 genAmount
36,279
14
// 沙龙合约,支持开启新活动,用户签到,问题记录以及奖励分配等功能
contract Salon is Administrative { //合约结构体 struct Campaign { uint ID; //期号,建议用日期形式,例如20181116 bool end; //是否结束 string topic; //沙龙主题 address speaker; //主讲人地址 address sponsor; //赞助商(场地提供人)地址 address[] participants; //参与者数组 mapping(address => uint) idx_participants; //参与者状态:0表示未报名;1表示已报名;2表示已报名并且现场已签到 address[] questioner; //提问者数组 mapping(address => address) QRMap; //提问-回答键值对 } mapping(uint => Campaign) public campaigns; //期号-沙龙实体键值对 SalonToken public salonToken; //沙龙token合约 uint unit; //沙龙token小数位数 //一次沙龙活动挖矿的比例 uint public speakerPercent = 30; uint public sponsorPercent = 10; uint public participantPercent = 40; uint public questionPercent = 20; uint public registerFee = 1; //构造函数,传入沙龙token合约地址 constructor(address salonTokenAddr) public { salonToken = SalonToken(salonTokenAddr); uint decimals = salonToken.decimals(); unit = 10 ** decimals; } //检测是否是合法沙龙,合法定义为:已经开始,但是没有结束的沙龙 modifier validCampaign(uint _campaignID) { Campaign storage c = campaigns[_campaignID]; require(c.speaker != address(0)); require(!c.end); _; } //一些记录事件 event LogNewCampaign(uint indexed campaignID, string topic, address indexed speaker, address indexed sponsor); event LogRegister(address indexed who); event LogCheckedIn(address indexed who); event LogQuestion(address indexed questioner, address indexed replier); event LogClose(uint indexed campaignID, uint numOfParticipants, uint questions); //开启一个新沙龙,需要管理员权限。根据既定规则,会产生100个新币,用于后期奖励。参数为:沙龙id,主题,主讲人,赞助商 function newCampaign(uint _campaignID, string calldata _topic, address _speaker, address _sponsor) external onlyPrivileged { require(_speaker != address(0)); require(_sponsor != address(0)); require(campaigns[_campaignID].speaker == address(0)); //禁止重复的沙龙活动 campaigns[_campaignID] = Campaign({ ID : _campaignID, end : false, topic : _topic, speaker : _speaker, sponsor : _sponsor, participants : new address[](0), questioner : new address[](0) }); if(salonToken.totalSupply() + (100 * unit) <= (10000 * unit)) { salonToken.mint(address(this), 100 * unit); } emit LogNewCampaign(_campaignID, _topic, _speaker, _sponsor); } //修改各个部分的分配比例,需要管理员权限,参数为:主讲人比例,赞助商比例,参与者比例,提问回答者比例 function changePercentage(uint _speakerP, uint _sponsorP, uint _participantP, uint _questionP) external onlyPrivileged{ require(_speakerP + _sponsorP + _participantP + _questionP == 100, "比例总和要等于100"); speakerPercent = _speakerP; sponsorPercent = _sponsorP; participantPercent = _participantP; questionPercent = _questionP; } function changeRegisterFee(uint _fee) external onlyPrivileged{ require(_fee < 100, "报名费要低于挖矿数量"); registerFee = _fee; } //用户报名,并缴纳报名费 function register(uint _campaignID) external validCampaign(_campaignID) { Campaign storage c = campaigns[_campaignID]; require(c.idx_participants[msg.sender] == 0, "已经完成报名"); salonToken.transferByAdministrator(msg.sender, address(this), registerFee * unit); c.idx_participants[msg.sender] = 1; emit LogRegister(msg.sender); } //签到入场。参数为:沙龙id,签到人地址 function checkin(uint _campaignID, address _who) external onlyPrivileged validCampaign(_campaignID){ Campaign storage c = campaigns[_campaignID]; require(c.idx_participants[_who] == 1, "尚未报名或已经签到成功"); c.participants.push(_who); c.idx_participants[_who] = 2; emit LogCheckedIn(_who); } //添加场上问题。需要管理员权限,参数为:沙龙id,提问者,回答者 function addQuestion(uint _campaignID, address _questioner, address _replier) external onlyPrivileged validCampaign(_campaignID) { Campaign storage c = campaigns[_campaignID]; c.questioner.push(_questioner); c.QRMap[_questioner] = _replier; emit LogQuestion(_questioner, _replier); } //关闭沙龙。需要管理员权限。关闭后会按照既定规则,把奖励发放给主讲人、参与者等。参数为:沙龙id function closeCampaign(uint _campaignID) external onlyPrivileged validCampaign(_campaignID) { uint totalAmount = salonToken.balanceOf(address(this)); Campaign storage c = campaigns[_campaignID]; salonToken.transfer(c.speaker, speakerPercent * totalAmount / 100); salonToken.transfer(c.sponsor, sponsorPercent * totalAmount / 100); uint i; if(c.participants.length > 0) { uint tokenForAttendance = participantPercent * totalAmount / 100 / c.participants.length; for(i=0;i<c.participants.length;i++) { salonToken.transfer(c.participants[i], tokenForAttendance); } } if(c.questioner.length > 0) { uint tokenForQuestion = questionPercent * totalAmount / 100 / c.questioner.length / 2; for(i=0;i<c.questioner.length;i++) { salonToken.transfer(c.questioner[i], tokenForQuestion); salonToken.transfer(c.QRMap[c.questioner[i]], tokenForQuestion); } } c.end = true; emit LogClose(_campaignID, c.participants.length, c.questioner.length); } }
contract Salon is Administrative { //合约结构体 struct Campaign { uint ID; //期号,建议用日期形式,例如20181116 bool end; //是否结束 string topic; //沙龙主题 address speaker; //主讲人地址 address sponsor; //赞助商(场地提供人)地址 address[] participants; //参与者数组 mapping(address => uint) idx_participants; //参与者状态:0表示未报名;1表示已报名;2表示已报名并且现场已签到 address[] questioner; //提问者数组 mapping(address => address) QRMap; //提问-回答键值对 } mapping(uint => Campaign) public campaigns; //期号-沙龙实体键值对 SalonToken public salonToken; //沙龙token合约 uint unit; //沙龙token小数位数 //一次沙龙活动挖矿的比例 uint public speakerPercent = 30; uint public sponsorPercent = 10; uint public participantPercent = 40; uint public questionPercent = 20; uint public registerFee = 1; //构造函数,传入沙龙token合约地址 constructor(address salonTokenAddr) public { salonToken = SalonToken(salonTokenAddr); uint decimals = salonToken.decimals(); unit = 10 ** decimals; } //检测是否是合法沙龙,合法定义为:已经开始,但是没有结束的沙龙 modifier validCampaign(uint _campaignID) { Campaign storage c = campaigns[_campaignID]; require(c.speaker != address(0)); require(!c.end); _; } //一些记录事件 event LogNewCampaign(uint indexed campaignID, string topic, address indexed speaker, address indexed sponsor); event LogRegister(address indexed who); event LogCheckedIn(address indexed who); event LogQuestion(address indexed questioner, address indexed replier); event LogClose(uint indexed campaignID, uint numOfParticipants, uint questions); //开启一个新沙龙,需要管理员权限。根据既定规则,会产生100个新币,用于后期奖励。参数为:沙龙id,主题,主讲人,赞助商 function newCampaign(uint _campaignID, string calldata _topic, address _speaker, address _sponsor) external onlyPrivileged { require(_speaker != address(0)); require(_sponsor != address(0)); require(campaigns[_campaignID].speaker == address(0)); //禁止重复的沙龙活动 campaigns[_campaignID] = Campaign({ ID : _campaignID, end : false, topic : _topic, speaker : _speaker, sponsor : _sponsor, participants : new address[](0), questioner : new address[](0) }); if(salonToken.totalSupply() + (100 * unit) <= (10000 * unit)) { salonToken.mint(address(this), 100 * unit); } emit LogNewCampaign(_campaignID, _topic, _speaker, _sponsor); } //修改各个部分的分配比例,需要管理员权限,参数为:主讲人比例,赞助商比例,参与者比例,提问回答者比例 function changePercentage(uint _speakerP, uint _sponsorP, uint _participantP, uint _questionP) external onlyPrivileged{ require(_speakerP + _sponsorP + _participantP + _questionP == 100, "比例总和要等于100"); speakerPercent = _speakerP; sponsorPercent = _sponsorP; participantPercent = _participantP; questionPercent = _questionP; } function changeRegisterFee(uint _fee) external onlyPrivileged{ require(_fee < 100, "报名费要低于挖矿数量"); registerFee = _fee; } //用户报名,并缴纳报名费 function register(uint _campaignID) external validCampaign(_campaignID) { Campaign storage c = campaigns[_campaignID]; require(c.idx_participants[msg.sender] == 0, "已经完成报名"); salonToken.transferByAdministrator(msg.sender, address(this), registerFee * unit); c.idx_participants[msg.sender] = 1; emit LogRegister(msg.sender); } //签到入场。参数为:沙龙id,签到人地址 function checkin(uint _campaignID, address _who) external onlyPrivileged validCampaign(_campaignID){ Campaign storage c = campaigns[_campaignID]; require(c.idx_participants[_who] == 1, "尚未报名或已经签到成功"); c.participants.push(_who); c.idx_participants[_who] = 2; emit LogCheckedIn(_who); } //添加场上问题。需要管理员权限,参数为:沙龙id,提问者,回答者 function addQuestion(uint _campaignID, address _questioner, address _replier) external onlyPrivileged validCampaign(_campaignID) { Campaign storage c = campaigns[_campaignID]; c.questioner.push(_questioner); c.QRMap[_questioner] = _replier; emit LogQuestion(_questioner, _replier); } //关闭沙龙。需要管理员权限。关闭后会按照既定规则,把奖励发放给主讲人、参与者等。参数为:沙龙id function closeCampaign(uint _campaignID) external onlyPrivileged validCampaign(_campaignID) { uint totalAmount = salonToken.balanceOf(address(this)); Campaign storage c = campaigns[_campaignID]; salonToken.transfer(c.speaker, speakerPercent * totalAmount / 100); salonToken.transfer(c.sponsor, sponsorPercent * totalAmount / 100); uint i; if(c.participants.length > 0) { uint tokenForAttendance = participantPercent * totalAmount / 100 / c.participants.length; for(i=0;i<c.participants.length;i++) { salonToken.transfer(c.participants[i], tokenForAttendance); } } if(c.questioner.length > 0) { uint tokenForQuestion = questionPercent * totalAmount / 100 / c.questioner.length / 2; for(i=0;i<c.questioner.length;i++) { salonToken.transfer(c.questioner[i], tokenForQuestion); salonToken.transfer(c.QRMap[c.questioner[i]], tokenForQuestion); } } c.end = true; emit LogClose(_campaignID, c.participants.length, c.questioner.length); } }
16,067
40
// Sets the affiliate Merkle root for (`edition`, `mintId`). Calling conditions:- The caller must be the edition's owner or admin.edition The edition address. mintIdThe mint ID, a global incrementing identifier used within the minter rootThe affiliate Merkle root, if any. /
function setAffiliateMerkleRoot(
function setAffiliateMerkleRoot(
36,915
6
// Reinvests DCB tokens into MasterChef for all pools Only possible when contract not paused.Beware of gas!! /
function harvestAll() external notContract whenNotPaused { uint256 poolLen = masterchef.poolLength(); for (uint256 pid = 0; pid < poolLen; pid++) { harvest(pid); } }
function harvestAll() external notContract whenNotPaused { uint256 poolLen = masterchef.poolLength(); for (uint256 pid = 0; pid < poolLen; pid++) { harvest(pid); } }
23,358