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
8
// Open registration. Can only be called by the owner. /
function openRegistration() public override onlyOwner { _restricted = false; emit Unrestricted(); }
function openRegistration() public override onlyOwner { _restricted = false; emit Unrestricted(); }
37,981
6
// Redeem token and burn VUSD amount less redeem fee, if any. _token Token to redeem, it should be 1 of the supported tokens from treasury. _vusdAmount VUSD amount to burn. VUSD will be burnt from caller _tokenReceiver Address of token receiver /
function redeem( address _token, uint256 _vusdAmount, address _tokenReceiver
function redeem( address _token, uint256 _vusdAmount, address _tokenReceiver
41,963
210
// Requests randomness /
function getRandomNumber() public returns (bytes32 requestId) { uint256 nextId = totalSupply(); require(nextId >= MAX_FEET, "Supply not all minted"); require(randomnessState == 0, "Randomness already requested"); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); randomnessState = 1; return requestRandomness(keyHash, fee); }
function getRandomNumber() public returns (bytes32 requestId) { uint256 nextId = totalSupply(); require(nextId >= MAX_FEET, "Supply not all minted"); require(randomnessState == 0, "Randomness already requested"); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); randomnessState = 1; return requestRandomness(keyHash, fee); }
12,573
41
// Get User Left Lp Can Buy /
function getUserLeftLpCanBuy(address user, uint256 bondId) public view returns (uint256)
function getUserLeftLpCanBuy(address user, uint256 bondId) public view returns (uint256)
30,205
0
// REMOVE TESTNET ADDRESSES BEFORE DEPLOYMENT ON MAINNET
address payable internal devWallet = payable(0x15044445b4491De2D555fe91a7347bBF4C0A41fa);
address payable internal devWallet = payable(0x15044445b4491De2D555fe91a7347bBF4C0A41fa);
4,884
248
// Constructor _owner The address which controls this contract. _associatedContract The ERC20 contract whose state this composes. /
constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public
constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public
30,769
406
// Create a new instance of an app linked to this kernel and set its baseimplementation if it was not already setCreate a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`_appId Identifier for app_appBase Address of the app's base implementation_initializePayload Payload for call made by the proxy during its construction to initialize_setDefault Whether the app proxy app is the default one.Useful when the Kernel needs to know of an instance of a particular app,like Vault for escape hatch mechanism. return AppProxy instance/
function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy)
function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy)
49,101
27
// send quit request for the next election /
function quitRequest() public nonReentrant { require(deposits[msg.sender].amount > 0, "do not have deposit"); // when not in consensus period require( ITssGroupManager(tssGroupContract).memberExistInActive(deposits[msg.sender].pubKey) || ITssGroupManager(tssGroupContract).memberExistActive(deposits[msg.sender].pubKey), "not at the inactive group or active group" ); // is active member for (uint256 i = 0; i < quitRequestList.length; i++) { require(quitRequestList[i] != msg.sender, "already in quitRequestList"); } quitRequestList.push(msg.sender); }
function quitRequest() public nonReentrant { require(deposits[msg.sender].amount > 0, "do not have deposit"); // when not in consensus period require( ITssGroupManager(tssGroupContract).memberExistInActive(deposits[msg.sender].pubKey) || ITssGroupManager(tssGroupContract).memberExistActive(deposits[msg.sender].pubKey), "not at the inactive group or active group" ); // is active member for (uint256 i = 0; i < quitRequestList.length; i++) { require(quitRequestList[i] != msg.sender, "already in quitRequestList"); } quitRequestList.push(msg.sender); }
31,223
21
// check transferHandler is whitelisted (if used)
if (transferHandler != address(0)) { require(flashReceiverIsWhitelisted[transferHandler] || flashReceiverIsWhitelisted[address(0)], "flash receiver not whitelisted"); }
if (transferHandler != address(0)) { require(flashReceiverIsWhitelisted[transferHandler] || flashReceiverIsWhitelisted[address(0)], "flash receiver not whitelisted"); }
36,011
121
// Creates `amount` tokens of token type `id`, and assigns them to `account`.
* Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); require(!_exists(id)); require(amount != 0, "Supply should be positive"); _creators.set(id, account); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); }
* Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); require(!_exists(id)); require(amount != 0, "Supply should be positive"); _creators.set(id, account); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); }
40,178
9
// Trigger global check point
function checkpoint() external;
function checkpoint() external;
2,533
86
// Remove Bonder from allowlist bonder The address being removed as a Bonder /
function removeBonder(address bonder) external onlyGovernance { require(_isBonder[bonder] == true, "ACT: Address is not bonder"); _isBonder[bonder] = false; emit BonderRemoved(bonder); }
function removeBonder(address bonder) external onlyGovernance { require(_isBonder[bonder] == true, "ACT: Address is not bonder"); _isBonder[bonder] = false; emit BonderRemoved(bonder); }
58,041
8
// SOLIDITY THINGS
function supportsInterface(bytes4 interfaceId) public view override(ERC1155, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); }
function supportsInterface(bytes4 interfaceId) public view override(ERC1155, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); }
19,985
54
// Gets the amount of AFN locked in the contract
uint256 totalAFN = AFN.balanceOf(address(this));
uint256 totalAFN = AFN.balanceOf(address(this));
36,444
26
// Establish liquidity if the sale period ended or the liquidity sale has been sold out.
function establishLiquidity() external
function establishLiquidity() external
7,744
6
// @custom:oz-retyped-from mapping(uint256 => Governor.ProposalCore)
mapping(uint256 => ProposalCore) private _proposals;
mapping(uint256 => ProposalCore) private _proposals;
1,720
71
// The automatic end time for the presale (if usePresaleTimes is true and presaleActive is true)
uint32 presaleEndTime;
uint32 presaleEndTime;
50,520
12
// switch in all three arrays together
(weights[uint(i)], weights[uint(j)]) = (weights[uint(j)], weights[uint(i)]); (addresses[uint(i)], addresses[uint(j)]) = (addresses[uint(j)], addresses[uint(i)]); (ips[uint(i)], ips[uint(j)]) = (ips[uint(j)], ips[uint(i)]); i++; j--;
(weights[uint(i)], weights[uint(j)]) = (weights[uint(j)], weights[uint(i)]); (addresses[uint(i)], addresses[uint(j)]) = (addresses[uint(j)], addresses[uint(i)]); (ips[uint(i)], ips[uint(j)]) = (ips[uint(j)], ips[uint(i)]); i++; j--;
48,607
62
// Taylor series around x_0=0.57 exp(-x_0) + (-1)exp(-x_0)(x-x_0) + exp(-x_0)(x-x_0)^2 + (-1)exp(-x_0)(x-x_0)^3 e^(-0.57) = 0.565525 (the similarity is a coincidence) Note: solidity can't exponentiate a negative number if the operands are uint. Example: (x-x_0)2 throws if x<x_0
if (xe6 < 57e4) return (565525 * (10**18 - 10**12 * (xe6 - 57*10**4) + 10**6 * (57*10**4 - xe6)**2 / 2 + (57*10**4 - xe6)**3 / 6)) / 10**18; return (565525 * (10**18 - 10**12 * (xe6 - 57*10**4) + 10**6 * (xe6 - 57*10**4)**2 / 2 - (xe6 - 57*10**4)**3 / 6)) / 10**18;
if (xe6 < 57e4) return (565525 * (10**18 - 10**12 * (xe6 - 57*10**4) + 10**6 * (57*10**4 - xe6)**2 / 2 + (57*10**4 - xe6)**3 / 6)) / 10**18; return (565525 * (10**18 - 10**12 * (xe6 - 57*10**4) + 10**6 * (xe6 - 57*10**4)**2 / 2 - (xe6 - 57*10**4)**3 / 6)) / 10**18;
37,681
434
// Returns a bool if `connector` is registered or not. connector The address of the Connector contract to check if registered. /
function getRegisteredConnector(address connector) external view override returns (bool)
function getRegisteredConnector(address connector) external view override returns (bool)
13,262
26
// Safe cast from uint to uint48
function to48(uint a) internal pure returns (uint48 b) { b = uint48(a); assert(uint(b) == a); }
function to48(uint a) internal pure returns (uint48 b) { b = uint48(a); assert(uint(b) == a); }
13,016
3
// reward token address, ERC20
address public rewardToken;
address public rewardToken;
13,065
105
// if refunding a child proposal also account the parent receipt
if (proposal.parentProposalId > 0) { _accountRefundOnParent(msg.sender, proposal.parentProposalId, rawVoteAmount); }
if (proposal.parentProposalId > 0) { _accountRefundOnParent(msg.sender, proposal.parentProposalId, rawVoteAmount); }
47,424
45
// Investor refunds ERC20 token to Growdrop by Growdrop's identifier.Refunding CToken amount should be bigger than 0.Refunding amount calculated as CToken should be smaller than investor's funded amount calculated as CToken by Growdrop's identifier.Can refund only after started and before ended.
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information. * * @param _GrowdropCount Growdrop's identifier * @param Amount ERC20 token amount to refund to Growdrop */ function Redeem(uint256 _GrowdropCount, uint256 Amount) public { require(GrowdropStart[_GrowdropCount], "not started"); require(now<GrowdropEndTime[_GrowdropCount], "already ended"); uint256 _exchangeRateCurrent = CToken[_GrowdropCount].exchangeRateCurrent(); uint256 _ctoken; uint256 _toMinAmount; (_ctoken,_toMinAmount) = toMinAmount(Amount, _exchangeRateCurrent); require(_ctoken>0 && _ctoken<=MulAndDiv(InvestAmountPerAddress[_GrowdropCount][msg.sender], 1e18, _exchangeRateCurrent), "redeem error"); uint256 actualAmount; uint256 actualCToken; (actualCToken, actualAmount) = toActualAmount(_toMinAmount, _exchangeRateCurrent); CTokenPerAddress[_GrowdropCount][msg.sender] = Sub(CTokenPerAddress[_GrowdropCount][msg.sender], _ctoken); TotalCTokenAmount[_GrowdropCount] = Sub(TotalCTokenAmount[_GrowdropCount],_ctoken); ActualCTokenPerAddress[_GrowdropCount][msg.sender] = Sub(ActualCTokenPerAddress[_GrowdropCount][msg.sender], actualCToken); TotalCTokenActual[_GrowdropCount] = Sub(TotalCTokenActual[_GrowdropCount], actualCToken); InvestAmountPerAddress[_GrowdropCount][msg.sender] = Sub(InvestAmountPerAddress[_GrowdropCount][msg.sender], _toMinAmount); TotalMintedAmount[_GrowdropCount] = Sub(TotalMintedAmount[_GrowdropCount], _toMinAmount); ActualPerAddress[_GrowdropCount][msg.sender] = Sub(ActualPerAddress[_GrowdropCount][msg.sender], actualAmount); TotalMintedActual[_GrowdropCount] = Sub(TotalMintedActual[_GrowdropCount], actualAmount); require(CToken[_GrowdropCount].redeemUnderlying(Amount)==0, "error in redeem"); require(Token[_GrowdropCount].transfer(msg.sender, Amount), "transfer token error"); TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])] = Sub(TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])], _toMinAmount); EventIdx += 1; emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], CTokenPerAddress[_GrowdropCount][msg.sender], 1, now); }
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information. * * @param _GrowdropCount Growdrop's identifier * @param Amount ERC20 token amount to refund to Growdrop */ function Redeem(uint256 _GrowdropCount, uint256 Amount) public { require(GrowdropStart[_GrowdropCount], "not started"); require(now<GrowdropEndTime[_GrowdropCount], "already ended"); uint256 _exchangeRateCurrent = CToken[_GrowdropCount].exchangeRateCurrent(); uint256 _ctoken; uint256 _toMinAmount; (_ctoken,_toMinAmount) = toMinAmount(Amount, _exchangeRateCurrent); require(_ctoken>0 && _ctoken<=MulAndDiv(InvestAmountPerAddress[_GrowdropCount][msg.sender], 1e18, _exchangeRateCurrent), "redeem error"); uint256 actualAmount; uint256 actualCToken; (actualCToken, actualAmount) = toActualAmount(_toMinAmount, _exchangeRateCurrent); CTokenPerAddress[_GrowdropCount][msg.sender] = Sub(CTokenPerAddress[_GrowdropCount][msg.sender], _ctoken); TotalCTokenAmount[_GrowdropCount] = Sub(TotalCTokenAmount[_GrowdropCount],_ctoken); ActualCTokenPerAddress[_GrowdropCount][msg.sender] = Sub(ActualCTokenPerAddress[_GrowdropCount][msg.sender], actualCToken); TotalCTokenActual[_GrowdropCount] = Sub(TotalCTokenActual[_GrowdropCount], actualCToken); InvestAmountPerAddress[_GrowdropCount][msg.sender] = Sub(InvestAmountPerAddress[_GrowdropCount][msg.sender], _toMinAmount); TotalMintedAmount[_GrowdropCount] = Sub(TotalMintedAmount[_GrowdropCount], _toMinAmount); ActualPerAddress[_GrowdropCount][msg.sender] = Sub(ActualPerAddress[_GrowdropCount][msg.sender], actualAmount); TotalMintedActual[_GrowdropCount] = Sub(TotalMintedActual[_GrowdropCount], actualAmount); require(CToken[_GrowdropCount].redeemUnderlying(Amount)==0, "error in redeem"); require(Token[_GrowdropCount].transfer(msg.sender, Amount), "transfer token error"); TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])] = Sub(TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])], _toMinAmount); EventIdx += 1; emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], CTokenPerAddress[_GrowdropCount][msg.sender], 1, now); }
39,497
93
// Draw the final number, calculate reward in DEXToken per group, and make lottery claimable _lotteryId: lottery id _autoInjection: reinjects funds into next lottery (vs. withdrawing all) Callable by operator /
function drawFinalNumberAndMakeLotteryClaimable(uint256 _lotteryId, bool _autoInjection) external;
function drawFinalNumberAndMakeLotteryClaimable(uint256 _lotteryId, bool _autoInjection) external;
81,666
180
// Mainnet
IWETH internal constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IWETH internal constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
33,876
2
// Tranche wallet that holds ETH and allows to withdraw it in small portions /
contract EtherTrancheWallet is TrancheWallet { function EtherTrancheWallet( address _beneficiary, uint256 _tranchePeriodInDays, uint256 _trancheAmountPct ) TrancheWallet(_beneficiary, _tranchePeriodInDays, _trancheAmountPct) {} /**@dev Allows to receive ether */ function() payable {} /**@dev Returns current balance to be distributed to portions*/ function currentBalance() internal constant returns(uint256) { return this.balance; } /**@dev Transfers given amount of currency to the beneficiary */ function doTransfer(uint256 amount) internal { beneficiary.transfer(amount); } }
contract EtherTrancheWallet is TrancheWallet { function EtherTrancheWallet( address _beneficiary, uint256 _tranchePeriodInDays, uint256 _trancheAmountPct ) TrancheWallet(_beneficiary, _tranchePeriodInDays, _trancheAmountPct) {} /**@dev Allows to receive ether */ function() payable {} /**@dev Returns current balance to be distributed to portions*/ function currentBalance() internal constant returns(uint256) { return this.balance; } /**@dev Transfers given amount of currency to the beneficiary */ function doTransfer(uint256 amount) internal { beneficiary.transfer(amount); } }
51,043
26
// Set transaction fee/_txFee Transaction fee in tokens
function setTxFee(uint256 _txFee) external onlyOwner { txFee = _txFee; }
function setTxFee(uint256 _txFee) external onlyOwner { txFee = _txFee; }
34,722
115
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; }
if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; }
34,640
12
// return "Base DelegationShare implementation to inherit from for more complex implementations";
return "Mantle token DelegationShare implementation for submodules as an example";
return "Mantle token DelegationShare implementation for submodules as an example";
33,486
16
// Withdraw assets from this contract./See https:eips.ethereum.org/EIPS/eip-4626/assets The amount of assets to withdraw./receiver The address of account who will receive the assets./owner The address of user to withdraw from./ return shares The amount of pool shares burned.
function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares);
function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares);
9,121
123
// Enable incentives in aTokens and Variable Debt tokens
incentivesController.configureAssets(assets, emissions);
incentivesController.configureAssets(assets, emissions);
75,416
15
// Arbitrator Arbitrator abstract contract. When developing arbitrator contracts we need to: -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, may nbDisputes). -Define the functions for cost display (arbitrationCost and appealCost). -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling). /
interface IArbitrator { enum DisputeStatus {Waiting, Appealable, Solved} /** @dev To be emitted when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when a dispute can be appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealPossible(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes calldata _extraData) external payable returns(uint disputeID); /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function arbitrationCost(bytes calldata _extraData) external view returns(uint cost); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes calldata _extraData) external payable; /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function appealCost(uint _disputeID, bytes calldata _extraData) external view returns(uint cost); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0). * @param _disputeID ID of the dispute. * @return start The start of the period. * @return end The end of the period. */ function appealPeriod(uint _disputeID) external view returns(uint start, uint end); /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) external view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) external view returns(uint ruling); }
interface IArbitrator { enum DisputeStatus {Waiting, Appealable, Solved} /** @dev To be emitted when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when a dispute can be appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealPossible(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes calldata _extraData) external payable returns(uint disputeID); /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function arbitrationCost(bytes calldata _extraData) external view returns(uint cost); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes calldata _extraData) external payable; /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function appealCost(uint _disputeID, bytes calldata _extraData) external view returns(uint cost); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0). * @param _disputeID ID of the dispute. * @return start The start of the period. * @return end The end of the period. */ function appealPeriod(uint _disputeID) external view returns(uint start, uint end); /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) external view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) external view returns(uint ruling); }
25,186
50
// the fee taken in tokens from the pool
uint256 public feePct;
uint256 public feePct;
2,976
10
// Returns only items a user has listed /
function fetchItemsListed() public view returns (MarketItem[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { uint currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; }
function fetchItemsListed() public view returns (MarketItem[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { uint currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; }
35,132
79
// borrowing
vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrows );
vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrows );
17,571
312
// solium-disable-next-line security/no-block-members / Store that the orders have been settled.
orderStatus[_buyID] = OrderStatus.Settled; orderStatus[_sellID] = OrderStatus.Settled;
orderStatus[_buyID] = OrderStatus.Settled; orderStatus[_sellID] = OrderStatus.Settled;
33,927
156
// utility function to convert string to integer with precision consideration
function stringToUintNormalize(string s) internal pure returns (uint result) { uint p =2; bool precision=false; bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { if (precision) {p = p-1;}
function stringToUintNormalize(string s) internal pure returns (uint result) { uint p =2; bool precision=false; bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { if (precision) {p = p-1;}
12,252
28
// Handles creating auctions for sale and siring of hauntoos./This wrapper of ReverseAuction exists only so that users can create/auctions with only one transaction.
abstract contract HauntooAuction is HauntooBreeding { /// @dev The address of the ClockAuction contract that handles sales of Hauntoos. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; // @notice The auction contract variables are defined in HauntooBase to allow // us to refer to them in HauntooOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of hauntoos. // `siringAuction` refers to the auction for siring rights of hauntoos. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyOwner { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyOwner { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a hauntoo up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _hauntooId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If hauntoo is already on any auction, this will throw // because it will be owned by the auction contract. require(ownerOf(_hauntooId) == msg.sender); // Ensure the hauntoo is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the hauntoo IS allowed to be in a cooldown. require(!isPregnant(_hauntooId)); approve(address(saleAuction), _hauntooId); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the hauntoo. saleAuction.createAuction( _hauntooId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Put a hauntoo up for auction to be sire. /// Performs checks to ensure the hauntoo can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _hauntooId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If hauntoo is already on any auction, this will throw // because it will be owned by the auction contract. require(ownerOf(_hauntooId) == msg.sender); require(isReadyToBreed(_hauntooId)); approve(address(siringAuction), _hauntooId); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the hauntoo. siringAuction.createAuction( _hauntooId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(ownerOf(_matronId) == msg.sender); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bid{value: msg.value - autoBirthFee}(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } /// @dev Transfers the balance of the sale auction contract /// to the HauntooCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyOwner { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } }
abstract contract HauntooAuction is HauntooBreeding { /// @dev The address of the ClockAuction contract that handles sales of Hauntoos. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; // @notice The auction contract variables are defined in HauntooBase to allow // us to refer to them in HauntooOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of hauntoos. // `siringAuction` refers to the auction for siring rights of hauntoos. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyOwner { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyOwner { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a hauntoo up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _hauntooId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If hauntoo is already on any auction, this will throw // because it will be owned by the auction contract. require(ownerOf(_hauntooId) == msg.sender); // Ensure the hauntoo is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the hauntoo IS allowed to be in a cooldown. require(!isPregnant(_hauntooId)); approve(address(saleAuction), _hauntooId); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the hauntoo. saleAuction.createAuction( _hauntooId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Put a hauntoo up for auction to be sire. /// Performs checks to ensure the hauntoo can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _hauntooId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If hauntoo is already on any auction, this will throw // because it will be owned by the auction contract. require(ownerOf(_hauntooId) == msg.sender); require(isReadyToBreed(_hauntooId)); approve(address(siringAuction), _hauntooId); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the hauntoo. siringAuction.createAuction( _hauntooId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(ownerOf(_matronId) == msg.sender); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bid{value: msg.value - autoBirthFee}(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } /// @dev Transfers the balance of the sale auction contract /// to the HauntooCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyOwner { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } }
23,950
18
// updates an ETH price range at the given _index Requirements:Caller must be contract owner /
function setPriceRange( uint256 rangeType, uint8 _index, uint256 _low, uint256 _high, string memory _tokenURIUp, string memory _tokenURIDown
function setPriceRange( uint256 rangeType, uint8 _index, uint256 _low, uint256 _high, string memory _tokenURIUp, string memory _tokenURIDown
33,288
44
// https:github.com/OpenZeppelin/zeppelin-solidity/blob/1737555b0dda2974a0cd3a46bdfc3fb9f5b561b9/contracts/crowdsale/FinalizableCrowdsale.solL23
function finalize() onlyOwner { require(!isFinalized); Finalized(); isFinalized = true; }
function finalize() onlyOwner { require(!isFinalized); Finalized(); isFinalized = true; }
27,887
95
// xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_safeTransferFrom}. Emits a {TransferBatch} event. Requirements: - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return theacceptance magic value. /
function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address");
function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address");
46,940
7
// Interface that any module contract should implement Contract is abstract /
contract Module is IModule { address public factory; address public securityToken; bytes32 public constant FEE_ADMIN = "FEE_ADMIN"; IERC20 public polyToken; /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public { securityToken = _securityToken; factory = msg.sender; polyToken = IERC20(_polyAddress); } //Allows owner, factory or permissioned delegate modifier withPerm(bytes32 _perm) { bool isOwner = msg.sender == Ownable(securityToken).owner(); bool isFactory = msg.sender == factory; require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed"); _; } modifier onlyOwner { require(msg.sender == Ownable(securityToken).owner(), "Sender is not owner"); _; } modifier onlyFactory { require(msg.sender == factory, "Sender is not factory"); _; } modifier onlyFactoryOwner { require(msg.sender == Ownable(factory).owner(), "Sender is not factory owner"); _; } modifier onlyFactoryOrOwner { require((msg.sender == Ownable(securityToken).owner()) || (msg.sender == factory), "Sender is not factory or owner"); _; } /** * @notice used to withdraw the fee by the factory owner */ function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) { require(polyToken.transferFrom(securityToken, Ownable(factory).owner(), _amount), "Unable to take fee"); return true; } }
contract Module is IModule { address public factory; address public securityToken; bytes32 public constant FEE_ADMIN = "FEE_ADMIN"; IERC20 public polyToken; /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public { securityToken = _securityToken; factory = msg.sender; polyToken = IERC20(_polyAddress); } //Allows owner, factory or permissioned delegate modifier withPerm(bytes32 _perm) { bool isOwner = msg.sender == Ownable(securityToken).owner(); bool isFactory = msg.sender == factory; require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed"); _; } modifier onlyOwner { require(msg.sender == Ownable(securityToken).owner(), "Sender is not owner"); _; } modifier onlyFactory { require(msg.sender == factory, "Sender is not factory"); _; } modifier onlyFactoryOwner { require(msg.sender == Ownable(factory).owner(), "Sender is not factory owner"); _; } modifier onlyFactoryOrOwner { require((msg.sender == Ownable(securityToken).owner()) || (msg.sender == factory), "Sender is not factory or owner"); _; } /** * @notice used to withdraw the fee by the factory owner */ function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) { require(polyToken.transferFrom(securityToken, Ownable(factory).owner(), _amount), "Unable to take fee"); return true; } }
38,115
441
// If the last round was appealed and the given term is before the appeal confirmation end term, then the last round appeal can still be confirmed. Note that if the round being checked was already appealed and confirmed, it won't be the last round, thus it will be caught above by the first check and considered 'Ended'.
uint64 appealConfirmationEndTerm = appealConfirmationStartTerm.add(_config.appealConfirmTerms); if (_termId < appealConfirmationEndTerm) { return AdjudicationState.ConfirmingAppeal; }
uint64 appealConfirmationEndTerm = appealConfirmationStartTerm.add(_config.appealConfirmTerms); if (_termId < appealConfirmationEndTerm) { return AdjudicationState.ConfirmingAppeal; }
27,808
369
// Utility; converts an RLP-decoded node into our nice struct. _items RLP-decoded node to convert.return _node Node as a TrieNode struct. /
function _makeNode( Lib_RLPReader.RLPItem[] memory _items ) private pure returns ( TrieNode memory _node )
function _makeNode( Lib_RLPReader.RLPItem[] memory _items ) private pure returns ( TrieNode memory _node )
36,756
138
// Try to start monarchy game, reward upon success.
function startMonarchyGame(uint _index) public
function startMonarchyGame(uint _index) public
20,772
8
// abstract function
function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual; function _lzSend( uint16 _dstChainId, bytes memory _payload,
function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual; function _lzSend( uint16 _dstChainId, bytes memory _payload,
20,023
88
// Use the latest checkpoint
if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value;
if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value;
43,209
9
// Restore a pool after being liquidated. _pool The margin liquidity pool. /
function restoreLiquidatedPool(MarginLiquidityPoolInterface _pool) external nonReentrant { require(market.marginProtocol.getPositionsByPoolLength(_pool) == 0, "W2"); stoppedPools[_pool] = false; MarginFlowProtocol.TradingPair[] memory tradingPairs = market.config.getTradingPairs(); for (uint256 i = 0; i < tradingPairs.length; i++) { poolPairPrices[_pool][tradingPairs[i].base] = 0; poolPairPrices[_pool][tradingPairs[i].quote] = 0; poolBidSpreads[_pool][tradingPairs[i].base][tradingPairs[i].quote] = 0; poolAskSpreads[_pool][tradingPairs[i].base][tradingPairs[i].quote] = 0; } }
function restoreLiquidatedPool(MarginLiquidityPoolInterface _pool) external nonReentrant { require(market.marginProtocol.getPositionsByPoolLength(_pool) == 0, "W2"); stoppedPools[_pool] = false; MarginFlowProtocol.TradingPair[] memory tradingPairs = market.config.getTradingPairs(); for (uint256 i = 0; i < tradingPairs.length; i++) { poolPairPrices[_pool][tradingPairs[i].base] = 0; poolPairPrices[_pool][tradingPairs[i].quote] = 0; poolBidSpreads[_pool][tradingPairs[i].base][tradingPairs[i].quote] = 0; poolAskSpreads[_pool][tradingPairs[i].base][tradingPairs[i].quote] = 0; } }
12,447
33
// a big number is easier ; just find a solution that is smalleruint public_MAXIMUM_TARGET = 2224;bitcoin uses 224
uint public _MAXIMUM_TARGET = 2 ** 234;
uint public _MAXIMUM_TARGET = 2 ** 234;
23,261
3
// address tokenAddress;
bool isEntity;
bool isEntity;
4,238
5
// Variable validation. The endTradeBlock can't be smaller than the current one plus 220 (around 1 hour)
if(msg.value == 0 || tokenAmount == 0 || endTradeBlock <= block.number + 220){ throw; }
if(msg.value == 0 || tokenAmount == 0 || endTradeBlock <= block.number + 220){ throw; }
39,375
138
// Fraction of capital assigned to the connector (100% = 1e18)
uint256 public fraction;
uint256 public fraction;
9,984
185
// Address of Uniswap
address public uniswapAddr = address(0);
address public uniswapAddr = address(0);
48,064
31
// general functions
function WrapConversionRate(ConversionRateWrapperInterface _conversionRates, address _admin) public WrapperBase(PermissionGroups(address(_conversionRates)), _admin)
function WrapConversionRate(ConversionRateWrapperInterface _conversionRates, address _admin) public WrapperBase(PermissionGroups(address(_conversionRates)), _admin)
56,839
196
// Update the free memory pointer to allocate.
mstore(0x40, ptr)
mstore(0x40, ptr)
428
31
// Users borrow assets from the protocol to their own addressborrowAmount The amount of the underlying asset to borrow return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } if (getCash() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; vars.interestBalancePrior = borrowInterestBalancePriorInternal(borrower); vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = vars.accountBorrows.add(borrowAmount); vars.totalBorrowsNew = totalBorrows.add(borrowAmount); doTransferOut(borrower, borrowAmount); accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior); return 0; }
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } if (getCash() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; vars.interestBalancePrior = borrowInterestBalancePriorInternal(borrower); vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = vars.accountBorrows.add(borrowAmount); vars.totalBorrowsNew = totalBorrows.add(borrowAmount); doTransferOut(borrower, borrowAmount); accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew, vars.interestBalancePrior); return 0; }
15,999
493
// MarginEvents dYdX Contains events for the Margin contract. NOTE: Any Margin function libraries that use events will need to both define the event hereand copy the event into the library itself as libraries don&39;t support sharing events /
contract MarginEvents { // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a position was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); }
contract MarginEvents { // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a position was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); }
17,915
84
// overflow is desired, casting never truncates cumulative price is in (uq112x112 priceseconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112( uint224((price0Cumulative - price0CumulativeLast) / timeElapsed) ); price1Average = FixedPoint.uq112x112( uint224((price1Cumulative - price1CumulativeLast) / timeElapsed) ); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp;
price0Average = FixedPoint.uq112x112( uint224((price0Cumulative - price0CumulativeLast) / timeElapsed) ); price1Average = FixedPoint.uq112x112( uint224((price1Cumulative - price1CumulativeLast) / timeElapsed) ); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp;
3,140
352
// mint a vNFT
vnftDetails[_tokenIds.current()] = VNFTObj( supportedNfts[index].token, _id, nftType ); timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days); timeVnftBorn[_tokenIds.current()] = block.timestamp; super._mint(msg.sender, _tokenIds.current());
vnftDetails[_tokenIds.current()] = VNFTObj( supportedNfts[index].token, _id, nftType ); timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days); timeVnftBorn[_tokenIds.current()] = block.timestamp; super._mint(msg.sender, _tokenIds.current());
42,851
88
// Remove the element at `index` from an array and decrement its length.If `index` is the last index in the array, pops it from the array.Otherwise, stores the last element in the array at `index` and then pops the last element. /
function mremove(address[] memory arr, uint256 index) internal pure { uint256 len = arr.length; if (index != len - 1) { address last = arr[len - 1]; arr[index] = last; } assembly { mstore(arr, sub(len, 1)) } }
function mremove(address[] memory arr, uint256 index) internal pure { uint256 len = arr.length; if (index != len - 1) { address last = arr[len - 1]; arr[index] = last; } assembly { mstore(arr, sub(len, 1)) } }
45,305
26
// If `self` starts with `needle`, `needle` is removed from the beginning of `self`. Otherwise, `self` is unmodified. self The slice to operate on. needle The slice to search for.return `self` /
function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; }
function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; }
34,984
9
// forCar - which car the topup is for: validated earlier using 'validate' by ownerplateHash - hash of license platebyWhom - who made the topup payment: sha256 hash with format `<address>@<imparterTag>` where imparterTag is as per ledgers.jsnewZoneTimeoutsBytes - Unix time seconds when zone permits expire forCar:32 byte hex string first 4 bytes: zonaA, next zoneB, next zoneC Note: if this code looks convoluted in places, it's adjustments to avoid 'stack too deep' errors
function topup(address forCar, bytes32 plateHash, bytes32 byWhom,
function topup(address forCar, bytes32 plateHash, bytes32 byWhom,
42,835
548
// cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different type of asset token is listed in the future. It's possible if those tokens have a different precision dust may accrue but that is not relevant now.
int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
35,625
270
// Unfortunately, there is no simple way to verify that the _nativeToken address does not belong to the bridged token on the other side, since information about bridged tokens addresses is not transferred back. Therefore, owner account calling this function SHOULD manually verify on the other side of the bridge that nativeTokenAddress(_nativeToken) == address(0) && isTokenRegistered(_nativeToken) == false.
IBurnableMintableERC677Token(_bridgedToken).safeMint(address(this), 1); IBurnableMintableERC677Token(_bridgedToken).burn(1); _setTokenAddressPair(_nativeToken, _bridgedToken);
IBurnableMintableERC677Token(_bridgedToken).safeMint(address(this), 1); IBurnableMintableERC677Token(_bridgedToken).burn(1); _setTokenAddressPair(_nativeToken, _bridgedToken);
8,991
60
// For querying founder cut which is left in the contract by `purchase`_price The token actual price/
function calculateFounderCut (uint256 _price) public pure returns (uint256 _founderCut) { return _price.mul(1).div(100); }
function calculateFounderCut (uint256 _price) public pure returns (uint256 _founderCut) { return _price.mul(1).div(100); }
36,191
198
// Safe agro transfer function, just in case if rounding error causes pool to not have enough AGROs.
function safeAgroTransfer(address _to, uint256 _amount) internal { uint256 agroBal = agro.balanceOf(address(this)); if (_amount > agroBal) { agro.transfer(_to, agroBal); } else { agro.transfer(_to, _amount); } }
function safeAgroTransfer(address _to, uint256 _amount) internal { uint256 agroBal = agro.balanceOf(address(this)); if (_amount > agroBal) { agro.transfer(_to, agroBal); } else { agro.transfer(_to, _amount); } }
39,879
6
// mapping auctionId -> array of bid Ids
mapping(bytes32 => bytes32[]) auctionBidIdsRegistry;
mapping(bytes32 => bytes32[]) auctionBidIdsRegistry;
31,253
161
// MIP39c2-SP6: MakerDAO Shop Core Unit, MDS-001 Hash: seth keccak -- "$(wget https:raw.githubusercontent.com/makerdao/mips/85fc70a7793831d3f7dd120d447a03e4ebfb9e2f/MIP39/MIP39c2-Subproposals/MIP39c2-SP6.md -q -O - 2> /dev/null)"
string constant public MIP39c2SP6 = "0x2f0189cf1b3e6ca83a4f2b9ebc77b23f39dcb9606f1087f8e184d6a28ef1289a";
string constant public MIP39c2SP6 = "0x2f0189cf1b3e6ca83a4f2b9ebc77b23f39dcb9606f1087f8e184d6a28ef1289a";
34,420
1
// CONSTRUCTOR
function _setImplementation(address newImplementation, bytes memory data) internal
function _setImplementation(address newImplementation, bytes memory data) internal
16,520
83
// Decrease the debt and collateral of the current Trove according to the LUSD lot and corresponding ETH to send
uint newDebt = (Troves[_borrower].debt).sub(singleRedemption.LUSDLot); uint newColl = (Troves[_borrower].coll).sub(singleRedemption.ETHLot); if (newDebt == LUSD_GAS_COMPENSATION) {
uint newDebt = (Troves[_borrower].debt).sub(singleRedemption.LUSDLot); uint newColl = (Troves[_borrower].coll).sub(singleRedemption.ETHLot); if (newDebt == LUSD_GAS_COMPENSATION) {
62,615
15
// If its a zero address being passed for the strategy we are removing the default strategy
if (_strategy != address(0)) {
if (_strategy != address(0)) {
41,417
7
// Swap rewards tokens for equal value of LP tokens
(uint256 _amountToken0, uint256 _amountToken1) = UniswapRouter .swapTokensForEqualAmounts( swapRouter, _tokenBalances, _paths, rewardsTokens, _minAmountsOut, _deadline );
(uint256 _amountToken0, uint256 _amountToken1) = UniswapRouter .swapTokensForEqualAmounts( swapRouter, _tokenBalances, _paths, rewardsTokens, _minAmountsOut, _deadline );
44,178
7
// `fromBlock` is the block number that the value was generatedsuper.mint(_to, _amount); from
uint128 fromBlock;
uint128 fromBlock;
10,979
16
// approve PancakeSwap to spend LP tokens on behalf of this contract
pancakePair.approve(address(pancakeRouter), liquidity);
pancakePair.approve(address(pancakeRouter), liquidity);
29,454
125
// Accumulator for delayed inbox; tail represents hash of the current state; each element represents the inclusion of a new message.
bytes32[] public override inboxAccs;
bytes32[] public override inboxAccs;
47,637
3
// symbol
string symbol;
string symbol;
15,058
115
// Goals: 1. deposits eth into the vault2. gives the holder a claim on the vault for later withdrawal
(uint collateralToLock, uint fee, uint tokensToIssue) = calculateIssuanceAmount(msg.value); bytes memory proxyCall = abi.encodeWithSignature( "lockETH(address,address,uint256)", makerManager, ethGemJoin, cdpId);
(uint collateralToLock, uint fee, uint tokensToIssue) = calculateIssuanceAmount(msg.value); bytes memory proxyCall = abi.encodeWithSignature( "lockETH(address,address,uint256)", makerManager, ethGemJoin, cdpId);
9,959
4
// Allow deposits of ETH
receive() external payable {}
receive() external payable {}
637
165
// Nonces for each VOR key from which randomness has been requested. Must stay in sync with VORCoordinator[_keyHash][this]/ keyHash // nonce // _vorCoordinator address of VORCoordinator contract _xfund address of xFUND token contract /
constructor(address _vorCoordinator, address _xfund) internal { vorCoordinator = _vorCoordinator; xFUNDAddress = _xfund; xFUND = IERC20_Ex(_xfund); }
constructor(address _vorCoordinator, address _xfund) internal { vorCoordinator = _vorCoordinator; xFUNDAddress = _xfund; xFUND = IERC20_Ex(_xfund); }
64,254
6
// Increase poll for given term _termName name of term _value knowledge presents given term _count how much shares given for increase Given knownledge should be delegated to me /
function pollUp(string _termName, Knowledge _value, uint _count) { // So throw when knowledge is not my if (_value.owner() != address(this)) return; // Poll up given term name var voter = msg.sender; var term = termOf[_termName]; term.up(voter, _value, shares, _count); // Update thesaurus term update(_termName); }
function pollUp(string _termName, Knowledge _value, uint _count) { // So throw when knowledge is not my if (_value.owner() != address(this)) return; // Poll up given term name var voter = msg.sender; var term = termOf[_termName]; term.up(voter, _value, shares, _count); // Update thesaurus term update(_termName); }
8,909
161
// Wrappers over Solidity's arithmetic operations. NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compilernow has built in overflow checking. /
library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
1,407
15
// Function to mint tokens_to The address that will receive the minted tokens._amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); if (balances[_to] == 0) { holders.push(_to); } balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; }
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); if (balances[_to] == 0) { holders.push(_to); } balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; }
32,114
16
// Owner address to Vault Id
mapping(address => uint256) public userToVault;
mapping(address => uint256) public userToVault;
49,474
6
// Approved an address to sign order-opening and withdrawals./_broker The address of the broker.
function registerBroker(address _broker) external onlyOwner { require(!brokerRegistered[_broker], "already registered"); brokerRegistered[_broker] = true; emit LogBrokerRegistered(_broker); }
function registerBroker(address _broker) external onlyOwner { require(!brokerRegistered[_broker], "already registered"); brokerRegistered[_broker] = true; emit LogBrokerRegistered(_broker); }
8,014
50
// It allows owner to set the cToken address_cToken : new cToken address /
function setCToken(address _cToken)
function setCToken(address _cToken)
42,040
6
// KIP17 Non-Fungible Pausable token KIP17 modified with pausable transfers. /
contract KIP17Pausable is KIP13, KIP17, Pausable { /* * bytes4(keccak256('paused()')) == 0x5c975abb * bytes4(keccak256('pause()')) == 0x8456cb59 * bytes4(keccak256('unpause()')) == 0x3f4ba83a * bytes4(keccak256('isPauser(address)')) == 0x46fbf68e * bytes4(keccak256('addPauser(address)')) == 0x82dc1ec4 * bytes4(keccak256('renouncePauser()')) == 0x6ef8d66d * * => 0x5c975abb ^ 0x8456cb59 ^ 0x3f4ba83a ^ 0x46fbf68e ^ 0x82dc1ec4 ^ 0x6ef8d66d == 0x4d5507ff */ bytes4 private constant _INTERFACE_ID_KIP17_PAUSABLE = 0x4d5507ff; /** * @dev Constructor function. */ constructor() public { // register the supported interface to conform to KIP17Pausable via KIP13 _registerInterface(_INTERFACE_ID_KIP17_PAUSABLE); } function approve(address to, uint256 tokenId) public whenNotPaused { super.approve(to, tokenId); } function setApprovalForAll(address to, bool approved) public whenNotPaused { super.setApprovalForAll(to, approved); } function transferFrom( address from, address to, uint256 tokenId ) public whenNotPaused { super.transferFrom(from, to, tokenId); } }
contract KIP17Pausable is KIP13, KIP17, Pausable { /* * bytes4(keccak256('paused()')) == 0x5c975abb * bytes4(keccak256('pause()')) == 0x8456cb59 * bytes4(keccak256('unpause()')) == 0x3f4ba83a * bytes4(keccak256('isPauser(address)')) == 0x46fbf68e * bytes4(keccak256('addPauser(address)')) == 0x82dc1ec4 * bytes4(keccak256('renouncePauser()')) == 0x6ef8d66d * * => 0x5c975abb ^ 0x8456cb59 ^ 0x3f4ba83a ^ 0x46fbf68e ^ 0x82dc1ec4 ^ 0x6ef8d66d == 0x4d5507ff */ bytes4 private constant _INTERFACE_ID_KIP17_PAUSABLE = 0x4d5507ff; /** * @dev Constructor function. */ constructor() public { // register the supported interface to conform to KIP17Pausable via KIP13 _registerInterface(_INTERFACE_ID_KIP17_PAUSABLE); } function approve(address to, uint256 tokenId) public whenNotPaused { super.approve(to, tokenId); } function setApprovalForAll(address to, bool approved) public whenNotPaused { super.setApprovalForAll(to, approved); } function transferFrom( address from, address to, uint256 tokenId ) public whenNotPaused { super.transferFrom(from, to, tokenId); } }
43,402
2
// a call to {approve}. `value` is the new allowance. /
event Approval(address indexed owner, address indexed spender, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
24,180
291
// event emitted when a user has unstaked a token
event Unstaked(address owner, uint256 amount);
event Unstaked(address owner, uint256 amount);
61,643
71
// define midtoken address, ETH -> WETH address
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]); uint256 curTotalWeight = totalWeight[i-1]; for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) { (address pool, address adapter, uint256 mixPara) = abi.decode(swapSequence[j], (address, address, uint256)); uint256 direction = mixPara >> 17; uint256 weight = (0xffff & mixPara) >> 9; uint256 poolEdition = (0xff & mixPara); if(assetFrom[i-1] == address(this)) {
uint256 curTotalAmount = IERC20(midToken[i]).tokenBalanceOf(assetFrom[i-1]); uint256 curTotalWeight = totalWeight[i-1]; for(uint256 j = splitNumber[i-1]; j < splitNumber[i]; j++) { (address pool, address adapter, uint256 mixPara) = abi.decode(swapSequence[j], (address, address, uint256)); uint256 direction = mixPara >> 17; uint256 weight = (0xffff & mixPara) >> 9; uint256 poolEdition = (0xff & mixPara); if(assetFrom[i-1] == address(this)) {
15,899
0
// by reserving a mint an user captures a new token id
mapping(uint256 => address) public reservations;
mapping(uint256 => address) public reservations;
27,006
107
// Checks if a transfer can occur between the from/to addresses and MUST throw when the check fails.initiator The address initiating the transfer.from The address of the senderto The address of the receivertoKind The kind of the to addresstokens The number of tokens being transferred.store The Storage contract /
function check(address initiator, address from, address to, uint8 toKind, uint256 tokens, Storage store) external;
function check(address initiator, address from, address to, uint8 toKind, uint256 tokens, Storage store) external;
42,418
99
// If `account` had not been already granted `role`, emits a {RoleGranted}event. Note that unlike {grantRole}, this function doesn't perform anychecks on the calling account. [WARNING]====This function should only be called from the constructor when settingup the initial roles for the system. Using this function in any other way is effectively circumventing the adminsystem imposed by {AccessControl}.==== /
function _setupRole(address role, address account) internal virtual { _grantRole(role, account); }
function _setupRole(address role, address account) internal virtual { _grantRole(role, account); }
6,226
48
// record the currentInterval so the above check is useful
allocations[_index].currentInterval = currentInterval;
allocations[_index].currentInterval = currentInterval;
29,446
85
// Grab the index into the _from owner's ownedTokens array
uint32 fromIndex = tokenToOwnedTokensIndex[uint32(_tokenId)];
uint32 fromIndex = tokenToOwnedTokensIndex[uint32(_tokenId)];
23,661
142
// Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)_kernel Reference to organization kernel for the app_appId Identifier for app_initializePayload Payload for call to be made after setup to initialize/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first
6,234
14
// Allows to add a new owner. Transaction has to be sent by wallet./owner Address of new owner.
function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required)
function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required)
8,507
19
// a little number
uint public _MINIMUM_TARGET = 2**16;
uint public _MINIMUM_TARGET = 2**16;
5,563
27
// Transfer Function /
{ return _transferFrom(msg.sender, recipient, amount); }
{ return _transferFrom(msg.sender, recipient, amount); }
3,582
185
// Allows a Module to execute a Safe transaction without any further confirmations./to Destination address of module transaction./value Ether value of module transaction./data Data payload of module transaction./operation Operation type of module transaction.
function execTransactionFromModule( address to, uint256 value, bytes memory data, Enum.Operation operation
function execTransactionFromModule( address to, uint256 value, bytes memory data, Enum.Operation operation
26,718