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
98
// Make sure cToken Comptrollers are identical
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); }
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); }
7,578
441
// Returns the accumulators corresponding to each of `queries`. /
function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view returns (int256[] memory results);
function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view returns (int256[] memory results);
24,231
222
// Checks an expression and reverts with an {IllegalState} error if the expression is {false}.//expression The expression to check.
function _checkState(bool expression) internal pure { if (!expression) { revert IllegalState(); }
function _checkState(bool expression) internal pure { if (!expression) { revert IllegalState(); }
6,171
48
// Internal function to trigger a call to the conduit currently held by the accumulator if the accumulator contains item transfers (i.e. it is "armed") and the supplied conduit key does not match the key held by the accumulator.accumulator An open-ended array that collects transfers to execute against a given conduit in a single call. conduitKeyA bytes32 value indicating what corresponding conduit, if any, to source token approvals from. The zero hash signifies that no conduit should be used, with direct approvals set on this contract. /
function _triggerIfArmedAndNotAccumulatable(bytes memory accumulator, bytes32 conduitKey) internal { // Retrieve the current conduit key from the accumulator. bytes32 accumulatorConduitKey = _getAccumulatorConduitKey(accumulator); // Perform conduit call if the set key does not match the supplied key. if (accumulatorConduitKey != conduitKey) { _triggerIfArmed(accumulator); } }
function _triggerIfArmedAndNotAccumulatable(bytes memory accumulator, bytes32 conduitKey) internal { // Retrieve the current conduit key from the accumulator. bytes32 accumulatorConduitKey = _getAccumulatorConduitKey(accumulator); // Perform conduit call if the set key does not match the supplied key. if (accumulatorConduitKey != conduitKey) { _triggerIfArmed(accumulator); } }
17,051
29
// Calling this function managers can collect Rubic's fixed crypto fee /
function collectRubicCryptoFee() external onlyManagerOrAdmin { uint256 _cryptoFee = availableRubicCryptoFee; availableRubicCryptoFee = 0; sendToken(address(0), _cryptoFee, msg.sender); emit FixedCryptoFeeCollected(_cryptoFee, msg.sender); }
function collectRubicCryptoFee() external onlyManagerOrAdmin { uint256 _cryptoFee = availableRubicCryptoFee; availableRubicCryptoFee = 0; sendToken(address(0), _cryptoFee, msg.sender); emit FixedCryptoFeeCollected(_cryptoFee, msg.sender); }
17,862
278
// Emitted when URI of token is set /
event SetTokenURI(uint256 tokenId, string tokenURI);
event SetTokenURI(uint256 tokenId, string tokenURI);
14,530
1
// add Safe math addition function /
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; }
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; }
19,188
12
// Returns the list of purposes associated with a key. /
function getKeyPurposes(bytes32 _key) external view returns(uint256[] memory _purposes);
function getKeyPurposes(bytes32 _key) external view returns(uint256[] memory _purposes);
55,799
34
// Buying tokens with Ethers (unit: wei) /
function buyTokens() public payable returns (bool success) { uint256 _value = SafeMath.div(msg.value, _rate); require(_value > 0, "Purchased tokens <= 0"); balances[_owner] = SafeMath.sub(balances[_owner], _value); balances[msg.sender] = SafeMath.add(balances[msg.sender], _value); emit Transfer(_owner, msg.sender, _value); return true; }
function buyTokens() public payable returns (bool success) { uint256 _value = SafeMath.div(msg.value, _rate); require(_value > 0, "Purchased tokens <= 0"); balances[_owner] = SafeMath.sub(balances[_owner], _value); balances[msg.sender] = SafeMath.add(balances[msg.sender], _value); emit Transfer(_owner, msg.sender, _value); return true; }
22,798
85
// return the block timestamp. /
function getBlockTimestamp() public view returns (uint) { return block.timestamp; }
function getBlockTimestamp() public view returns (uint) { return block.timestamp; }
50,220
641
// Check if TVL has active manual override
function hasTvlOverride() external view returns (bool);
function hasTvlOverride() external view returns (bool);
44,134
31
// set Public Sale Address /
function setPublicSaleAddress(address _pubSaleAddr) public onlyOwner { Wesion_PUBLIC_SALE = IWesionPublicSale(_pubSaleAddr); }
function setPublicSaleAddress(address _pubSaleAddr) public onlyOwner { Wesion_PUBLIC_SALE = IWesionPublicSale(_pubSaleAddr); }
40,715
2
// event Transfer(address from, address to, address issuer, address dedeAddress);unused in current version
event Activate(address dip, address scs, address issuer, address dedeAddress); event Nullify(address dip, address scs, address issuer, address dedeAddress); address public dedeNetworkAddress; address public myAddress;
event Activate(address dip, address scs, address issuer, address dedeAddress); event Nullify(address dip, address scs, address issuer, address dedeAddress); address public dedeNetworkAddress; address public myAddress;
25,653
16
// it is checked that not too many iteration steps were taken: require that the sum of SellAmounts times the price of the last order is not more than initially sold amount
(, uint96 buyAmountOfIter, uint96 sellAmountOfIter) = iterOrder .decodeOrder(); require( sumBidAmount.mul(buyAmountOfIter) < auctioneerSellAmount.mul(sellAmountOfIter), "too many orders summed up" ); interimSumBidAmount = sumBidAmount; interimOrder = iterOrder;
(, uint96 buyAmountOfIter, uint96 sellAmountOfIter) = iterOrder .decodeOrder(); require( sumBidAmount.mul(buyAmountOfIter) < auctioneerSellAmount.mul(sellAmountOfIter), "too many orders summed up" ); interimSumBidAmount = sumBidAmount; interimOrder = iterOrder;
34,205
179
// 按照索引更新保险库合约地址
vaults[tokenIndex] = vault;
vaults[tokenIndex] = vault;
863
1
// "YFLArt", "YFA", "https:api.bonktoken.com/contractMetadata/{address} ", "ipfs:/", this.YFLink.address, { from: alice }
function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value);
function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value);
5,625
7
// Extend the unlock time for `msg.sender` to `_unlock_time` _unlock_time New epoch time for unlocking /
function increase_unlock_time(uint256 _unlock_time) external;
function increase_unlock_time(uint256 _unlock_time) external;
58,035
0
// Structs related to the _deprecatedLatestPriceInfoV1
enum DeprecatedPriceStatusV1 { UNKNOWN, TRADING, HALTED, AUCTION }
enum DeprecatedPriceStatusV1 { UNKNOWN, TRADING, HALTED, AUCTION }
12,800
215
// keep track of which tokens were submitted to prevent dupes/ all tokens are eligible but only 15 are needed
uint256[] memory tokens = new uint256[](19); uint256[] memory values = new uint256[](15);
uint256[] memory tokens = new uint256[](19); uint256[] memory values = new uint256[](15);
27,475
11
// Transfer WETH to the caller if verified in the merkle tree/ Requirements:/ - Users in the tree can claim their WETH value only once/proof_ merkle proof provided by the user/index_ user index in the merkle tree/value_ WETH value to transfer
function claim( bytes32[] calldata proof_, uint256 index_, uint256 value_
function claim( bytes32[] calldata proof_, uint256 index_, uint256 value_
42,018
23
// Integer precision for calculating float values for weights and biases
int constant int_precision = 10000;
int constant int_precision = 10000;
53,446
22
// approve should be called when allowed[_spender] == 0. To incrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.sol /
function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
35,389
128
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; }
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; }
703
21
// Emitted when the `AxiomV1Core` address is updated./ newAddress The updated address.
event UpdateAxiomAddress(address newAddress);
event UpdateAxiomAddress(address newAddress);
28,474
4
// cryptodemonz v1 official address
address public demonz = 0xAE16529eD90FAfc927D774Ea7bE1b95D826664E3;
address public demonz = 0xAE16529eD90FAfc927D774Ea7bE1b95D826664E3;
14,866
3
// Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) _dst Destination address to perform the delegatecall _calldata Calldata for the delegatecall /
function delegatedFwd(address _dst, bytes _calldata) internal { assembly { let result := delegatecall(sub(gas, 10000), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } }
function delegatedFwd(address _dst, bytes _calldata) internal { assembly { let result := delegatecall(sub(gas, 10000), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } }
54,223
111
// Reads nested bytes from a specific position./NOTE: the returned value overlaps with the input value./Both should be treated as immutable./b Byte array containing nested bytes./index Index of nested bytes./ return result Nested bytes.
function readBytesWithLength( bytes memory b, uint256 index ) internal pure returns (bytes memory result)
function readBytesWithLength( bytes memory b, uint256 index ) internal pure returns (bytes memory result)
33,661
77
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
return computedHash == root;
12,000
5
// set the price for the chosen currency pair.
currentPrice = getLatestPrice(); COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator);
currentPrice = getLatestPrice(); COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator);
19,509
192
// Returns the pair address for on a given DEX._factory The factory to address _tokenAThe address of tokenA _tokenBThe address of tokenB return The pair address (Note: address(0) is returned by default if the pair is not available on that DEX) /
function _getPair(address _factory, address _tokenA, address _tokenB) internal view returns (address) { return IUniswapV2Factory(_factory).getPair(_tokenA, _tokenB); }
function _getPair(address _factory, address _tokenA, address _tokenB) internal view returns (address) { return IUniswapV2Factory(_factory).getPair(_tokenA, _tokenB); }
73,867
20
// Throws if the sender does not have any of the `roles`.
function _checkRoles(uint256 roles) internal view virtual { /// @solidity memory-safe-assembly assembly { // Compute the role slot. mstore(0x0c, _ROLE_SLOT_SEED) mstore(0x00, caller()) // Load the stored value, and if the `and` intersection // of the value and `roles` is zero, revert. if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) { mstore(0x00, _UNAUTHORIZED_ERROR_SELECTOR) revert(0x1c, 0x04) } } }
function _checkRoles(uint256 roles) internal view virtual { /// @solidity memory-safe-assembly assembly { // Compute the role slot. mstore(0x0c, _ROLE_SLOT_SEED) mstore(0x00, caller()) // Load the stored value, and if the `and` intersection // of the value and `roles` is zero, revert. if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) { mstore(0x00, _UNAUTHORIZED_ERROR_SELECTOR) revert(0x1c, 0x04) } } }
24,200
11
// Upgrades the implementation and makes call to the proxy The call is used to initialize the new implementation. proxyAddress The address of the proxy implementation The address of the new implementationinitParams The parameters to the call after the upgrade /
function _upgradeTokenImplementation( address proxyAddress, address implementation, bytes memory initParams
function _upgradeTokenImplementation( address proxyAddress, address implementation, bytes memory initParams
11,035
8
// sets the allocation of incoming PCV
function setAllocation(address[] calldata pcvDeposits, uint[] calldata ratios) external;
function setAllocation(address[] calldata pcvDeposits, uint[] calldata ratios) external;
24,812
5
// Defines conditions around being able to set default royalty royalty Royalty being set sender msg sender /
function canSetDefaultRoyalty(Royalty calldata royalty, address sender) external view returns (bool);
function canSetDefaultRoyalty(Royalty calldata royalty, address sender) external view returns (bool);
13,712
2
// return the entryPoint used by this account.subclass should return the current entryPoint used by this account. /
function entryPoint() public view virtual returns (IEntryPoint);
function entryPoint() public view virtual returns (IEntryPoint);
4,954
35
// Accrues interest and adds reserves by transferring from admin addAmount Amount of reserves to addreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); }
function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); }
39,975
138
// Converts bytes array to bytes32. Truncates bytes array if its size is more than 32 bytes. NOTE: This function does not perform any checks on the received parameter. Make sure that the _bytes argument has a correct length, not less than 32 bytes. A case when _bytes has length less than 32 will lead to the undefined behaviour, since assembly will read data from memory that is not related to the _bytes argument._bytes to be converted to bytes32 type return bytes32 type of the firsts 32 bytes array in parameter./
function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) { assembly { result := mload(add(_bytes, 32)) } }
function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) { assembly { result := mload(add(_bytes, 32)) } }
27,497
52
// Find the insert position for a new node with the given NICR _NICR Node's NICR _prevId Id of previous node for the insert position _nextId Id of next node for the insert position /
function findInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view override returns (address, address) { return _findInsertPosition(troveManager, _NICR, _prevId, _nextId); }
function findInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view override returns (address, address) { return _findInsertPosition(troveManager, _NICR, _prevId, _nextId); }
8,878
19
// The enabled static calls
mapping (bytes4 => address) public enabled;
mapping (bytes4 => address) public enabled;
2,358
37
// Admin function for setting the proposal thresholdnewProposalThreshold must be greater than the hardcoded minnewProposalThreshold new proposal threshold/
function _setProposalThreshold(uint newProposalThreshold) external { require(msg.sender == admin, "GovernorMike::_setProposalThreshold: admin only"); require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorMike::_setProposalThreshold: invalid proposal threshold"); uint oldProposalThreshold = proposalThreshold; proposalThreshold = newProposalThreshold; emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold); }
function _setProposalThreshold(uint newProposalThreshold) external { require(msg.sender == admin, "GovernorMike::_setProposalThreshold: admin only"); require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorMike::_setProposalThreshold: invalid proposal threshold"); uint oldProposalThreshold = proposalThreshold; proposalThreshold = newProposalThreshold; emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold); }
45,375
76
// Emits {Approval} event./ Returns boolean value indicating whether operation succeeded.
function approve(address spender, uint256 value) external override returns (bool) {
function approve(address spender, uint256 value) external override returns (bool) {
7,426
486
// borrow effect sumBorrowPlusEffects += oraclePriceborrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
13,778
110
// try-catch all errors/exceptions having failed messages does not block messages passing
try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
24,460
20
// EmergencyBrake allows to plan for and execute transactions that remove access permissions for a target/ contract. In an permissioned environment this can be used for pausing components./ All contracts in scope of emergency plans must grant ROOT permissions to EmergencyBrake. To mitigate the risk/ of governance capture, EmergencyBrake has very limited functionality, being able only to revoke existing roles/ and to restore previously revoked roles. Thus EmergencyBrake cannot grant permissions that weren't there in the / first place. As an additional safeguard, EmergencyBrake cannot revoke or grant ROOT roles./ In addition, there is a separation of concerns between the planner
contract EmergencyBrake is AccessControl, IEmergencyBrake { enum State {UNPLANNED, PLANNED, EXECUTED} struct Plan { State state; address target; bytes permissions; } event Planned(bytes32 indexed txHash, address indexed target); event Cancelled(bytes32 indexed txHash); event Executed(bytes32 indexed txHash, address indexed target); event Restored(bytes32 indexed txHash, address indexed target); event Terminated(bytes32 indexed txHash); mapping (bytes32 => Plan) public plans; constructor(address planner, address executor) AccessControl() { _grantRole(IEmergencyBrake.plan.selector, planner); _grantRole(IEmergencyBrake.cancel.selector, planner); _grantRole(IEmergencyBrake.execute.selector, executor); _grantRole(IEmergencyBrake.restore.selector, planner); _grantRole(IEmergencyBrake.terminate.selector, planner); // Granting roles (plan, cancel, execute, restore, terminate) is reserved to ROOT } /// @dev Compute the hash of a plan function hash(address target, Permission[] calldata permissions) external pure returns (bytes32 txHash) { txHash = keccak256(abi.encode(target, permissions)); } /// @dev Register an access removal transaction function plan(address target, Permission[] calldata permissions) external override auth returns (bytes32 txHash) { txHash = keccak256(abi.encode(target, permissions)); require(plans[txHash].state == State.UNPLANNED, "Emergency already planned for."); // Removing or granting ROOT permissions is out of bounds for EmergencyBrake for (uint256 i = 0; i < permissions.length; i++){ for (uint256 j = 0; j < permissions[i].signatures.length; j++){ require( permissions[i].signatures[j] != ROOT, "Can't remove ROOT" ); } } plans[txHash] = Plan({ state: State.PLANNED, target: target, permissions: abi.encode(permissions) }); emit Planned(txHash, target); } /// @dev Erase a planned access removal transaction function cancel(bytes32 txHash) external override auth { require(plans[txHash].state == State.PLANNED, "Emergency not planned for."); delete plans[txHash]; emit Cancelled(txHash); } /// @dev Execute an access removal transaction function execute(bytes32 txHash) external override auth { Plan memory plan_ = plans[txHash]; require(plan_.state == State.PLANNED, "Emergency not planned for."); plans[txHash].state = State.EXECUTED; Permission[] memory permissions_ = abi.decode(plan_.permissions, (Permission[])); for (uint256 i = 0; i < permissions_.length; i++){ // AccessControl.sol doesn't revert if revoking permissions that haven't been granted // If we don't check, planner and executor can collude to gain access to contacts Permission memory permission_ = permissions_[i]; for (uint256 j = 0; j < permission_.signatures.length; j++){ AccessControl contact = AccessControl(permission_.contact); bytes4 signature_ = permission_.signatures[j]; require( contact.hasRole(signature_, plan_.target), "Permission not found" ); contact.revokeRole(signature_, plan_.target); } } emit Executed(txHash, plan_.target); } /// @dev Restore the orchestration from an isolated target function restore(bytes32 txHash) external override auth { Plan memory plan_ = plans[txHash]; require(plan_.state == State.EXECUTED, "Emergency plan not executed."); plans[txHash].state = State.PLANNED; Permission[] memory permissions_ = abi.decode(plan_.permissions, (Permission[])); for (uint256 i = 0; i < permissions_.length; i++){ Permission memory permission_ = permissions_[i]; for (uint256 j = 0; j < permission_.signatures.length; j++){ AccessControl contact = AccessControl(permission_.contact); bytes4 signature_ = permission_.signatures[j]; contact.grantRole(signature_, plan_.target); } } emit Restored(txHash, plan_.target); } /// @dev Remove the restoring option from an isolated target function terminate(bytes32 txHash) external override auth { require(plans[txHash].state == State.EXECUTED, "Emergency plan not executed."); delete plans[txHash]; emit Terminated(txHash); } }
contract EmergencyBrake is AccessControl, IEmergencyBrake { enum State {UNPLANNED, PLANNED, EXECUTED} struct Plan { State state; address target; bytes permissions; } event Planned(bytes32 indexed txHash, address indexed target); event Cancelled(bytes32 indexed txHash); event Executed(bytes32 indexed txHash, address indexed target); event Restored(bytes32 indexed txHash, address indexed target); event Terminated(bytes32 indexed txHash); mapping (bytes32 => Plan) public plans; constructor(address planner, address executor) AccessControl() { _grantRole(IEmergencyBrake.plan.selector, planner); _grantRole(IEmergencyBrake.cancel.selector, planner); _grantRole(IEmergencyBrake.execute.selector, executor); _grantRole(IEmergencyBrake.restore.selector, planner); _grantRole(IEmergencyBrake.terminate.selector, planner); // Granting roles (plan, cancel, execute, restore, terminate) is reserved to ROOT } /// @dev Compute the hash of a plan function hash(address target, Permission[] calldata permissions) external pure returns (bytes32 txHash) { txHash = keccak256(abi.encode(target, permissions)); } /// @dev Register an access removal transaction function plan(address target, Permission[] calldata permissions) external override auth returns (bytes32 txHash) { txHash = keccak256(abi.encode(target, permissions)); require(plans[txHash].state == State.UNPLANNED, "Emergency already planned for."); // Removing or granting ROOT permissions is out of bounds for EmergencyBrake for (uint256 i = 0; i < permissions.length; i++){ for (uint256 j = 0; j < permissions[i].signatures.length; j++){ require( permissions[i].signatures[j] != ROOT, "Can't remove ROOT" ); } } plans[txHash] = Plan({ state: State.PLANNED, target: target, permissions: abi.encode(permissions) }); emit Planned(txHash, target); } /// @dev Erase a planned access removal transaction function cancel(bytes32 txHash) external override auth { require(plans[txHash].state == State.PLANNED, "Emergency not planned for."); delete plans[txHash]; emit Cancelled(txHash); } /// @dev Execute an access removal transaction function execute(bytes32 txHash) external override auth { Plan memory plan_ = plans[txHash]; require(plan_.state == State.PLANNED, "Emergency not planned for."); plans[txHash].state = State.EXECUTED; Permission[] memory permissions_ = abi.decode(plan_.permissions, (Permission[])); for (uint256 i = 0; i < permissions_.length; i++){ // AccessControl.sol doesn't revert if revoking permissions that haven't been granted // If we don't check, planner and executor can collude to gain access to contacts Permission memory permission_ = permissions_[i]; for (uint256 j = 0; j < permission_.signatures.length; j++){ AccessControl contact = AccessControl(permission_.contact); bytes4 signature_ = permission_.signatures[j]; require( contact.hasRole(signature_, plan_.target), "Permission not found" ); contact.revokeRole(signature_, plan_.target); } } emit Executed(txHash, plan_.target); } /// @dev Restore the orchestration from an isolated target function restore(bytes32 txHash) external override auth { Plan memory plan_ = plans[txHash]; require(plan_.state == State.EXECUTED, "Emergency plan not executed."); plans[txHash].state = State.PLANNED; Permission[] memory permissions_ = abi.decode(plan_.permissions, (Permission[])); for (uint256 i = 0; i < permissions_.length; i++){ Permission memory permission_ = permissions_[i]; for (uint256 j = 0; j < permission_.signatures.length; j++){ AccessControl contact = AccessControl(permission_.contact); bytes4 signature_ = permission_.signatures[j]; contact.grantRole(signature_, plan_.target); } } emit Restored(txHash, plan_.target); } /// @dev Remove the restoring option from an isolated target function terminate(bytes32 txHash) external override auth { require(plans[txHash].state == State.EXECUTED, "Emergency plan not executed."); delete plans[txHash]; emit Terminated(txHash); } }
9,295
64
// Uint256ArrayUtils Prophecy Utility functions to handle uint256 Arrays /
library Uint256ArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(uint256[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { uint256 current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The uint256 to remove * @return Returns the array with the object removed. */ function remove(uint256[] memory A, uint256 a) internal pure returns (uint256[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { (uint256[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The uint256 to remove */ function removeStorage(uint256[] storage A, uint256 a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(uint256[] memory A, uint256 index) internal pure returns (uint256[] memory, uint256) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); uint256[] memory newUint256s = new uint256[](length - 1); for (uint256 i = 0; i < index; i++) { newUint256s[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newUint256s[j - 1] = A[j]; } return (newUint256s, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; uint256[] memory newUint256s = new uint256[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newUint256s[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newUint256s[aLength + j] = B[j]; } return newUint256s; } /** * Validate uint256 array is not empty and contains no duplicate elements. * * @param A Array of uint256 */ function _validateLengthAndUniqueness(uint256[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate uint256"); } }
library Uint256ArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(uint256[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { uint256 current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The uint256 to remove * @return Returns the array with the object removed. */ function remove(uint256[] memory A, uint256 a) internal pure returns (uint256[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { (uint256[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The uint256 to remove */ function removeStorage(uint256[] storage A, uint256 a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(uint256[] memory A, uint256 index) internal pure returns (uint256[] memory, uint256) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); uint256[] memory newUint256s = new uint256[](length - 1); for (uint256 i = 0; i < index; i++) { newUint256s[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newUint256s[j - 1] = A[j]; } return (newUint256s, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; uint256[] memory newUint256s = new uint256[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newUint256s[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newUint256s[aLength + j] = B[j]; } return newUint256s; } /** * Validate uint256 array is not empty and contains no duplicate elements. * * @param A Array of uint256 */ function _validateLengthAndUniqueness(uint256[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate uint256"); } }
54,291
1
// Emil Dudnyk /
contract ETHPriceWatcher { address public ethPriceProvider; modifier onlyEthPriceProvider() { require(msg.sender == ethPriceProvider); _; } function receiveEthPrice(uint ethUsdPrice) external; function setEthPriceProvider(address provider) external; }
contract ETHPriceWatcher { address public ethPriceProvider; modifier onlyEthPriceProvider() { require(msg.sender == ethPriceProvider); _; } function receiveEthPrice(uint ethUsdPrice) external; function setEthPriceProvider(address provider) external; }
61,098
0
// toString/
function toString(bytes32 _input) internal pure returns (string memory result) { bytes memory reversed = new bytes(32); uint256 i = 0; uint256 v = uint256(_input); while (v != 0) { reversed[i++] = bytes1(uint8(48 + (v % 16))); v = v / 16; } bytes memory s = new bytes(i); for (uint j = 0; j < i; j++) { s[j] = reversed[i - j - 1]; } result = string(s); }
function toString(bytes32 _input) internal pure returns (string memory result) { bytes memory reversed = new bytes(32); uint256 i = 0; uint256 v = uint256(_input); while (v != 0) { reversed[i++] = bytes1(uint8(48 + (v % 16))); v = v / 16; } bytes memory s = new bytes(i); for (uint j = 0; j < i; j++) { s[j] = reversed[i - j - 1]; } result = string(s); }
39,737
18
// Set the main DeCash Storage address
constructor(address _decashStorageAddress) { // Update the contract address _decashStorage = DeCashStorageInterface(_decashStorageAddress); }
constructor(address _decashStorageAddress) { // Update the contract address _decashStorage = DeCashStorageInterface(_decashStorageAddress); }
51,355
48
// Claimable Extension for the Ownable contract, where the ownership needs to be claimed.This allows the new owner to accept the transfer. /
contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } }
contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } }
1,025
410
// See {IERC777-send}. Also emits a {IERC20-Transfer} event for ERC20 compatibility. /
function send( address recipient, uint256 amount, bytes memory data ) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); }
function send( address recipient, uint256 amount, bytes memory data ) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); }
20,216
16
// H
[ 'M40 20v25h-5V30h-5v-5h5v-5h5Zm-20 0v5h10v5H20v15h-5V20h5Zm20-10v10h-5V10h5ZM20 20h-5V10h5v10Z', 'M60 0v60h-5V0h5Zm-5 55v5H30v-5h25Zm-25 0v5H5v-5h25ZM0 0h5v60H0V0Zm45 10v40H35v-5h5V10h5ZM30 30v5h-5v15H15v-5h5V30h10Zm5 0v5h-5v-5h5ZM25 10v15h-5V10h5ZM55 0v5H30V0h25ZM30 0v5H5V0h25Z' ],
[ 'M40 20v25h-5V30h-5v-5h5v-5h5Zm-20 0v5h10v5H20v15h-5V20h5Zm20-10v10h-5V10h5ZM20 20h-5V10h5v10Z', 'M60 0v60h-5V0h5Zm-5 55v5H30v-5h25Zm-25 0v5H5v-5h25ZM0 0h5v60H0V0Zm45 10v40H35v-5h5V10h5ZM30 30v5h-5v15H15v-5h5V30h10Zm5 0v5h-5v-5h5ZM25 10v15h-5V10h5ZM55 0v5H30V0h25ZM30 0v5H5V0h25Z' ],
5,170
9
// Get offer ranked siblings in the sorted offer list._offerId offer id. return nextOfferId_ id of the next offer in the sorted list of offers for this token pair.return prevOfferId_ id of the previous offer in the sorted list of offers for this token pair. /
function getOfferSiblings(uint256 _offerId) external view returns (
function getOfferSiblings(uint256 _offerId) external view returns (
32,424
77
// newController The new controller who should receive ownership of the provided DMM token IDs. /
function transferOwnershipToNewController(
function transferOwnershipToNewController(
27,461
11
// Public Functions //Contract initializer /_shipToken The token that is minted/_legacyShipToken The legacy token that is upgradable to _token/_beneficiary The address that receives the minting fees
function initialize(address _shipToken, address _legacyShipToken, address payable _beneficiary) public initializer
function initialize(address _shipToken, address _legacyShipToken, address payable _beneficiary) public initializer
8,487
22
// then, subtract claimed
claim -= redeemedRewards[_address];
claim -= redeemedRewards[_address];
49,857
119
// Amount of time--in seconds--a user must wait to withdraw an NFT.
uint256 withdrawalDelay;
uint256 withdrawalDelay;
33,739
11
// Funcion para ver las Notas
function VerNotas(string memory _idAlumno) public view returns(uint){ //transformo el id en un hash bytes32 hash_idAlumno = keccak256(abi.encodePacked(_idAlumno)); //Relaciono el id con la nota y la guardo en una variable, para luego retornarla uint _nota = Notas[hash_idAlumno]; return _nota; }
function VerNotas(string memory _idAlumno) public view returns(uint){ //transformo el id en un hash bytes32 hash_idAlumno = keccak256(abi.encodePacked(_idAlumno)); //Relaciono el id con la nota y la guardo en una variable, para luego retornarla uint _nota = Notas[hash_idAlumno]; return _nota; }
18,748
10
// SetTokenCount to 1
tokenCount = 1;
tokenCount = 1;
33,029
26
// remove from buffer
buffer = _buffer.sub(_toDistribute);
buffer = _buffer.sub(_toDistribute);
15,589
133
// Registry holding the rarity value of a given NFT./Nemitari Ajienka @najienka
interface INFTRarityRegister { /** * The Staking SC allows to stake Prizes won via lottery which can be used to increase the APY of * staked tokens according to the rarity of NFT staked. For this reason, * we need to hold a table that the Staking SC can query and get back the rarity value of a given * NFT price (even the ones in the past). */ event NftRarityStored( address indexed tokenAddress, uint256 tokenId, uint256 rarityValue ); /** * @dev Store the rarity of a given NFT * @param tokenAddress The NFT smart contract address e.g., ERC-721 standard contract * @param tokenId The NFT's unique token id * @param rarityValue The rarity of a given NFT address and id unique combination */ function storeNftRarity(address tokenAddress, uint256 tokenId, uint16 rarityValue) external; /** * @dev Get the rarity of a given NFT * @param tokenAddress The NFT smart contract address e.g., ERC-721 standard contract * @param tokenId The NFT's unique token id * @return The the rarity of a given NFT address and id unique combination and timestamp */ function getNftRarity(address tokenAddress, uint256 tokenId) external view returns (uint16); }
interface INFTRarityRegister { /** * The Staking SC allows to stake Prizes won via lottery which can be used to increase the APY of * staked tokens according to the rarity of NFT staked. For this reason, * we need to hold a table that the Staking SC can query and get back the rarity value of a given * NFT price (even the ones in the past). */ event NftRarityStored( address indexed tokenAddress, uint256 tokenId, uint256 rarityValue ); /** * @dev Store the rarity of a given NFT * @param tokenAddress The NFT smart contract address e.g., ERC-721 standard contract * @param tokenId The NFT's unique token id * @param rarityValue The rarity of a given NFT address and id unique combination */ function storeNftRarity(address tokenAddress, uint256 tokenId, uint16 rarityValue) external; /** * @dev Get the rarity of a given NFT * @param tokenAddress The NFT smart contract address e.g., ERC-721 standard contract * @param tokenId The NFT's unique token id * @return The the rarity of a given NFT address and id unique combination and timestamp */ function getNftRarity(address tokenAddress, uint256 tokenId) external view returns (uint16); }
48,202
37
// function to transfer NFT from user to contract
function stakeToken(uint256[] memory tokenId) private { uint256 releaseTime = block.timestamp; require(_totalStaked + tokenId.length <= 500, "max stake amount reached"); for (uint256 i = 0; i < tokenId.length; i++) { IERC721(NFTToken).transferFrom( msg.sender, address(this), tokenId[i] ); // User must approve() this contract address via the NFT ERC721 contract before NFT can be transfered uint256 currentStakingId = _stakingId; Staking memory staking = Staking( msg.sender, NFTToken, tokenId[i], releaseTime, releaseTime, 0, StakingStatus.Active, currentStakingId ); _StakedItem[_stakingId] = staking; _stakingId++; _totalStaked++; emit tokenStaked( msg.sender, staking.token, staking.tokenId, staking.status, currentStakingId ); } stakedCount[msg.sender] += tokenId.length; }
function stakeToken(uint256[] memory tokenId) private { uint256 releaseTime = block.timestamp; require(_totalStaked + tokenId.length <= 500, "max stake amount reached"); for (uint256 i = 0; i < tokenId.length; i++) { IERC721(NFTToken).transferFrom( msg.sender, address(this), tokenId[i] ); // User must approve() this contract address via the NFT ERC721 contract before NFT can be transfered uint256 currentStakingId = _stakingId; Staking memory staking = Staking( msg.sender, NFTToken, tokenId[i], releaseTime, releaseTime, 0, StakingStatus.Active, currentStakingId ); _StakedItem[_stakingId] = staking; _stakingId++; _totalStaked++; emit tokenStaked( msg.sender, staking.token, staking.tokenId, staking.status, currentStakingId ); } stakedCount[msg.sender] += tokenId.length; }
12,804
7
// keep track of who owns the nft
nftHolders[msg.sender] = newId;
nftHolders[msg.sender] = newId;
52,096
34
// emit ValorTraductoresModificado(valorTraductores);
24,089
234
// returns data to calculate amountIn, amountOut
function getTradeInfo() external virtual override view returns ( uint112 _reserve0, uint112 _reserve1, uint112 _vReserve0, uint112 _vReserve1,
function getTradeInfo() external virtual override view returns ( uint112 _reserve0, uint112 _reserve1, uint112 _vReserve0, uint112 _vReserve1,
28,068
52
// Binary search
uint256 _min; uint256 _max = userPointEpoch[addr]; for (uint256 i = 0; i < 128; i++) {// Will be always enough for 128-bit numbers if (_min >= _max) { break; }
uint256 _min; uint256 _max = userPointEpoch[addr]; for (uint256 i = 0; i < 128; i++) {// Will be always enough for 128-bit numbers if (_min >= _max) { break; }
477
10
// Public whitelist sale data
createPresale(4, 0.15 ether, 4101); addReserveTokenMinters(0x72b6f2Ed3Cc57BEf3f5C5319DFbFe82D29e0B93F);
createPresale(4, 0.15 ether, 4101); addReserveTokenMinters(0x72b6f2Ed3Cc57BEf3f5C5319DFbFe82D29e0B93F);
37,411
182
// This function is called by a borrower when they want to repay their loan. It can be called at any time after the loan has begun. The borrower will pay a pro-rata portion of their interest if the loan is paid off early. The interest will continue to accrue after the loan has expired. This function can continue to be called by the borrower even after the loan has expired to retrieve their NFT. Note that the lender can call NFTfi.liquidateOverdueLoan() at any time after the loan has expired, so a borrower should avoid paying their loan after the due
function payBackLoan(uint256 _loanId) external nonReentrant { // Sanity check that payBackLoan() and liquidateOverdueLoan() have // never been called on this loanId. Depending on how the rest of the // code turns out, this check may be unnecessary. require(!loanRepaidOrLiquidated[_loanId], 'Loan has already been repaid or liquidated'); // Fetch loan details from storage, but store them in memory for the // sake of saving gas. Loan memory loan = loanIdToLoan[_loanId]; // Check that the borrower is the caller, only the borrower is entitled // to the collateral. require(msg.sender == loan.borrower, 'Only the borrower can pay back a loan and reclaim the underlying NFT'); // Fetch current owner of loan promissory note. address lender = ownerOf(_loanId); // Calculate amounts to send to lender and admins uint256 interestDue = (loan.maximumRepaymentAmount).sub(loan.loanPrincipalAmount); if(loan.interestIsProRated == true){ interestDue = _computeInterestDue( loan.loanPrincipalAmount, loan.maximumRepaymentAmount, now.sub(uint256(loan.loanStartTime)), uint256(loan.loanDuration), uint256(loan.loanInterestRateForDurationInBasisPoints) ); } uint256 adminFee = _computeAdminFee(interestDue, uint256(loan.loanAdminFeeInBasisPoints)); uint256 payoffAmount = ((loan.loanPrincipalAmount).add(interestDue)).sub(adminFee); // Mark loan as repaid before doing any external transfers to follow // the Checks-Effects-Interactions design pattern. loanRepaidOrLiquidated[_loanId] = true; // Update number of active loans. totalActiveLoans = totalActiveLoans.sub(1); // Transfer principal-plus-interest-minus-fees from borrower to lender IERC20(loan.loanERC20Denomination).transferFrom(loan.borrower, lender, payoffAmount); // Transfer fees from borrower to admins IERC20(loan.loanERC20Denomination).transferFrom(loan.borrower, owner(), adminFee); // Transfer collateral from this contract to borrower. require(_transferNftToAddress( loan.nftCollateralContract, loan.nftCollateralId, loan.borrower ), 'NFT was not successfully transferred'); // Destroy the lender's promissory note. _burn(_loanId); // Emit an event with all relevant details from this transaction. emit LoanRepaid( _loanId, loan.borrower, lender, loan.loanPrincipalAmount, loan.nftCollateralId, payoffAmount, adminFee, loan.nftCollateralContract, loan.loanERC20Denomination ); // Delete the loan from storage in order to achieve a substantial gas // savings and to lessen the burden of storage on Ethereum nodes, since // we will never access this loan's details again, and the details are // still available through event data. delete loanIdToLoan[_loanId]; }
function payBackLoan(uint256 _loanId) external nonReentrant { // Sanity check that payBackLoan() and liquidateOverdueLoan() have // never been called on this loanId. Depending on how the rest of the // code turns out, this check may be unnecessary. require(!loanRepaidOrLiquidated[_loanId], 'Loan has already been repaid or liquidated'); // Fetch loan details from storage, but store them in memory for the // sake of saving gas. Loan memory loan = loanIdToLoan[_loanId]; // Check that the borrower is the caller, only the borrower is entitled // to the collateral. require(msg.sender == loan.borrower, 'Only the borrower can pay back a loan and reclaim the underlying NFT'); // Fetch current owner of loan promissory note. address lender = ownerOf(_loanId); // Calculate amounts to send to lender and admins uint256 interestDue = (loan.maximumRepaymentAmount).sub(loan.loanPrincipalAmount); if(loan.interestIsProRated == true){ interestDue = _computeInterestDue( loan.loanPrincipalAmount, loan.maximumRepaymentAmount, now.sub(uint256(loan.loanStartTime)), uint256(loan.loanDuration), uint256(loan.loanInterestRateForDurationInBasisPoints) ); } uint256 adminFee = _computeAdminFee(interestDue, uint256(loan.loanAdminFeeInBasisPoints)); uint256 payoffAmount = ((loan.loanPrincipalAmount).add(interestDue)).sub(adminFee); // Mark loan as repaid before doing any external transfers to follow // the Checks-Effects-Interactions design pattern. loanRepaidOrLiquidated[_loanId] = true; // Update number of active loans. totalActiveLoans = totalActiveLoans.sub(1); // Transfer principal-plus-interest-minus-fees from borrower to lender IERC20(loan.loanERC20Denomination).transferFrom(loan.borrower, lender, payoffAmount); // Transfer fees from borrower to admins IERC20(loan.loanERC20Denomination).transferFrom(loan.borrower, owner(), adminFee); // Transfer collateral from this contract to borrower. require(_transferNftToAddress( loan.nftCollateralContract, loan.nftCollateralId, loan.borrower ), 'NFT was not successfully transferred'); // Destroy the lender's promissory note. _burn(_loanId); // Emit an event with all relevant details from this transaction. emit LoanRepaid( _loanId, loan.borrower, lender, loan.loanPrincipalAmount, loan.nftCollateralId, payoffAmount, adminFee, loan.nftCollateralContract, loan.loanERC20Denomination ); // Delete the loan from storage in order to achieve a substantial gas // savings and to lessen the burden of storage on Ethereum nodes, since // we will never access this loan's details again, and the details are // still available through event data. delete loanIdToLoan[_loanId]; }
10,256
130
// Returns the ERC20 asset token used for deposits./Should be implemented in a child contract during the inheritance./ return The ERC20 asset token.
function _token() internal view virtual returns (IERC20Upgradeable);
function _token() internal view virtual returns (IERC20Upgradeable);
29,753
65
// make sure request is still valid
if (validUntil_ > 0 && validUntil_ < block.timestamp) { revert AvoWallet__Expired(); }
if (validUntil_ > 0 && validUntil_ < block.timestamp) { revert AvoWallet__Expired(); }
25,480
28
// Emoji
characterModifier = _characterList[i].skinToneModifier; bytes memory charAsBytes = Utils.characterToUnicodeBytes( 0, // We still do the conversion for emojis to validate skin tone modifiers tileData.characterIndex, characterModifier );
characterModifier = _characterList[i].skinToneModifier; bytes memory charAsBytes = Utils.characterToUnicodeBytes( 0, // We still do the conversion for emojis to validate skin tone modifiers tileData.characterIndex, characterModifier );
14,756
106
// Transfer tokens from one address to another. from The address you want to send tokens from. to The address you want to transfer to. value The amount of tokens to be transferred. /
function transferFrom(address from, address to, uint256 value) external validRecipient(to) updateAccount(from) updateAccount(to) returns (bool)
function transferFrom(address from, address to, uint256 value) external validRecipient(to) updateAccount(from) updateAccount(to) returns (bool)
1,611
12
// "burnable"
function burn(uint256 amount) external { require(_balances[msg.sender] >= amount, ERROR_BTL); _burn(msg.sender, amount); }
function burn(uint256 amount) external { require(_balances[msg.sender] >= amount, ERROR_BTL); _burn(msg.sender, amount); }
38,532
410
// dYdX SoloMargin contract object. /
SoloMargin constant private _soloMargin = SoloMargin(SOLO_MARGIN_CONTRACT);
SoloMargin constant private _soloMargin = SoloMargin(SOLO_MARGIN_CONTRACT);
10,992
308
// Total asset cash in the market
uint80 totalAssetCash;
uint80 totalAssetCash;
2,246
18
// Ensure that the component index is in range.
if (componentIndex >= offer.length) { revert OfferCriteriaResolverOutOfRange(); }
if (componentIndex >= offer.length) { revert OfferCriteriaResolverOutOfRange(); }
14,956
41
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (Error(error).fail(FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
return (Error(error).fail(FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
27,445
167
// File: contracts\data\WitnetBoardData.sol/Witnet Request Board base data model. /The Witnet Foundation.
abstract contract WitnetBoardData { bytes32 internal constant _WITNET_BOARD_DATA_SLOTHASH = /* keccak256("io.witnet.boards.data") */ 0xf595240b351bc8f951c2f53b26f4e78c32cb62122cf76c19b7fdda7d4968e183; struct WitnetBoardState { address base; address owner; uint256 numQueries; mapping (uint => Witnet.Query) queries; } constructor() { _state().owner = msg.sender; } /// Asserts the given query is currently in the given status. modifier inStatus(uint256 _queryId, Witnet.QueryStatus _status) { require( _getQueryStatus(_queryId) == _status, _getQueryStatusRevertMessage(_status) ); _; } /// Asserts the given query was previously posted and that it was not yet deleted. modifier notDeleted(uint256 _queryId) { require(_queryId > 0 && _queryId <= _state().numQueries, "WitnetBoardData: not yet posted"); require(_getRequester(_queryId) != address(0), "WitnetBoardData: deleted"); _; } /// Asserts caller corresponds to the current owner. modifier onlyOwner { require(msg.sender == _state().owner, "WitnetBoardData: only owner"); _; } /// Asserts the give query was actually posted before calling this method. modifier wasPosted(uint256 _queryId) { require(_queryId > 0 && _queryId <= _state().numQueries, "WitnetBoardData: not yet posted"); _; } // ================================================================================================================ // --- Internal functions ----------------------------------------------------------------------------------------- /// Gets current status of given query. function _getQueryStatus(uint256 _queryId) internal view returns (Witnet.QueryStatus) { if (_queryId == 0 || _queryId > _state().numQueries) { // "Unknown" status if queryId is out of range: return Witnet.QueryStatus.Unknown; } else { Witnet.Query storage _query = _state().queries[_queryId]; if (_query.response.drTxHash != 0) { // Query is in "Reported" status as soon as the hash of the // Witnet transaction that solved the query is reported // back from a Witnet bridge: return Witnet.QueryStatus.Reported; } else if ( _query.from != address(0) || _query.request.requester != address(0) // (avoids breaking change when upgrading from 0.5.3 to 0.5.4) ) { // Otherwise, while address from which the query was posted // is kept in storage, the query remains in "Posted" status: return Witnet.QueryStatus.Posted; } else { // Requester's address is removed from storage only if // the query gets "Deleted" by its requester. return Witnet.QueryStatus.Deleted; } } } function _getQueryStatusRevertMessage(Witnet.QueryStatus _status) internal pure returns (string memory) { if (_status == Witnet.QueryStatus.Posted) { return "WitnetBoardData: not in Posted status"; } else if (_status == Witnet.QueryStatus.Reported) { return "WitnetBoardData: not in Reported status"; } else if (_status == Witnet.QueryStatus.Deleted) { return "WitnetBoardData: not in Deleted status"; } else { return "WitnetBoardData: bad mood"; } } /// Gets from of a given query. function _getRequester(uint256 _queryId) internal view returns (address) { return _state().queries[_queryId].from; } /// Gets the Witnet.Request part of a given query. function _getRequestData(uint256 _queryId) internal view returns (Witnet.Request storage) { return _state().queries[_queryId].request; } /// Gets the Witnet.Result part of a given query. function _getResponseData(uint256 _queryId) internal view returns (Witnet.Response storage) { return _state().queries[_queryId].response; } /// Returns storage pointer to contents of 'WitnetBoardState' struct. function _state() internal pure returns (WitnetBoardState storage _ptr) { assembly { _ptr.slot := _WITNET_BOARD_DATA_SLOTHASH } } }
abstract contract WitnetBoardData { bytes32 internal constant _WITNET_BOARD_DATA_SLOTHASH = /* keccak256("io.witnet.boards.data") */ 0xf595240b351bc8f951c2f53b26f4e78c32cb62122cf76c19b7fdda7d4968e183; struct WitnetBoardState { address base; address owner; uint256 numQueries; mapping (uint => Witnet.Query) queries; } constructor() { _state().owner = msg.sender; } /// Asserts the given query is currently in the given status. modifier inStatus(uint256 _queryId, Witnet.QueryStatus _status) { require( _getQueryStatus(_queryId) == _status, _getQueryStatusRevertMessage(_status) ); _; } /// Asserts the given query was previously posted and that it was not yet deleted. modifier notDeleted(uint256 _queryId) { require(_queryId > 0 && _queryId <= _state().numQueries, "WitnetBoardData: not yet posted"); require(_getRequester(_queryId) != address(0), "WitnetBoardData: deleted"); _; } /// Asserts caller corresponds to the current owner. modifier onlyOwner { require(msg.sender == _state().owner, "WitnetBoardData: only owner"); _; } /// Asserts the give query was actually posted before calling this method. modifier wasPosted(uint256 _queryId) { require(_queryId > 0 && _queryId <= _state().numQueries, "WitnetBoardData: not yet posted"); _; } // ================================================================================================================ // --- Internal functions ----------------------------------------------------------------------------------------- /// Gets current status of given query. function _getQueryStatus(uint256 _queryId) internal view returns (Witnet.QueryStatus) { if (_queryId == 0 || _queryId > _state().numQueries) { // "Unknown" status if queryId is out of range: return Witnet.QueryStatus.Unknown; } else { Witnet.Query storage _query = _state().queries[_queryId]; if (_query.response.drTxHash != 0) { // Query is in "Reported" status as soon as the hash of the // Witnet transaction that solved the query is reported // back from a Witnet bridge: return Witnet.QueryStatus.Reported; } else if ( _query.from != address(0) || _query.request.requester != address(0) // (avoids breaking change when upgrading from 0.5.3 to 0.5.4) ) { // Otherwise, while address from which the query was posted // is kept in storage, the query remains in "Posted" status: return Witnet.QueryStatus.Posted; } else { // Requester's address is removed from storage only if // the query gets "Deleted" by its requester. return Witnet.QueryStatus.Deleted; } } } function _getQueryStatusRevertMessage(Witnet.QueryStatus _status) internal pure returns (string memory) { if (_status == Witnet.QueryStatus.Posted) { return "WitnetBoardData: not in Posted status"; } else if (_status == Witnet.QueryStatus.Reported) { return "WitnetBoardData: not in Reported status"; } else if (_status == Witnet.QueryStatus.Deleted) { return "WitnetBoardData: not in Deleted status"; } else { return "WitnetBoardData: bad mood"; } } /// Gets from of a given query. function _getRequester(uint256 _queryId) internal view returns (address) { return _state().queries[_queryId].from; } /// Gets the Witnet.Request part of a given query. function _getRequestData(uint256 _queryId) internal view returns (Witnet.Request storage) { return _state().queries[_queryId].request; } /// Gets the Witnet.Result part of a given query. function _getResponseData(uint256 _queryId) internal view returns (Witnet.Response storage) { return _state().queries[_queryId].response; } /// Returns storage pointer to contents of 'WitnetBoardState' struct. function _state() internal pure returns (WitnetBoardState storage _ptr) { assembly { _ptr.slot := _WITNET_BOARD_DATA_SLOTHASH } } }
19,867
4
// triggered when the rate between two tokens in the converter changesnote that the event might be dispatched for rate updates between any two tokens in the convertertoken1 address of the first token token2 address of the second token rateN rate of 1 unit of `token1` in `token2` (numerator) rateD rate of 1 unit of `token1` in `token2` (denominator) /
event TokenRateUpdate(address indexed token1, address indexed token2, uint256 rateN, uint256 rateD);
event TokenRateUpdate(address indexed token1, address indexed token2, uint256 rateN, uint256 rateD);
14,305
15
// Withdraws the specified amount of tokens from the sender's deposit with the specified ID
function withdraw(uint256 id, uint256 amount) external { address msgSender = _msgSender(); uint256 blockNumber = block.number; Unbond[] storage unbonds = _accountUnbonds[msgSender]; // Take this opportunity to clean up any expired unbonds for (uint256 i = unbonds.length; i > 0; i--) { if (unbonds[i - 1].expiryBlock <= blockNumber) { unbonds[i - 1] = unbonds[unbonds.length - 1]; unbonds.pop(); } } (Deposit storage deposit, Deposit[] storage deposits, uint256 index) = _getDeposit(msgSender, id); require(deposit.amount >= amount, "SchnoodleFarming: cannot withdraw more than deposited"); require(deposit.blockNumber + _vestingBlocksFactor * deposit.vestingBlocks / 1000 < blockNumber, "SchnoodleFarming: cannot withdraw during vesting blocks"); (uint256 netReward, uint256 grossReward, uint256 newCumulativeTotal) = _getRewardInfo(deposit, amount, blockNumber); // Update all tracking states to remove the withdrawn deposit (_totalTokens, _totalDepositWeight) = _getAggregatedTotals(-int256(amount), deposit.vestingBlocks, deposit.unbondingBlocks); _cumulativeTotal = newCumulativeTotal; _checkpointBlock = blockNumber; _balances[msgSender] -= amount; deposit.amount -= amount; // Start the unbonding procedure for the withdrawn amount unbonds.push(Unbond(amount, blockNumber + _unbondingBlocksFactor * deposit.unbondingBlocks / 1000)); // Remove the deposit if it is fully withdrawn by replacing it with the last deposit in the array if (deposit.amount == 0) { deposits[index] = deposits[deposits.length - 1]; deposits.pop(); } farmingReward(msgSender, netReward, grossReward); emit Withdrawn(msgSender, id, amount, netReward, grossReward, _totalTokens, _totalDepositWeight, _cumulativeTotal); }
function withdraw(uint256 id, uint256 amount) external { address msgSender = _msgSender(); uint256 blockNumber = block.number; Unbond[] storage unbonds = _accountUnbonds[msgSender]; // Take this opportunity to clean up any expired unbonds for (uint256 i = unbonds.length; i > 0; i--) { if (unbonds[i - 1].expiryBlock <= blockNumber) { unbonds[i - 1] = unbonds[unbonds.length - 1]; unbonds.pop(); } } (Deposit storage deposit, Deposit[] storage deposits, uint256 index) = _getDeposit(msgSender, id); require(deposit.amount >= amount, "SchnoodleFarming: cannot withdraw more than deposited"); require(deposit.blockNumber + _vestingBlocksFactor * deposit.vestingBlocks / 1000 < blockNumber, "SchnoodleFarming: cannot withdraw during vesting blocks"); (uint256 netReward, uint256 grossReward, uint256 newCumulativeTotal) = _getRewardInfo(deposit, amount, blockNumber); // Update all tracking states to remove the withdrawn deposit (_totalTokens, _totalDepositWeight) = _getAggregatedTotals(-int256(amount), deposit.vestingBlocks, deposit.unbondingBlocks); _cumulativeTotal = newCumulativeTotal; _checkpointBlock = blockNumber; _balances[msgSender] -= amount; deposit.amount -= amount; // Start the unbonding procedure for the withdrawn amount unbonds.push(Unbond(amount, blockNumber + _unbondingBlocksFactor * deposit.unbondingBlocks / 1000)); // Remove the deposit if it is fully withdrawn by replacing it with the last deposit in the array if (deposit.amount == 0) { deposits[index] = deposits[deposits.length - 1]; deposits.pop(); } farmingReward(msgSender, netReward, grossReward); emit Withdrawn(msgSender, id, amount, netReward, grossReward, _totalTokens, _totalDepositWeight, _cumulativeTotal); }
26,397
37
// Make sure input address is clean. (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
14,719
13
// Avoid overflowing the Merkle tree (and prevent edge case in computing `branch`)
require(deposit_count < MAX_DEPOSIT_COUNT, "DepositContract: merkle tree full");
require(deposit_count < MAX_DEPOSIT_COUNT, "DepositContract: merkle tree full");
12,250
34
// delete request
clearDocumentKeyShadowRetrievalRequest(retrievalId, request);
clearDocumentKeyShadowRetrievalRequest(retrievalId, request);
8,502
197
// Deposit LP tokens to MasterYmen for MUTANT 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.accMutantPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMutantTransfer(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.accMutantPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
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.accMutantPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMutantTransfer(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.accMutantPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
4,614
28
// Withdraw unsale Token/
function tokenWithdraw(address receiver, uint256 tokens) onlyFounder { require(receiver != 0x0); require(tokens > 0); if (!tokenReward.transfer(receiver, tokens)) { revert(); } }
function tokenWithdraw(address receiver, uint256 tokens) onlyFounder { require(receiver != 0x0); require(tokens > 0); if (!tokenReward.transfer(receiver, tokens)) { revert(); } }
36,580
40
// Function : Enables The Liquidity and Worth DVC Fund fee// Parameters : -- // Only Owner Function /
function enableAllFees() external onlyOwner { _liquidityFee = 25; _previousLiquidityFee = _liquidityFee; _worthDVCFundFee = 25; _previousWorthDVCFundFee = _worthDVCFundFee; swapAndLiquifyEnabled = true; emit SwapAndLiquifyEnabledUpdated(swapAndLiquifyEnabled); }
function enableAllFees() external onlyOwner { _liquidityFee = 25; _previousLiquidityFee = _liquidityFee; _worthDVCFundFee = 25; _previousWorthDVCFundFee = _worthDVCFundFee; swapAndLiquifyEnabled = true; emit SwapAndLiquifyEnabledUpdated(swapAndLiquifyEnabled); }
54,946
72
// Distribute sale eth input
modifier distributeSaleInput(address _owner) { uint256 contractOwnerCommision; //1% uint256 playerShare; //99% if(msg.value > 100){ contractOwnerCommision = (msg.value / 100); playerShare = msg.value - contractOwnerCommision; }else{ contractOwnerCommision = 0; playerShare = msg.value; } addressInfo[_owner].withdrawal += playerShare; addressInfo[contractOwner].withdrawal += contractOwnerCommision; pendingWithdrawal += playerShare + contractOwnerCommision; _; }
modifier distributeSaleInput(address _owner) { uint256 contractOwnerCommision; //1% uint256 playerShare; //99% if(msg.value > 100){ contractOwnerCommision = (msg.value / 100); playerShare = msg.value - contractOwnerCommision; }else{ contractOwnerCommision = 0; playerShare = msg.value; } addressInfo[_owner].withdrawal += playerShare; addressInfo[contractOwner].withdrawal += contractOwnerCommision; pendingWithdrawal += playerShare + contractOwnerCommision; _; }
39,057
19
// Withdraw token./Only owner can call this function./_token The address of token to withdraw./_amount The amount of token to withdraw.
function withdrawToken(address _token, uint256 _amount) external;
function withdrawToken(address _token, uint256 _amount) external;
16,793
83
// See {IERC721-ownerOf}./
function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; }
function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; }
1,422
14
// Rewards accumulated by users
function rewards(address user) external view returns(uint128 accumulatedUserStart, uint128 accumulatedCheckpoint);
function rewards(address user) external view returns(uint128 accumulatedUserStart, uint128 accumulatedCheckpoint);
42,233
10
// Returns the amount of tokens owned by `account`. /
function balanceOf(address account) external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
28,398
127
// start
block.timestamp,
block.timestamp,
39,761
35
// we can just check that call not reverts because it wants to withdraw all amount
(sent,) = address(this).call.gas(withdrawGasLimit)( abi.encodeWithSignature("withdrawERC20Guarded(address,address,uint128,uint128)", tokenAddr, to, amount, amount) );
(sent,) = address(this).call.gas(withdrawGasLimit)( abi.encodeWithSignature("withdrawERC20Guarded(address,address,uint128,uint128)", tokenAddr, to, amount, amount) );
29,847
16
// @custom:legacy/Legacy getter for the bridge. Use BRIDGE going forward.
function l2Bridge() public view returns (address) { return BRIDGE; }
function l2Bridge() public view returns (address) { return BRIDGE; }
12,303
212
// Function to stop minting new tokens.
* NOTE: restricting access to owner only. See {BEP20Mintable-finishMinting}. */ function _finishMinting() internal override onlyOwner { super._finishMinting(); }
* NOTE: restricting access to owner only. See {BEP20Mintable-finishMinting}. */ function _finishMinting() internal override onlyOwner { super._finishMinting(); }
2,857
4
// -------------------- MODIFIERS ----------------------------
modifier onlyArbitrator { require(msg.sender == arbitrator); _; }
modifier onlyArbitrator { require(msg.sender == arbitrator); _; }
13,346
26
// claiming paid MKR back
if (msg.value > 0) {
if (msg.value > 0) {
48,015
79
// don't panic, no safemath, look above comment
(uint256(proportions[i]) * uint256(PROPORTION_BASE)) / totalProportions );
(uint256(proportions[i]) * uint256(PROPORTION_BASE)) / totalProportions );
28,923
24
// CrowdSale /
contract PreICO is Ownable { ERC20 public token; ERC20 public authorize; using SafeMath for uint; address public backEndOperator = msg.sender; address bounty = 0xAddEB4E7780DB11b7C5a0b7E96c133e50f05740E; // 0.4% - для баунти программы mapping(address=>bool) public whitelist; mapping(address => uint256) public investedEther; uint256 public startPreICO = 1543700145; uint256 public endPreICO = 1547510400; uint256 public investors; // total number of investors uint256 public weisRaised; // total amount collected by ether uint256 public hardCap1Stage = 10000000*1e18; // 10,000,000 SPC = $1,000,000 EURO uint256 public buyPrice; // 0.1 EURO uint256 public euroPrice; // Ether by USD uint256 public soldTokens; // solded tokens - > 10,000,000 SPC event Authorized(address wlCandidate, uint timestamp); event Revoked(address wlCandidate, uint timestamp); event UpdateDollar(uint256 time, uint256 _rate); modifier backEnd() { require(msg.sender == backEndOperator || msg.sender == owner); _; } // contract constructor constructor(ERC20 _token, ERC20 _authorize, uint256 usdETH) public { token = _token; authorize = _authorize; euroPrice = usdETH; buyPrice = (1e18/euroPrice).div(10); // 0.1 euro } // change the date of commencement of pre-sale function setStartSale(uint256 newStartSale) public onlyOwner { startPreICO = newStartSale; } // change the date of the end of pre-sale function setEndSale(uint256 newEndSale) public onlyOwner { endPreICO = newEndSale; } // Change of operator’s backend address function setBackEndAddress(address newBackEndOperator) public onlyOwner { backEndOperator = newBackEndOperator; } // Change in the rate of dollars to broadcast function setBuyPrice(uint256 _dollar) public backEnd { euroPrice = _dollar; buyPrice = (1e18/euroPrice).div(10); // 0.1 euro emit UpdateDollar(now, euroPrice); } /******************************************************************************* * Payable's section */ function isPreICO() public constant returns(bool) { return now >= startPreICO && now <= endPreICO; } // callback contract function function () public payable { require(authorize.isWhitelisted(msg.sender)); require(isPreICO()); require(msg.value >= buyPrice.mul(100)); // ~ 10 EURO SalePreICO(msg.sender, msg.value); require(soldTokens<=hardCap1Stage); investedEther[msg.sender] = investedEther[msg.sender].add(msg.value); } // release of tokens during the pre-sale period function SalePreICO(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); token.mintFromICO(_investor, tokens); soldTokens = soldTokens.add(tokens); uint256 tokensBoynty = tokens.div(250); // 2 % token.mintFromICO(bounty, tokensBoynty); weisRaised = weisRaised.add(_value); } function manualMint(address _investor, uint256 _tokens) public onlyOwner { token.mintFromICO(_investor, _tokens); } // Sending air from the contract function transferEthFromContract(address _to, uint256 amount) public onlyOwner { _to.transfer(amount); } }
contract PreICO is Ownable { ERC20 public token; ERC20 public authorize; using SafeMath for uint; address public backEndOperator = msg.sender; address bounty = 0xAddEB4E7780DB11b7C5a0b7E96c133e50f05740E; // 0.4% - для баунти программы mapping(address=>bool) public whitelist; mapping(address => uint256) public investedEther; uint256 public startPreICO = 1543700145; uint256 public endPreICO = 1547510400; uint256 public investors; // total number of investors uint256 public weisRaised; // total amount collected by ether uint256 public hardCap1Stage = 10000000*1e18; // 10,000,000 SPC = $1,000,000 EURO uint256 public buyPrice; // 0.1 EURO uint256 public euroPrice; // Ether by USD uint256 public soldTokens; // solded tokens - > 10,000,000 SPC event Authorized(address wlCandidate, uint timestamp); event Revoked(address wlCandidate, uint timestamp); event UpdateDollar(uint256 time, uint256 _rate); modifier backEnd() { require(msg.sender == backEndOperator || msg.sender == owner); _; } // contract constructor constructor(ERC20 _token, ERC20 _authorize, uint256 usdETH) public { token = _token; authorize = _authorize; euroPrice = usdETH; buyPrice = (1e18/euroPrice).div(10); // 0.1 euro } // change the date of commencement of pre-sale function setStartSale(uint256 newStartSale) public onlyOwner { startPreICO = newStartSale; } // change the date of the end of pre-sale function setEndSale(uint256 newEndSale) public onlyOwner { endPreICO = newEndSale; } // Change of operator’s backend address function setBackEndAddress(address newBackEndOperator) public onlyOwner { backEndOperator = newBackEndOperator; } // Change in the rate of dollars to broadcast function setBuyPrice(uint256 _dollar) public backEnd { euroPrice = _dollar; buyPrice = (1e18/euroPrice).div(10); // 0.1 euro emit UpdateDollar(now, euroPrice); } /******************************************************************************* * Payable's section */ function isPreICO() public constant returns(bool) { return now >= startPreICO && now <= endPreICO; } // callback contract function function () public payable { require(authorize.isWhitelisted(msg.sender)); require(isPreICO()); require(msg.value >= buyPrice.mul(100)); // ~ 10 EURO SalePreICO(msg.sender, msg.value); require(soldTokens<=hardCap1Stage); investedEther[msg.sender] = investedEther[msg.sender].add(msg.value); } // release of tokens during the pre-sale period function SalePreICO(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); token.mintFromICO(_investor, tokens); soldTokens = soldTokens.add(tokens); uint256 tokensBoynty = tokens.div(250); // 2 % token.mintFromICO(bounty, tokensBoynty); weisRaised = weisRaised.add(_value); } function manualMint(address _investor, uint256 _tokens) public onlyOwner { token.mintFromICO(_investor, _tokens); } // Sending air from the contract function transferEthFromContract(address _to, uint256 amount) public onlyOwner { _to.transfer(amount); } }
16,885
20
// Calculate geometric average of x and y, i.e. sqrt (xy) rounding down.Revert on overflow or in case xy is negative.x signed 64.64-bit fixed point number y signed 64.64-bit fixed point numberreturn signed 64.64-bit fixed point number /
function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } }
function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } }
31,186
7
// 0x00: Unknown error. Something went really bad!
Unknown,
Unknown,
29,981