Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
12
// Update the last execution time to now when a task is executed./_taskCreator The creator of the task./_executionData The execution data of the task.
function onExec(address _taskCreator, bytes calldata _executionData) external override onlyFuruGelato returns (bool)
function onExec(address _taskCreator, bytes calldata _executionData) external override onlyFuruGelato returns (bool)
2,719
13
// Emits when the account owner increases CA's debt
event IncreaseBorrowedAmount(address indexed borrower, uint256 amount);
event IncreaseBorrowedAmount(address indexed borrower, uint256 amount);
28,714
84
// The current validator's signatures
uint8[] memory _v, bytes32[] memory _r, bytes32[] memory _s,
uint8[] memory _v, bytes32[] memory _r, bytes32[] memory _s,
21,724
19
// ´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.:// INTERNAL FUNCTIONS //.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•//Initializes the owner directly without authorization guard./ This function must be called upon initialization,/ regardless of whether the contract is upgradeable or not./ This is to enable generalization to both regular and upgradeable contracts,/ and to save gas in case the initial owner is not the caller./ For performance reasons, this function will not check if there/ is an existing owner.
function _initializeOwner(address newOwner) internal virtual { assembly { // Clean the upper 96 bits. newOwner := shr(96, shl(96, newOwner)) // Store the new value. sstore(not(_OWNER_SLOT_NOT), newOwner) // Emit the {OwnershipTransferred} event. log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner) } }
function _initializeOwner(address newOwner) internal virtual { assembly { // Clean the upper 96 bits. newOwner := shr(96, shl(96, newOwner)) // Store the new value. sstore(not(_OWNER_SLOT_NOT), newOwner) // Emit the {OwnershipTransferred} event. log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner) } }
5,040
7
// couldnt get the below to work so used call() :shrug: payable(msg.sender).transfer(msg.value - totalPrice);
(bool sent, bytes memory data) = msg.sender.call{value: msg.value - totalPrice}("");
(bool sent, bytes memory data) = msg.sender.call{value: msg.value - totalPrice}("");
41,140
57
// Approve tokens for use in Strategy Should use modifier `onlyOwner` to avoid griefing /
function setAllowances() public virtual;
function setAllowances() public virtual;
32,165
58
// Get the minimum fee required for all orders /
function getMinFee() external view returns (uint128) { return LibStorage.getConfigStorage().minFee; }
function getMinFee() external view returns (uint128) { return LibStorage.getConfigStorage().minFee; }
66,994
144
// make sure the msg.sender has enough synthetic fuel to transfer
if (balances[msg.sender][nativeBip32X_type] >= _value) { autoUpgradeEnabled[msg.sender] = true;
if (balances[msg.sender][nativeBip32X_type] >= _value) { autoUpgradeEnabled[msg.sender] = true;
21,865
31
// Calculate the result.
bytes32 n = keccak256( abi.encodePacked(randomNumber, blockhash(betPlacedOnBlock)) ); uint8 spinNumber = uint8(uint256(n) % 38);
bytes32 n = keccak256( abi.encodePacked(randomNumber, blockhash(betPlacedOnBlock)) ); uint8 spinNumber = uint8(uint256(n) % 38);
37,044
24
// 4 Gets the DAI price as function suggests
function getDAIPrice() constant returns (uint256) { // Creating OrFeed Instance & calling ORFEED Alpha Smart Contract OrFeedInterface orfeed = OrFeedInterface(0x8316b082621cfedab95bf4a44a1d4b64a6ffc336); // Get the exchange rate for eth to usd and then amount 4.1 uint256 ethPrice = orfeed.getExchangeRate("ETH", "USD", "", 100000000); return ethPrice; }
function getDAIPrice() constant returns (uint256) { // Creating OrFeed Instance & calling ORFEED Alpha Smart Contract OrFeedInterface orfeed = OrFeedInterface(0x8316b082621cfedab95bf4a44a1d4b64a6ffc336); // Get the exchange rate for eth to usd and then amount 4.1 uint256 ethPrice = orfeed.getExchangeRate("ETH", "USD", "", 100000000); return ethPrice; }
5,622
160
// Determine the next allocation to rebalance into. If the dollar value of the two collateral sets is morethan 5x different from each other then create a new collateral set. If currently riskOn then a newstable collateral set is created, if !riskOn then a new risk collateral set is created. _riskAssetPriceCurrent risk asset price as found on oraclereturn addressThe address of the proposed nextSetreturn uint256The USD value of current Setreturn uint256The USD value of next Set /
function determineNewAllocation( uint256 _riskAssetPrice ) internal returns (address, uint256, uint256)
function determineNewAllocation( uint256 _riskAssetPrice ) internal returns (address, uint256, uint256)
18,173
88
// Get ntoken address from token address/tokenAddress Destination token address/ return ntoken address
function getNTokenAddress(address tokenAddress) external view returns (address);
function getNTokenAddress(address tokenAddress) external view returns (address);
36,760
29
// Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling therevert reason using the provided one. _Available since v4.3._ /
function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage
function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage
16,178
51
// return reference hash
return dealAffiliateReferenceHash[_dealIndex][_affiliateAddress];
return dealAffiliateReferenceHash[_dealIndex][_affiliateAddress];
47,696
98
// Set borrower weight to pending borrower weight
if (borrowWeight != pendingBorrowWeight) { borrowerWeights[borrowers[i]] .borrowerWeight = pendingBorrowWeight;
if (borrowWeight != pendingBorrowWeight) { borrowerWeights[borrowers[i]] .borrowerWeight = pendingBorrowWeight;
8,346
375
// Return an identical view with a different type. memView The view _newTypeThe new typereturnnewView - The new view with the specified type /
function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } }
function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } }
14,055
0
// keccak256("MANAGER_ROLE")
bytes32 public constant MANAGER_ROLE = 0x241ecf16d79d0f8dbfb92cbc07fe17840425976cf0667f022fe9877caa831b08;
bytes32 public constant MANAGER_ROLE = 0x241ecf16d79d0f8dbfb92cbc07fe17840425976cf0667f022fe9877caa831b08;
48,542
26
// Returns the integer division of two unsigned integers. Reverts with custom message ondivision 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 Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements:- The divisor cannot be zero. /
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
7,588
32
// Fallback for distributeTokens in case of gas overflow. Distributes PNG tokens to a single pool.distibuteTokens() must still be called once to reset the contract state before calling vestAllocation. Args:pairIndex: index of pair to distribute tokens to, AVAX pairs come first in the ordering /
function distributeTokensSinglePool(uint pairIndex) external nonReentrant { require(readyToDistribute, 'LiquidityPoolManager::distributeTokensSinglePool: Previous returns not allocated. Call calculateReturns()'); require(pairIndex < numPools, 'LiquidityPoolManager::distributeTokensSinglePool: Index out of bounds'); address stakeContract; if (pairIndex < avaxPairs.length()) { stakeContract = stakes[avaxPairs.at(pairIndex)]; } else { stakeContract = stakes[pngPairs.at(pairIndex - avaxPairs.length())]; } uint rewardTokens = distribution[pairIndex]; if (rewardTokens > 0) { distribution[pairIndex] = 0; require(IPNG(png).transfer(stakeContract, rewardTokens), 'LiquidityPoolManager::distributeTokens: Transfer failed'); StakingRewards(stakeContract).notifyRewardAmount(rewardTokens); } }
function distributeTokensSinglePool(uint pairIndex) external nonReentrant { require(readyToDistribute, 'LiquidityPoolManager::distributeTokensSinglePool: Previous returns not allocated. Call calculateReturns()'); require(pairIndex < numPools, 'LiquidityPoolManager::distributeTokensSinglePool: Index out of bounds'); address stakeContract; if (pairIndex < avaxPairs.length()) { stakeContract = stakes[avaxPairs.at(pairIndex)]; } else { stakeContract = stakes[pngPairs.at(pairIndex - avaxPairs.length())]; } uint rewardTokens = distribution[pairIndex]; if (rewardTokens > 0) { distribution[pairIndex] = 0; require(IPNG(png).transfer(stakeContract, rewardTokens), 'LiquidityPoolManager::distributeTokens: Transfer failed'); StakingRewards(stakeContract).notifyRewardAmount(rewardTokens); } }
36,890
217
// the tick range of the position
int24 tickLower; int24 tickUpper;
int24 tickLower; int24 tickUpper;
30,882
75
// Update the appropriate fields - ownerID, consumerID, itemState
items[_upc].ownerID = msg.sender; items[_upc].consumerID = msg.sender; items[_upc].itemState = State.Purchased;
items[_upc].ownerID = msg.sender; items[_upc].consumerID = msg.sender; items[_upc].itemState = State.Purchased;
43,741
2
// Returns the current quorum numerator. See {quorumDenominator}. /
function quorumNumerator() public view virtual returns (uint256) { return _quorumNumeratorHistory._checkpoints.length == 0 ? _quorumNumerator : _quorumNumeratorHistory.latest(); }
function quorumNumerator() public view virtual returns (uint256) { return _quorumNumeratorHistory._checkpoints.length == 0 ? _quorumNumerator : _quorumNumeratorHistory.latest(); }
17,131
12
// Returns the beneficiary. /
function beneficiary() external view returns (address) { return _beneficiary; }
function beneficiary() external view returns (address) { return _beneficiary; }
11,890
60
// Validator contract. Nikola MadjarevicDate created: 3.5.21.Github: madjarevicn /
contract Validator is Initializable, ChainportMiddleware { address public signatoryAddress; // Set initial signatory address and Chainport congress function initialize( address _signatoryAddress, address _chainportCongress, address _maintainersRegistry ) public initializer { signatoryAddress = _signatoryAddress; setCongressAndMaintainers(_chainportCongress, _maintainersRegistry); } // Set / change signatory address function setSignatoryAddress( address _signatoryAddress ) public onlyChainportCongress { require(_signatoryAddress != address(0)); signatoryAddress = _signatoryAddress; } /** * @notice Function to verify withdraw parameters and if signatory signed message * @param signedMessage is the message to verify * @param beneficiary is the address of user for who we signed message * @param token is the address of the token being withdrawn * @param amount is the amount of tokens user is attempting to withdraw */ function verifyWithdraw( bytes memory signedMessage, address token, uint256 amount, address beneficiary, uint256 nonce ) external view returns (bool) { address messageSigner = recoverSignature(signedMessage, beneficiary, token, amount, nonce); return messageSigner == signatoryAddress; } /** * @notice Function to can check who signed the message * @param signedMessage is the message to verify * @param beneficiary is the address of user for who we signed message * @param token is the address of the token being withdrawn * @param amount is the amount of tokens user is attempting to withdraw */ function recoverSignature( bytes memory signedMessage, address beneficiary, address token, uint256 amount, uint256 nonce ) public pure returns (address) { // Generate hash bytes32 hash = keccak256( abi.encodePacked( keccak256(abi.encodePacked('bytes binding user withdrawal')), keccak256(abi.encodePacked(beneficiary, token, amount, nonce)) ) ); // Recover signer message from signature return recoverHash(hash,signedMessage,0); } /** * @notice Generalized recover sig for hash * @dev Built for easily integrating onwards with new contracts, * since the message can be hashed on the another contract also. * @param hash is hash generated by encoding and hashing data * @param signature is the signature which should be verified. */ function recoverSigFromHash(bytes32 hash, bytes memory signature) public view returns (bool) { address signer = recoverHash(hash, signature, 0); return signer == signatoryAddress; } function recoverHash( bytes32 hash, bytes memory sig, uint idx ) public pure returns (address) { // same as recoverHash in utils/sign.js // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. require (sig.length >= 65+idx, 'bad signature length'); idx += 32; bytes32 r; assembly { r := mload(add(sig, idx)) } idx += 32; bytes32 s; assembly { s := mload(add(sig, idx)) } idx += 1; uint8 v; assembly { v := mload(add(sig, idx)) } if (v >= 32) { // handle case when signature was made with ethereum web3.eth.sign or getSign which is for signing ethereum transactions v -= 32; bytes memory prefix = "\x19Ethereum Signed Message:\n32"; // 32 is the number of bytes in the following hash hash = keccak256(abi.encodePacked(prefix, hash)); } if (v <= 1) v += 27; require(v==27 || v==28,'bad sig v'); //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol#L57 require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, 'bad sig s'); return ecrecover(hash, v, r, s); } }
contract Validator is Initializable, ChainportMiddleware { address public signatoryAddress; // Set initial signatory address and Chainport congress function initialize( address _signatoryAddress, address _chainportCongress, address _maintainersRegistry ) public initializer { signatoryAddress = _signatoryAddress; setCongressAndMaintainers(_chainportCongress, _maintainersRegistry); } // Set / change signatory address function setSignatoryAddress( address _signatoryAddress ) public onlyChainportCongress { require(_signatoryAddress != address(0)); signatoryAddress = _signatoryAddress; } /** * @notice Function to verify withdraw parameters and if signatory signed message * @param signedMessage is the message to verify * @param beneficiary is the address of user for who we signed message * @param token is the address of the token being withdrawn * @param amount is the amount of tokens user is attempting to withdraw */ function verifyWithdraw( bytes memory signedMessage, address token, uint256 amount, address beneficiary, uint256 nonce ) external view returns (bool) { address messageSigner = recoverSignature(signedMessage, beneficiary, token, amount, nonce); return messageSigner == signatoryAddress; } /** * @notice Function to can check who signed the message * @param signedMessage is the message to verify * @param beneficiary is the address of user for who we signed message * @param token is the address of the token being withdrawn * @param amount is the amount of tokens user is attempting to withdraw */ function recoverSignature( bytes memory signedMessage, address beneficiary, address token, uint256 amount, uint256 nonce ) public pure returns (address) { // Generate hash bytes32 hash = keccak256( abi.encodePacked( keccak256(abi.encodePacked('bytes binding user withdrawal')), keccak256(abi.encodePacked(beneficiary, token, amount, nonce)) ) ); // Recover signer message from signature return recoverHash(hash,signedMessage,0); } /** * @notice Generalized recover sig for hash * @dev Built for easily integrating onwards with new contracts, * since the message can be hashed on the another contract also. * @param hash is hash generated by encoding and hashing data * @param signature is the signature which should be verified. */ function recoverSigFromHash(bytes32 hash, bytes memory signature) public view returns (bool) { address signer = recoverHash(hash, signature, 0); return signer == signatoryAddress; } function recoverHash( bytes32 hash, bytes memory sig, uint idx ) public pure returns (address) { // same as recoverHash in utils/sign.js // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. require (sig.length >= 65+idx, 'bad signature length'); idx += 32; bytes32 r; assembly { r := mload(add(sig, idx)) } idx += 32; bytes32 s; assembly { s := mload(add(sig, idx)) } idx += 1; uint8 v; assembly { v := mload(add(sig, idx)) } if (v >= 32) { // handle case when signature was made with ethereum web3.eth.sign or getSign which is for signing ethereum transactions v -= 32; bytes memory prefix = "\x19Ethereum Signed Message:\n32"; // 32 is the number of bytes in the following hash hash = keccak256(abi.encodePacked(prefix, hash)); } if (v <= 1) v += 27; require(v==27 || v==28,'bad sig v'); //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol#L57 require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, 'bad sig s'); return ecrecover(hash, v, r, s); } }
38,431
211
// 0 = DEV, 1 = PRESALE, 2 = PUBLIC, 3 = CLOSED
uint8 private mintPhase = 0; bool private devMintLocked = false;
uint8 private mintPhase = 0; bool private devMintLocked = false;
17,415
51
// Event fired when admins are modified
event SetAdmin(address _caller, address _admin, bool _allowed);
event SetAdmin(address _caller, address _admin, bool _allowed);
80,850
0
// CRITERIA is declared as a public bytes8 type in ID.sol
CRITERIA = _fromTokenURIToBytes8(_CRITERIA);
CRITERIA = _fromTokenURIToBytes8(_CRITERIA);
31,934
946
// Issues new asset token on the platform.// Tokens issued with this call go straight to contract owner./ Each symbol can be issued only once, and only by contract owner.//_symbol asset symbol./_value amount of tokens to issue immediately./_name name of the asset./_description description for the asset./_baseUnit number of decimals./_isReissuable dynamic or fixed supply./_blockNumber block number from which asset can be used.// return success.
function issueAsset( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber ) public
function issueAsset( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber ) public
36,388
0
// |/|
struct RefinanceVariables { bool isFromStETHBasedProtocol; bool isToStETHBasedProtocol; uint256 spellIndex; uint256 spellsLength; string[] targets; bytes[] calldatas; uint256 withdrawIdToPaybackFlashloan; }
struct RefinanceVariables { bool isFromStETHBasedProtocol; bool isToStETHBasedProtocol; uint256 spellIndex; uint256 spellsLength; string[] targets; bytes[] calldatas; uint256 withdrawIdToPaybackFlashloan; }
12,760
113
// capable of vetoing DAO votes or optimistic timelocks
bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN");
bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN");
48,406
8
// 0 - Initial State1 - Contribution State2 - Final State
uint256 public state; mapping (address => bool) internal contributionKYC; mapping (address => uint256) internal originalContributed; mapping (address => uint256) internal adjustedContributed; uint256 public amountRaised; //Value strictly increases and tracks total raised. uint256 public adjustedRaised; uint256 public currentRate;
uint256 public state; mapping (address => bool) internal contributionKYC; mapping (address => uint256) internal originalContributed; mapping (address => uint256) internal adjustedContributed; uint256 public amountRaised; //Value strictly increases and tracks total raised. uint256 public adjustedRaised; uint256 public currentRate;
12,423
286
// See {ERC721Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`. /
function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); }
function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); }
4,532
37
// When creating new films _from is 0x0, but we can&39;t account that address.
if (_from != address(0)) { ownershipTokenCount[_from]--;
if (_from != address(0)) { ownershipTokenCount[_from]--;
20,871
51
// Create a Borrow, deploy a Loan Pool and delegate voting power_delegatee Address to delegate the voting power to_amount Amount of underlying to borrow_feeAmount Amount of fee to pay to start the loan return uint : new PalLoanToken Id/
function borrow(address _delegatee, uint _amount, uint _feeAmount) public virtual override nonReentrant returns(uint){ //Need the pool to have enough liquidity, and the interests to be up to date require(_amount < underlyingBalance(), Errors.INSUFFICIENT_CASH); require(_delegatee != address(0), Errors.ZERO_ADDRESS); require(_amount > 0, Errors.ZERO_BORROW); require(_feeAmount >= minBorrowFees(_amount), Errors.BORROW_INSUFFICIENT_FEES); require(_updateInterest()); address _borrower = msg.sender; //Update Total Borrowed totalBorrowed = totalBorrowed.add(_amount); IPalLoan _newLoan = IPalLoan(Clones.clone(delegator)); //Send the borrowed amount of underlying tokens to the Loan underlying.safeTransfer(address(_newLoan), _amount); //And transfer the fees from the Borrower to the Loan underlying.safeTransferFrom(_borrower, address(_newLoan), _feeAmount); //Start the Loan (and delegate voting power) require(_newLoan.initiate( address(this), _borrower, address(underlying), _delegatee, _amount, _feeAmount ), Errors.FAIL_LOAN_INITIATE); //Add the new Loan to mappings loans.push(address(_newLoan)); //Mint the palLoanToken linked to this new Loan uint256 _newTokenId = palLoanToken.mint(_borrower, address(this), address(_newLoan)); //New Borrow struct for this Loan loanToBorrow[address(_newLoan)] = Borrow( _newTokenId, _delegatee, address(_newLoan), _amount, address(underlying), _feeAmount, 0, borrowIndex, block.number, 0, false, false ); //Check the borrow succeeded require( controller.borrowVerify(address(this), _borrower, _delegatee, _amount, _feeAmount, address(_newLoan)), Errors.FAIL_BORROW ); //Emit the NewLoan Event emit NewLoan( _borrower, _delegatee, address(underlying), _amount, address(this), address(_newLoan), _newTokenId, block.number ); //Return the PalLoanToken Id return _newTokenId; }
function borrow(address _delegatee, uint _amount, uint _feeAmount) public virtual override nonReentrant returns(uint){ //Need the pool to have enough liquidity, and the interests to be up to date require(_amount < underlyingBalance(), Errors.INSUFFICIENT_CASH); require(_delegatee != address(0), Errors.ZERO_ADDRESS); require(_amount > 0, Errors.ZERO_BORROW); require(_feeAmount >= minBorrowFees(_amount), Errors.BORROW_INSUFFICIENT_FEES); require(_updateInterest()); address _borrower = msg.sender; //Update Total Borrowed totalBorrowed = totalBorrowed.add(_amount); IPalLoan _newLoan = IPalLoan(Clones.clone(delegator)); //Send the borrowed amount of underlying tokens to the Loan underlying.safeTransfer(address(_newLoan), _amount); //And transfer the fees from the Borrower to the Loan underlying.safeTransferFrom(_borrower, address(_newLoan), _feeAmount); //Start the Loan (and delegate voting power) require(_newLoan.initiate( address(this), _borrower, address(underlying), _delegatee, _amount, _feeAmount ), Errors.FAIL_LOAN_INITIATE); //Add the new Loan to mappings loans.push(address(_newLoan)); //Mint the palLoanToken linked to this new Loan uint256 _newTokenId = palLoanToken.mint(_borrower, address(this), address(_newLoan)); //New Borrow struct for this Loan loanToBorrow[address(_newLoan)] = Borrow( _newTokenId, _delegatee, address(_newLoan), _amount, address(underlying), _feeAmount, 0, borrowIndex, block.number, 0, false, false ); //Check the borrow succeeded require( controller.borrowVerify(address(this), _borrower, _delegatee, _amount, _feeAmount, address(_newLoan)), Errors.FAIL_BORROW ); //Emit the NewLoan Event emit NewLoan( _borrower, _delegatee, address(underlying), _amount, address(this), address(_newLoan), _newTokenId, block.number ); //Return the PalLoanToken Id return _newTokenId; }
38,616
60
// Allows arbitrator to remove a seller from the blacklist _seller Seller address /
function unBlacklistSeller(address _seller) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = false; emit UnBlacklistSeller(msg.sender, _seller); }
function unBlacklistSeller(address _seller) public { require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = false; emit UnBlacklistSeller(msg.sender, _seller); }
13,684
8
// TODO: add the keys to your keys array __
Assert.equal(keys_in_map.length, uint(3), "map should have 4 key value pairs"); Assert.equal(keys_in_map[2], uint(128), "array should have the key 256"); Assert.equal(doubles[keys_in_map[1]], __, "should return the correct value for the key");
Assert.equal(keys_in_map.length, uint(3), "map should have 4 key value pairs"); Assert.equal(keys_in_map[2], uint(128), "array should have the key 256"); Assert.equal(doubles[keys_in_map[1]], __, "should return the correct value for the key");
31,306
65
// all these are already scaled by 1e18
uint totalDai = bals[4] + bals[2] + bals[0];
uint totalDai = bals[4] + bals[2] + bals[0];
15,622
49
// Just in case, owner wants to transfer Tokens from contract to owner addresstokenAmount must be in WEI
function manualWithdrawTokens(address token, uint256 tokenAmount)onlyOwner public{ ERC20Essential(token).transfer(msg.sender, tokenAmount); }
function manualWithdrawTokens(address token, uint256 tokenAmount)onlyOwner public{ ERC20Essential(token).transfer(msg.sender, tokenAmount); }
53,637
92
// add liquidity
contractBalance = _thresholdToAddLiquidity; _swapAndLiquify(contractBalance);
contractBalance = _thresholdToAddLiquidity; _swapAndLiquify(contractBalance);
42,794
201
// Event fired when a digital media is burned
event DigitalMediaBurnEvent( uint256 id, address caller);
event DigitalMediaBurnEvent( uint256 id, address caller);
2,113
3
// region Variable
mapping(address => uint256) private ownerToNFTCount; mapping(uint256 => address) internal tokenIdToOwner; mapping(uint256 => address) internal tokenIdToApproval;
mapping(address => uint256) private ownerToNFTCount; mapping(uint256 => address) internal tokenIdToOwner; mapping(uint256 => address) internal tokenIdToApproval;
22,923
45
// based on generation
bytes32 _hash = hash(nft,id);
bytes32 _hash = hash(nft,id);
50,778
38
// [NOT MANDATORY FOR ERC1400Partition STANDARD][OVERRIDES ERC1400Raw METHOD] Transfer the value of tokens on behalf of the address from to the address to. from Token holder (or 'address(0)'' to set from to 'msg.sender'). to Token recipient. value Number of tokens to transfer. data Information attached to the transfer, and intended for the token holder ('from'). [CAN CONTAIN THE DESTINATION PARTITION] operatorData Information attached to the transfer by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] /
function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData)
function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData)
42,525
18
// Role based access control mixin for Rasmart Platform/Abha Mai <maiabha82@gmail.com>/Ignore DRY approach to achieve readability
contract RBACMixin { /// @notice Constant string message to throw on lack of access string constant FORBIDDEN = "Haven't enough right to access"; /// @notice Public map of owners mapping (address => bool) public owners; /// @notice Public map of minters mapping (address => bool) public minters; /// @notice The event indicates the addition of a new owner /// @param who is address of added owner event AddOwner(address indexed who); /// @notice The event indicates the deletion of an owner /// @param who is address of deleted owner event DeleteOwner(address indexed who); /// @notice The event indicates the addition of a new minter /// @param who is address of added minter event AddMinter(address indexed who); /// @notice The event indicates the deletion of a minter /// @param who is address of deleted minter event DeleteMinter(address indexed who); constructor () public { _setOwner(msg.sender, true); } /// @notice The functional modifier rejects the interaction of senders who are not owners modifier onlyOwner() { require(isOwner(msg.sender), FORBIDDEN); _; } /// @notice Functional modifier for rejecting the interaction of senders that are not minters modifier onlyMinter() { require(isMinter(msg.sender), FORBIDDEN); _; } /// @notice Look up for the owner role on providen address /// @param _who is address to look up /// @return A boolean of owner role function isOwner(address _who) public view returns (bool) { return owners[_who]; } /// @notice Look up for the minter role on providen address /// @param _who is address to look up /// @return A boolean of minter role function isMinter(address _who) public view returns (bool) { return minters[_who]; } /// @notice Adds the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, true); } /// @notice Deletes the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, false); } /// @notice Adds the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, true); } /// @notice Deletes the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, false); } /// @notice Changes the owner role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setOwner(address _who, bool _flag) private returns (bool) { require(owners[_who] != _flag); owners[_who] = _flag; if (_flag) { emit AddOwner(_who); } else { emit DeleteOwner(_who); } return true; } /// @notice Changes the minter role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setMinter(address _who, bool _flag) private returns (bool) { require(minters[_who] != _flag); minters[_who] = _flag; if (_flag) { emit AddMinter(_who); } else { emit DeleteMinter(_who); } return true; } }
contract RBACMixin { /// @notice Constant string message to throw on lack of access string constant FORBIDDEN = "Haven't enough right to access"; /// @notice Public map of owners mapping (address => bool) public owners; /// @notice Public map of minters mapping (address => bool) public minters; /// @notice The event indicates the addition of a new owner /// @param who is address of added owner event AddOwner(address indexed who); /// @notice The event indicates the deletion of an owner /// @param who is address of deleted owner event DeleteOwner(address indexed who); /// @notice The event indicates the addition of a new minter /// @param who is address of added minter event AddMinter(address indexed who); /// @notice The event indicates the deletion of a minter /// @param who is address of deleted minter event DeleteMinter(address indexed who); constructor () public { _setOwner(msg.sender, true); } /// @notice The functional modifier rejects the interaction of senders who are not owners modifier onlyOwner() { require(isOwner(msg.sender), FORBIDDEN); _; } /// @notice Functional modifier for rejecting the interaction of senders that are not minters modifier onlyMinter() { require(isMinter(msg.sender), FORBIDDEN); _; } /// @notice Look up for the owner role on providen address /// @param _who is address to look up /// @return A boolean of owner role function isOwner(address _who) public view returns (bool) { return owners[_who]; } /// @notice Look up for the minter role on providen address /// @param _who is address to look up /// @return A boolean of minter role function isMinter(address _who) public view returns (bool) { return minters[_who]; } /// @notice Adds the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, true); } /// @notice Deletes the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteOwner(address _who) public onlyOwner returns (bool) { _setOwner(_who, false); } /// @notice Adds the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, true); } /// @notice Deletes the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, false); } /// @notice Changes the owner role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setOwner(address _who, bool _flag) private returns (bool) { require(owners[_who] != _flag); owners[_who] = _flag; if (_flag) { emit AddOwner(_who); } else { emit DeleteOwner(_who); } return true; } /// @notice Changes the minter role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setMinter(address _who, bool _flag) private returns (bool) { require(minters[_who] != _flag); minters[_who] = _flag; if (_flag) { emit AddMinter(_who); } else { emit DeleteMinter(_who); } return true; } }
56,212
61
// Create a new vault, linked to a series (and therefore underlying) and up to 5 collateral types
function build(address owner, bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external returns (DataTypes.Vault memory);
function build(address owner, bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external returns (DataTypes.Vault memory);
16,312
8
// gets the information of a single slice template
function getSliceTemplate(string memory _templateId) public view returns (string memory, string memory, string memory, uint, string memory, address){ string memory _nam = sliceTemplate_list[_templateId].name; string memory _ver = sliceTemplate_list[_templateId].version; string memory _ven = sliceTemplate_list[_templateId].vendor; uint _pri = sliceTemplate_list[_templateId].price; string memory _uni = sliceTemplate_list[_templateId].unit; address _own = sliceTemplate_list[_templateId].templateOwner; return (_nam, _ver, _ven, _pri, _uni, _own); }
function getSliceTemplate(string memory _templateId) public view returns (string memory, string memory, string memory, uint, string memory, address){ string memory _nam = sliceTemplate_list[_templateId].name; string memory _ver = sliceTemplate_list[_templateId].version; string memory _ven = sliceTemplate_list[_templateId].vendor; uint _pri = sliceTemplate_list[_templateId].price; string memory _uni = sliceTemplate_list[_templateId].unit; address _own = sliceTemplate_list[_templateId].templateOwner; return (_nam, _ver, _ven, _pri, _uni, _own); }
19,604
8
// See {ERC721Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`. /
function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); }
function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); }
3,862
74
// Remember tha address so we can revert back to old addr if needed
previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) );
previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) );
25,249
7
// return uri for certain token
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); uint256 trueId = tokenId + 1; if(!isRevealed){ return placeholderTokenUri; } //string memory baseURI = _baseURI(); return bytes(baseTokenUri).length > 0 ? string(abi.encodePacked(baseTokenUri, trueId.toString(), ".json")) : ""; }
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); uint256 trueId = tokenId + 1; if(!isRevealed){ return placeholderTokenUri; } //string memory baseURI = _baseURI(); return bytes(baseTokenUri).length > 0 ? string(abi.encodePacked(baseTokenUri, trueId.toString(), ".json")) : ""; }
12,238
81
// 0age
contract DharmaDaiExchanger is DharmaDaiExchangerInterface, ERC20 { DTokenInterface private _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 ); ERC20Interface private _DAI = ERC20Interface( 0x6B175474E89094C44Da98b954EedeAC495271d0F ); constructor() public { // Approve Dharma Dai to move Dai on behalf of this contract to support minting. require( _DAI.approve(address(_DDAI), type(uint256).max), "DharmaDaiExchanger: Dai approval for Dharma Dai failed." ); // Ensure that LP token balance is non-zero — at least 1 Dai must be "donated" as well. _mint(address(this), 1e18); emit Deposit(address(this), 1e18, 1e18, 0); } /** * @notice Supply a specified Dai and/or Dharma Dai amount and receive back * liquidity provider tokens in exchange. Approval must be given to this * contract before calling this function. * @param dai uint256 The amount of Dai to supply. * @param dDai uint256 The amount of Dharma Dai to supply. * @return tokensReceived The amount of LP tokens received. */ function deposit(uint256 dai, uint256 dDai) external override returns (uint256 tokensReceived) { require(dai > 0 || dDai > 0, "DharmaDaiExchanger: No funds specified to deposit."); // Get the current Dai <> dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Determine Dai-equivalent value of funds currently in the pool (rounded up). uint256 originalLiquidityValue = _getCurrentLiquidityValue(exchangeRate, true); require( originalLiquidityValue >= 1e18, "DharmaDaiExchanger: Must seed contract with at least 1 Dai before depositing." ); // Transfer in supplied dai & dDai amounts. if (dai > 0) { require( _DAI.transferFrom(msg.sender, address(this), dai), "DharmaDaiExchanger: Dai transfer in failed — ensure allowance is correctly set." ); } if (dDai > 0) { require( _DDAI.transferFrom(msg.sender, address(this), dDai), "DharmaDaiExchanger: Dharma Dai transfer in failed — ensure allowance is correctly set." ); } // Determine the new Dai-equivalent liquidity value (rounded down). uint256 newLiquidityValue = _getCurrentLiquidityValue(exchangeRate, false); require( newLiquidityValue > originalLiquidityValue, "DharmaDaiExchanger: Supplied funds did not sufficiently increase liquidity value." ); // Determine LP tokens to mint by applying liquidity value ratio to current supply. uint256 originalLPTokens = totalSupply(); uint256 newLPTokens = originalLPTokens.mul(newLiquidityValue) / originalLiquidityValue; require( newLPTokens > originalLPTokens, "DharmaDaiExchanger: Supplied funds are insufficient to mint LP tokens." ); tokensReceived = newLPTokens - originalLPTokens; // Mint the LP tokens. _mint(msg.sender, tokensReceived); emit Deposit(msg.sender, tokensReceived, dai, dDai); } /** * @notice Supply a specified number of liquidity provider tokens and * get back the proportion of Dai and/or Dharma Dai tokens currently held * by this contract in exchange. * @param tokensToSupply The amount of LP tokens to supply. * @return dai uint256 The amount of Dai received. * @return dDai uint256 The amount of Dharma Dai received. */ function withdraw(uint256 tokensToSupply) external override returns (uint256 dai, uint256 dDai) { require(tokensToSupply > 0, "DharmaDaiExchanger: No funds specified to withdraw."); // Get the total supply, as well as current Dai & dDai balances. uint256 originalLPTokens = totalSupply(); uint256 daiBalance = _DAI.balanceOf(address(this)); uint256 dDaiBalance = _DDAI.balanceOf(address(this)); // Apply LP token ratio to Dai & dDai balances to determine amount to transfer out. dai = daiBalance.mul(tokensToSupply) / originalLPTokens; dDai = dDaiBalance.mul(tokensToSupply) / originalLPTokens; require( dai.add(dDai) > 0, "DharmaDaiExchanger: Supplied tokens are insufficient to withdraw liquidity." ); // Burn the LP tokens. _burn(msg.sender, tokensToSupply); // Transfer out the proportion of Dai & dDai associated with the burned tokens. if (dai > 0) { require( _DAI.transfer(msg.sender, dai), "DharmaDaiExchanger: Dai transfer out failed." ); } if (dDai > 0) { require( _DDAI.transfer(msg.sender, dDai), "DharmaDaiExchanger: Dharma Dai transfer out failed." ); } emit Withdraw(msg.sender, tokensToSupply, dai, dDai); } /** * @notice Supply a specified amount of Dai and receive Dharma Dai to * the specified account in exchange. Dai approval must be given to * this contract before calling this function. * @param account The recipient of the minted Dharma Dai. * @param daiToSupply uint256 The amount of Dai to supply. * @return dDaiMinted uint256 The amount of Dharma Dai received. */ function mintTo(address account, uint256 daiToSupply) external override returns (uint256 dDaiMinted) { // Get the current Dai <> dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Get the dDai to mint in exchange for the supplied Dai (round down). dDaiMinted = _fromUnderlying(daiToSupply, exchangeRate, false); require( dDaiMinted > 0, "DharmaDaiExchanger: Supplied Dai is insufficient to mint Dharma Dai." ); // Get the current dDai balance. uint256 dDaiBalance = _DDAI.balanceOf(address(this)); // Transfer in Dai to supply. require( _DAI.transferFrom(msg.sender, address(this), daiToSupply), "DharmaDaiExchanger: Dai transfer in failed — ensure allowance is correctly set." ); // Only perform a mint if insufficient dDai is currently available. if (dDaiBalance < dDaiMinted) { // Provide enough Dai to leave equal Dai and dDai value after transfer. uint256 daiBalance = _DAI.balanceOf(address(this)); uint256 dDaiBalanceInDai = _toUnderlying(dDaiBalance, exchangeRate, false); uint256 daiToSupplyInBatch = (daiBalance.add(daiToSupply)).sub(dDaiBalanceInDai) / 2; _DDAI.mint(daiToSupplyInBatch); } // Transfer the dDai to the specified recipient. require( _DDAI.transfer(account, dDaiMinted), "DharmaDaiExchanger: Dharma Dai transfer out failed." ); } /** * @notice Supply a specified amount of Dharma Dai (denominated in Dai) * and receive Dai to the specified account in exchange. Dharma Dai * approval must be given to this contract before calling this function. * @param account The recipient of the received Dai. * @param daiToReceive uint256 The amount of Dai to receive back in * exchange for supplied Dharma Dai. * @return dDaiBurned uint256 The amount of Dharma Dai redeemed. */ function redeemUnderlyingTo(address account, uint256 daiToReceive) external override returns (uint256 dDaiBurned) { // Get the current Dai <> dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Get the dDai to burn in exchange for the received Dai (round up). dDaiBurned = _fromUnderlying(daiToReceive, exchangeRate, true); require( dDaiBurned > 0, "DharmaDaiExchanger: Dai amount to receive is insufficient to redeem Dharma Dai." ); // Get the current Dai balance. uint256 daiBalance = _DAI.balanceOf(address(this)); // Transfer in required dDai to burn. require( _DDAI.transferFrom(msg.sender, address(this), dDaiBurned), "DharmaDaiExchanger: Dharma Dai transfer in failed — ensure allowance is correctly set." ); // Only perform a redeem if insufficient Dai is currently available. if (daiBalance < daiToReceive) { // Provide enough Dai to leave equal Dai and dDai value after transfer. uint256 dDaiBalance = _DDAI.balanceOf(address(this)); uint256 dDaiBalanceInDai = _toUnderlying(dDaiBalance, exchangeRate, false); uint256 daiToReceiveInBatch = (dDaiBalanceInDai.add(daiToReceive)).sub(daiBalance) / 2; _DDAI.redeemUnderlying(daiToReceiveInBatch); } // Transfer the Dai to the specified recipient. require( _DAI.transfer(account, daiToReceive), "DharmaDaiExchanger: Dai transfer out failed." ); } function name() external pure override returns (string memory) { return "Dai <> Dharma Dai Exchanger (Liquidity Provider token)"; } function symbol() external pure override returns (string memory) { return "Dai-dDai-LP"; } function decimals() external pure override returns (uint8) { return 18; } /** * @notice Internal view function to get the the current combined value of * Dai and Dharma Dai held by this contract, denominated in Dai. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return totalValueInDai The combined value in Dai held by this contract. */ function _getCurrentLiquidityValue(uint256 exchangeRate, bool roundUp) internal view returns (uint256 totalValueInDai) { uint256 daiBalance = _DAI.balanceOf(address(this)); uint256 dDaiBalance = _DDAI.balanceOf(address(this)); uint256 dDaiBalanceInDai = _toUnderlying(dDaiBalance, exchangeRate, roundUp); totalValueInDai = daiBalance.add(dDaiBalanceInDai); } /** * @notice Internal pure function to convert an underlying amount to a dToken * amount using an exchange rate and fixed-point arithmetic. * @param underlying uint256 The underlying amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return amount The dToken amount. */ function _fromUnderlying( uint256 underlying, uint256 exchangeRate, bool roundUp ) internal pure returns (uint256 amount) { if (roundUp) { amount = ( (underlying.mul(1e18)).add(exchangeRate.sub(1)) ).div(exchangeRate); } else { amount = (underlying.mul(1e18)).div(exchangeRate); } } /** * @notice Internal pure function to convert a dToken amount to the * underlying amount using an exchange rate and fixed-point arithmetic. * @param amount uint256 The dToken amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return underlying The underlying amount. */ function _toUnderlying( uint256 amount, uint256 exchangeRate, bool roundUp ) internal pure returns (uint256 underlying) { if (roundUp) { underlying = ( (amount.mul(exchangeRate).add(999999999999999999) ) / 1e18); } else { underlying = amount.mul(exchangeRate) / 1e18; } } }
contract DharmaDaiExchanger is DharmaDaiExchangerInterface, ERC20 { DTokenInterface private _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 ); ERC20Interface private _DAI = ERC20Interface( 0x6B175474E89094C44Da98b954EedeAC495271d0F ); constructor() public { // Approve Dharma Dai to move Dai on behalf of this contract to support minting. require( _DAI.approve(address(_DDAI), type(uint256).max), "DharmaDaiExchanger: Dai approval for Dharma Dai failed." ); // Ensure that LP token balance is non-zero — at least 1 Dai must be "donated" as well. _mint(address(this), 1e18); emit Deposit(address(this), 1e18, 1e18, 0); } /** * @notice Supply a specified Dai and/or Dharma Dai amount and receive back * liquidity provider tokens in exchange. Approval must be given to this * contract before calling this function. * @param dai uint256 The amount of Dai to supply. * @param dDai uint256 The amount of Dharma Dai to supply. * @return tokensReceived The amount of LP tokens received. */ function deposit(uint256 dai, uint256 dDai) external override returns (uint256 tokensReceived) { require(dai > 0 || dDai > 0, "DharmaDaiExchanger: No funds specified to deposit."); // Get the current Dai <> dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Determine Dai-equivalent value of funds currently in the pool (rounded up). uint256 originalLiquidityValue = _getCurrentLiquidityValue(exchangeRate, true); require( originalLiquidityValue >= 1e18, "DharmaDaiExchanger: Must seed contract with at least 1 Dai before depositing." ); // Transfer in supplied dai & dDai amounts. if (dai > 0) { require( _DAI.transferFrom(msg.sender, address(this), dai), "DharmaDaiExchanger: Dai transfer in failed — ensure allowance is correctly set." ); } if (dDai > 0) { require( _DDAI.transferFrom(msg.sender, address(this), dDai), "DharmaDaiExchanger: Dharma Dai transfer in failed — ensure allowance is correctly set." ); } // Determine the new Dai-equivalent liquidity value (rounded down). uint256 newLiquidityValue = _getCurrentLiquidityValue(exchangeRate, false); require( newLiquidityValue > originalLiquidityValue, "DharmaDaiExchanger: Supplied funds did not sufficiently increase liquidity value." ); // Determine LP tokens to mint by applying liquidity value ratio to current supply. uint256 originalLPTokens = totalSupply(); uint256 newLPTokens = originalLPTokens.mul(newLiquidityValue) / originalLiquidityValue; require( newLPTokens > originalLPTokens, "DharmaDaiExchanger: Supplied funds are insufficient to mint LP tokens." ); tokensReceived = newLPTokens - originalLPTokens; // Mint the LP tokens. _mint(msg.sender, tokensReceived); emit Deposit(msg.sender, tokensReceived, dai, dDai); } /** * @notice Supply a specified number of liquidity provider tokens and * get back the proportion of Dai and/or Dharma Dai tokens currently held * by this contract in exchange. * @param tokensToSupply The amount of LP tokens to supply. * @return dai uint256 The amount of Dai received. * @return dDai uint256 The amount of Dharma Dai received. */ function withdraw(uint256 tokensToSupply) external override returns (uint256 dai, uint256 dDai) { require(tokensToSupply > 0, "DharmaDaiExchanger: No funds specified to withdraw."); // Get the total supply, as well as current Dai & dDai balances. uint256 originalLPTokens = totalSupply(); uint256 daiBalance = _DAI.balanceOf(address(this)); uint256 dDaiBalance = _DDAI.balanceOf(address(this)); // Apply LP token ratio to Dai & dDai balances to determine amount to transfer out. dai = daiBalance.mul(tokensToSupply) / originalLPTokens; dDai = dDaiBalance.mul(tokensToSupply) / originalLPTokens; require( dai.add(dDai) > 0, "DharmaDaiExchanger: Supplied tokens are insufficient to withdraw liquidity." ); // Burn the LP tokens. _burn(msg.sender, tokensToSupply); // Transfer out the proportion of Dai & dDai associated with the burned tokens. if (dai > 0) { require( _DAI.transfer(msg.sender, dai), "DharmaDaiExchanger: Dai transfer out failed." ); } if (dDai > 0) { require( _DDAI.transfer(msg.sender, dDai), "DharmaDaiExchanger: Dharma Dai transfer out failed." ); } emit Withdraw(msg.sender, tokensToSupply, dai, dDai); } /** * @notice Supply a specified amount of Dai and receive Dharma Dai to * the specified account in exchange. Dai approval must be given to * this contract before calling this function. * @param account The recipient of the minted Dharma Dai. * @param daiToSupply uint256 The amount of Dai to supply. * @return dDaiMinted uint256 The amount of Dharma Dai received. */ function mintTo(address account, uint256 daiToSupply) external override returns (uint256 dDaiMinted) { // Get the current Dai <> dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Get the dDai to mint in exchange for the supplied Dai (round down). dDaiMinted = _fromUnderlying(daiToSupply, exchangeRate, false); require( dDaiMinted > 0, "DharmaDaiExchanger: Supplied Dai is insufficient to mint Dharma Dai." ); // Get the current dDai balance. uint256 dDaiBalance = _DDAI.balanceOf(address(this)); // Transfer in Dai to supply. require( _DAI.transferFrom(msg.sender, address(this), daiToSupply), "DharmaDaiExchanger: Dai transfer in failed — ensure allowance is correctly set." ); // Only perform a mint if insufficient dDai is currently available. if (dDaiBalance < dDaiMinted) { // Provide enough Dai to leave equal Dai and dDai value after transfer. uint256 daiBalance = _DAI.balanceOf(address(this)); uint256 dDaiBalanceInDai = _toUnderlying(dDaiBalance, exchangeRate, false); uint256 daiToSupplyInBatch = (daiBalance.add(daiToSupply)).sub(dDaiBalanceInDai) / 2; _DDAI.mint(daiToSupplyInBatch); } // Transfer the dDai to the specified recipient. require( _DDAI.transfer(account, dDaiMinted), "DharmaDaiExchanger: Dharma Dai transfer out failed." ); } /** * @notice Supply a specified amount of Dharma Dai (denominated in Dai) * and receive Dai to the specified account in exchange. Dharma Dai * approval must be given to this contract before calling this function. * @param account The recipient of the received Dai. * @param daiToReceive uint256 The amount of Dai to receive back in * exchange for supplied Dharma Dai. * @return dDaiBurned uint256 The amount of Dharma Dai redeemed. */ function redeemUnderlyingTo(address account, uint256 daiToReceive) external override returns (uint256 dDaiBurned) { // Get the current Dai <> dDai exchange rate. uint256 exchangeRate = _DDAI.exchangeRateCurrent(); // Get the dDai to burn in exchange for the received Dai (round up). dDaiBurned = _fromUnderlying(daiToReceive, exchangeRate, true); require( dDaiBurned > 0, "DharmaDaiExchanger: Dai amount to receive is insufficient to redeem Dharma Dai." ); // Get the current Dai balance. uint256 daiBalance = _DAI.balanceOf(address(this)); // Transfer in required dDai to burn. require( _DDAI.transferFrom(msg.sender, address(this), dDaiBurned), "DharmaDaiExchanger: Dharma Dai transfer in failed — ensure allowance is correctly set." ); // Only perform a redeem if insufficient Dai is currently available. if (daiBalance < daiToReceive) { // Provide enough Dai to leave equal Dai and dDai value after transfer. uint256 dDaiBalance = _DDAI.balanceOf(address(this)); uint256 dDaiBalanceInDai = _toUnderlying(dDaiBalance, exchangeRate, false); uint256 daiToReceiveInBatch = (dDaiBalanceInDai.add(daiToReceive)).sub(daiBalance) / 2; _DDAI.redeemUnderlying(daiToReceiveInBatch); } // Transfer the Dai to the specified recipient. require( _DAI.transfer(account, daiToReceive), "DharmaDaiExchanger: Dai transfer out failed." ); } function name() external pure override returns (string memory) { return "Dai <> Dharma Dai Exchanger (Liquidity Provider token)"; } function symbol() external pure override returns (string memory) { return "Dai-dDai-LP"; } function decimals() external pure override returns (uint8) { return 18; } /** * @notice Internal view function to get the the current combined value of * Dai and Dharma Dai held by this contract, denominated in Dai. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return totalValueInDai The combined value in Dai held by this contract. */ function _getCurrentLiquidityValue(uint256 exchangeRate, bool roundUp) internal view returns (uint256 totalValueInDai) { uint256 daiBalance = _DAI.balanceOf(address(this)); uint256 dDaiBalance = _DDAI.balanceOf(address(this)); uint256 dDaiBalanceInDai = _toUnderlying(dDaiBalance, exchangeRate, roundUp); totalValueInDai = daiBalance.add(dDaiBalanceInDai); } /** * @notice Internal pure function to convert an underlying amount to a dToken * amount using an exchange rate and fixed-point arithmetic. * @param underlying uint256 The underlying amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return amount The dToken amount. */ function _fromUnderlying( uint256 underlying, uint256 exchangeRate, bool roundUp ) internal pure returns (uint256 amount) { if (roundUp) { amount = ( (underlying.mul(1e18)).add(exchangeRate.sub(1)) ).div(exchangeRate); } else { amount = (underlying.mul(1e18)).div(exchangeRate); } } /** * @notice Internal pure function to convert a dToken amount to the * underlying amount using an exchange rate and fixed-point arithmetic. * @param amount uint256 The dToken amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return underlying The underlying amount. */ function _toUnderlying( uint256 amount, uint256 exchangeRate, bool roundUp ) internal pure returns (uint256 underlying) { if (roundUp) { underlying = ( (amount.mul(exchangeRate).add(999999999999999999) ) / 1e18); } else { underlying = amount.mul(exchangeRate) / 1e18; } } }
32,701
296
// Get the parameters to be used in constructing the pool, set transiently during pool creation./Called by the pool constructor to fetch the parameters of the pool/ Returns factory The factory address/ Returns token0 The first token of the pool by address sort order/ Returns token1 The second token of the pool by address sort order/ Returns fee The fee collected upon every swap in the pool, denominated in hundredths of a bip/ Returns tickSpacing The minimum number of ticks between initialized ticks
function parameters() external view returns ( address factory, address token0, address token1, uint24 fee, int24 tickSpacing );
function parameters() external view returns ( address factory, address token0, address token1, uint24 fee, int24 tickSpacing );
26,939
20
// initialize
function initialize( address _saleTokenAddress, address _getTokenAddress, address _getTokenOwner, address _sTOS ) external;
function initialize( address _saleTokenAddress, address _getTokenAddress, address _getTokenOwner, address _sTOS ) external;
5,370
7
// 检查转账是否满足条件 1.转出账户余额是否充足 2.转出金额是否大于0 并且是否超出限制
require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value;
require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value;
4,135
1
// working with unit8 & uint16 to save on gas. /If collection is larger 65,535 tokens than change the uint accordingly./ Since tokenStatus is always going to be a 0 or 1 it can stay uint8. The Number of tokens + _startToken. In our case _startToken is 1
uint8[5476] public tokenStatus;
uint8[5476] public tokenStatus;
7,973
200
// Deposit LP tokens to MasterChef for rNEX 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.accrNEXPerShare) .div(1e12) .sub(user.rewardDebt); if (pending > 0) { saferNEXTransfer(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.accrNEXPerShare).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.accrNEXPerShare) .div(1e12) .sub(user.rewardDebt); if (pending > 0) { saferNEXTransfer(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.accrNEXPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
23,126
32
// 解除仲裁员的冻结状态
uint256[] memory d = rans[i]; for (uint n = 0; n < meg; n++) { address ard = arber[rans[i][n]]; arbw[i][ard] = 0; arbone.backMar(ard); d[n] = 0; }
uint256[] memory d = rans[i]; for (uint n = 0; n < meg; n++) { address ard = arber[rans[i][n]]; arbw[i][ard] = 0; arbone.backMar(ard); d[n] = 0; }
4,513
11
// if wallet has token staked, then calculate the rewards
if (stakers[msg.sender].ammountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; }
if (stakers[msg.sender].ammountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; }
18,642
26
// Current number of tokens in circulation. /
uint256 tokenCount = 0;
uint256 tokenCount = 0;
6,936
165
// Calculate and mint the amount of xDvf the Dvf is worth. The ratio will change overtime, as xDvf is burned/minted and Dvf deposited + gained from fees / withdrawn.
else { uint256 what = _amount.mul(totalShares).div(totalDvf); _mint(msg.sender, what); }
else { uint256 what = _amount.mul(totalShares).div(totalDvf); _mint(msg.sender, what); }
41,828
191
// FREE MINT /
function updateFreeMintCount(address minter, uint256 count) private { freeMintCountMap[minter] += count; }
function updateFreeMintCount(address minter, uint256 count) private { freeMintCountMap[minter] += count; }
16,990
178
// Applied to every buy or sale of DVD./Tax denominator
uint256 public constant CURVE_TAX_DENOMINATOR = 10;
uint256 public constant CURVE_TAX_DENOMINATOR = 10;
73,885
9
// Freeze a account until undo.
* See {ERC20Lockable} and {Lockable-_lock}. * * Requirements: * * - the caller must have the `LOCKER_ROLE`. */ function freezeAddress(address target) public virtual { require(hasRole(LOCKER_ROLE, _msgSender()), "ERC20: must have locker role to lock"); _lock(target); }
* See {ERC20Lockable} and {Lockable-_lock}. * * Requirements: * * - the caller must have the `LOCKER_ROLE`. */ function freezeAddress(address target) public virtual { require(hasRole(LOCKER_ROLE, _msgSender()), "ERC20: must have locker role to lock"); _lock(target); }
23,908
109
// Returns a descriptive name for a collection of NFTokens.return _name Representing name. /
function name() external override view returns (string memory _name)
function name() external override view returns (string memory _name)
29,092
13
// total coins in circulation
uint256 public _circulatingSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _leverage = 0;
uint256 public _circulatingSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _leverage = 0;
17,475
4
// Returns x - y, reverts if overflows or underflows/x The minuend/y The subtrahend/ return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); }
function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); }
15,972
5
// A mapping between an account and its sent attestations.
mapping(address => mapping(bytes32 => bytes32[])) private _sentAttestations;
mapping(address => mapping(bytes32 => bytes32[])) private _sentAttestations;
30,704
9
// Checks if the specified number of tokens can be afforded for the given token ID. tokenId The ID of the token. tokens The number of tokens to check affordability for.return A boolean indicating whether the tokens can be afforded. /
function isAffordable(uint256 tokenId, uint256 tokens) public view returns (bool) { require(tokenExists(tokenId), "Token does not exist"); return tokenPrice[tokenId] <= tokens; }
function isAffordable(uint256 tokenId, uint256 tokens) public view returns (bool) { require(tokenExists(tokenId), "Token does not exist"); return tokenPrice[tokenId] <= tokens; }
9,409
60
// newHours: in hours /
function setTier(uint256 count, uint256 newHours) public onlyOwner { require(count < _taxTiers.length); _taxTiers[count] = newHours; }
function setTier(uint256 count, uint256 newHours) public onlyOwner { require(count < _taxTiers.length); _taxTiers[count] = newHours; }
23,461
24
// this is now updated to the current transaction
(, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(positionKey); position.tokensOwed0 += uint128( FullMath.mulDiv( feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128, position.liquidity, FixedPoint128.Q128 ) ); position.tokensOwed1 += uint128(
(, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(positionKey); position.tokensOwed0 += uint128( FullMath.mulDiv( feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128, position.liquidity, FixedPoint128.Q128 ) ); position.tokensOwed1 += uint128(
10,608
11
// Permission manager contract /
modifier onlyPermitted() { require(permissionManager.isPermitted(msg.sender)); _; }
modifier onlyPermitted() { require(permissionManager.isPermitted(msg.sender)); _; }
13,035
1
// XXX: function() external payable { }
receive() external payable { }
receive() external payable { }
32,113
8
// arbitrary transfer (requires TRUSTED_AGENT_ROLE) USE WITH CAUTION /
function trustedAgentTransfer(
function trustedAgentTransfer(
32,850
52
// Returns the square root of a number. If the number is not a perfect square, the value is rounded down. Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). /
function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } }
function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } }
47,891
37
// _lbc address : LifeBankerCoin contract deployment address
constructor(address _lbc) public{ startTime = now; LBC = LifeBankerCoin(_lbc); whiteList[msg.sender] = true; }
constructor(address _lbc) public{ startTime = now; LBC = LifeBankerCoin(_lbc); whiteList[msg.sender] = true; }
51,485
165
// address that has permission to partially pause the system, where system functionality is paused/ except redeem and settleVault
address public partialPauser;
address public partialPauser;
574
35
// If the mint is going to be stolen, there's a 50% chancea pirate will prefer a fine crafted EON liquor over it
if (seed & 1 == 1) { imperialGuild.safeTransferFrom( msg.sender, recipient, OnosiaLiquorId, 1, "" ); recipient = msg.sender; }
if (seed & 1 == 1) { imperialGuild.safeTransferFrom( msg.sender, recipient, OnosiaLiquorId, 1, "" ); recipient = msg.sender; }
34,101
64
// Database of Vending Items Purchasers for each ERC20
mapping(address => mapping(uint256 => address[])) public contractToWLPurchasers; mapping(address => mapping(uint256 => mapping(address => bool))) public contractToWLPurchased; function addWLVendingItem(address contract_, WLVendingItem memory WLVendingItem_)
mapping(address => mapping(uint256 => address[])) public contractToWLPurchasers; mapping(address => mapping(uint256 => mapping(address => bool))) public contractToWLPurchased; function addWLVendingItem(address contract_, WLVendingItem memory WLVendingItem_)
79,092
249
// create a 2d array and fill with a single value /
) internal pure returns (int256[][] memory) { /// Create a matrix of values with dimensions (m, q) int256[][] memory rows = new int256[][](m); for (uint256 i = 0; i < m; i++) { int256[] memory row = new int256[](q); for (uint256 j = 0; j < q; j++) { row[j] = value; } rows[i] = row; } return rows; }
) internal pure returns (int256[][] memory) { /// Create a matrix of values with dimensions (m, q) int256[][] memory rows = new int256[][](m); for (uint256 i = 0; i < m; i++) { int256[] memory row = new int256[](q); for (uint256 j = 0; j < q; j++) { row[j] = value; } rows[i] = row; } return rows; }
45,387
73
// Event emitted when token rate is calculated.
event RewardRateCalculated(uint256 rewardRate); IERC20 public Reward; mapping(address => bool) public teller; mapping(address => uint256) public tellerPriority; mapping(address => uint256) public priorityFreeze; uint256 public totalPriority; uint256 public rewardRate;
event RewardRateCalculated(uint256 rewardRate); IERC20 public Reward; mapping(address => bool) public teller; mapping(address => uint256) public tellerPriority; mapping(address => uint256) public priorityFreeze; uint256 public totalPriority; uint256 public rewardRate;
472
26
// if there's no new round, then the previous roundId was the latest
if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; }
if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; }
19,159
200
// Sends any leftover balances back to the user/Sends any leftover balances to the user/_swaps Swap data array/_leftoverReceiver Address to send leftover tokens to/_initialBalances Array of initial token balances
modifier noLeftovers( LibSwap.SwapData[] calldata _swaps, address payable _leftoverReceiver, uint256[] memory _initialBalances
modifier noLeftovers( LibSwap.SwapData[] calldata _swaps, address payable _leftoverReceiver, uint256[] memory _initialBalances
8,906
235
// Public Functions /
{ require(_regName != 0x0); kAddr_ = new Bakt(owner, _regName, msg.sender); Created(msg.sender, _regName, kAddr_); }
{ require(_regName != 0x0); kAddr_ = new Bakt(owner, _regName, msg.sender); Created(msg.sender, _regName, kAddr_); }
45,763
46
// Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation forproblems described in {BEP20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. /
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
21,332
8
// Funcion para evaluar a alumnos
function Evaluar(string memory _asignatura, string memory _idAlumno, uint _nota) public UnicamenteProfesor(msg.sender){ // Hash de la identificacion del alumno bytes32 hash_AsignaturaIdAlumno = keccak256(abi.encodePacked(_asignatura,_idAlumno)); // Relacion entre el hash de la identificacion del alumno y su nota Notas[hash_AsignaturaIdAlumno] = _nota; // Emision del evento emit alumno_evaluado(hash_AsignaturaIdAlumno); }
function Evaluar(string memory _asignatura, string memory _idAlumno, uint _nota) public UnicamenteProfesor(msg.sender){ // Hash de la identificacion del alumno bytes32 hash_AsignaturaIdAlumno = keccak256(abi.encodePacked(_asignatura,_idAlumno)); // Relacion entre el hash de la identificacion del alumno y su nota Notas[hash_AsignaturaIdAlumno] = _nota; // Emision del evento emit alumno_evaluado(hash_AsignaturaIdAlumno); }
22,880
1
// First PrizeDistributionBuffer source address
IPrizeDistributionSource public immutable prizeDistributionSourceBefore;
IPrizeDistributionSource public immutable prizeDistributionSourceBefore;
24,901
295
// checkpoints
uint8 checkpoint = currentCheckpoint(); uint8 lastCheckpoint = members[sender].lastCheckpoint;
uint8 checkpoint = currentCheckpoint(); uint8 lastCheckpoint = members[sender].lastCheckpoint;
75,127
10
// this function will swap cblt tokens for tokens that are allowed/
function swapForCblt( IERC20 fromToken, uint256 amount ) external payable
function swapForCblt( IERC20 fromToken, uint256 amount ) external payable
15,170
0
// イベント設置
event Set(address from,string message); event Message(address from, string message);
event Set(address from,string message); event Message(address from, string message);
2,801
43
// validation of the parameters: the LTV can only be lower or equal than the liquidation threshold (otherwise a loan against the asset would cause instantaneous liquidation)
require(ltv <= liquidationThreshold, Errors.INVALID_EMODE_CATEGORY_PARAMS); require( liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, Errors.INVALID_EMODE_CATEGORY_PARAMS );
require(ltv <= liquidationThreshold, Errors.INVALID_EMODE_CATEGORY_PARAMS); require( liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, Errors.INVALID_EMODE_CATEGORY_PARAMS );
6,301
53
// Assign the rating and adjust their account
booking.ownerRating = stars; blockchainBNBStorage().accounts[booking.hostAddr].totalScore += stars; blockchainBNBStorage().accounts[booking.hostAddr].nRatings++;
booking.ownerRating = stars; blockchainBNBStorage().accounts[booking.hostAddr].totalScore += stars; blockchainBNBStorage().accounts[booking.hostAddr].nRatings++;
29,346
107
// Initialize new epoch
currentEpochId++; newEpoch.id = currentEpochId; newEpoch.startEpoch = startEpoch; newEpoch.finishEpoch = finishEpoch; newEpoch.rewardRate = reward.div(rewardsDuration);
currentEpochId++; newEpoch.id = currentEpochId; newEpoch.startEpoch = startEpoch; newEpoch.finishEpoch = finishEpoch; newEpoch.rewardRate = reward.div(rewardsDuration);
55,080
2
// Ask this job if it has a unit of work available/This should never revert, only return false if nothing is available/This should normally be a view, but sometimes that's not possible/network The name of the external keeper network/ return canWork Returns true if a unit of work is available/ return args The custom arguments to be provided to work() or an error string if canWork is false
function workable(bytes32 network) external returns (bool canWork, bytes memory args);
function workable(bytes32 network) external returns (bool canWork, bytes memory args);
36,285
36
// Callback for proposals. identifier price identifier being requested. timestamp timestamp of the price being requested. ancillaryData ancillary data of the price being requested. /
function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external;
function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external;
9,743
79
// the total amount of SURF tokens wrapped and tracked by this contract (wei amount)
uint256 public SURFwrapped;
uint256 public SURFwrapped;
2,393
38
// The contract for capture composable nft challengescontrolHash is keccak256(keccak256(answer), msg.sender) and is a simple prevention against front runningTo win a player gives an answer, keccak256(answer) must agree with stored Challenge.answerHashFor every challenge there is one nft as reward, actually it is erc998 composable/bundle Only owner can add or remove challenges, no additional time constraintsDo not transfer reward NFTs to this contract !!!Before adding new challenge, current nft owner (aka from) must approveAll this contractThere can be only one address of reward nfts (aka bundles)Note, there is no check if tokenId is duplicated, it is responsibility of the owner to not
contract CaptureComposableNFT is Ownable { struct Challenge { bytes32 answerHash; // a hash of valid answer address winner; // address(0) if not yet solved address from; // from is an address from which a reward will be transferred uint256 tokenId; // bundles is the address of nft contract } IERC721 public immutable bundles; mapping(uint256 => Challenge) public challenges; constructor(address _bundles) { bundles = IERC721(_bundles); } /** * @notice only the first player with correct answer gets a reward * @param controlHash see the contract docs for info and you can use calculateControlHash function * @param answer must be precise */ function solveChallenge(uint256 challengeId, bytes32 controlHash, string memory answer) external { bytes32 expectedAnswerHash = challenges[challengeId].answerHash; require(expectedAnswerHash != 0x0, 'CaptureComposableNFT: Unknown challenge'); bytes32 answerHash = keccak256(bytes(answer)); require(expectedAnswerHash == answerHash, 'CaptureComposableNFT: wrong answer'); require(keccak256(abi.encodePacked(answerHash, msg.sender)) == controlHash, 'CaptureComposableNFT: wrong controlHash'); require(challenges[challengeId].winner == address(0), 'CaptureComposableNFT: challenge already solved'); challenges[challengeId].winner = msg.sender; address from = challenges[challengeId].from; uint256 tokenId = challenges[challengeId].tokenId; bundles.safeTransferFrom(from, msg.sender, tokenId); } /** * @notice a player can check if the answer is correct before sending tx and losing gas */ function checkAnswer(uint256 challengeId, string memory answer) public view returns (bool) { return challenges[challengeId].answerHash == keccak256(bytes(answer)); } function isSolved(uint256 challengeId) external view returns (bool) { return challenges[challengeId].answerHash != 0x0 && challenges[challengeId].winner != address(0); } /** * @notice a helper function for a player to ease calculating a control hash */ function calculateControlHash(string memory answer, address solver) external pure returns (bytes32) { bytes32 answerHash = keccak256(bytes(answer)); return keccak256(abi.encodePacked(answerHash, solver)); } function newChallenge(uint256 challengeId, bytes32 answerHash, address from, uint256 tokenId) external onlyOwner { bytes32 expectedAnswerHash = challenges[challengeId].answerHash; require(expectedAnswerHash == 0x0, 'CaptureComposableNFT: challengeId already taken'); require(bundles.ownerOf(tokenId) == from, 'CaptureComposableNFT: tokenId is not owned by from address'); require(bundles.isApprovedForAll(from, address(this)), 'CaptureComposableNFT: tokenId is not approved by from address'); challenges[challengeId].answerHash = answerHash; challenges[challengeId].from = from; challenges[challengeId].tokenId = tokenId; } function dropChallenge(uint256 challengeId) external onlyOwner { bytes32 expectedAnswerHash = challenges[challengeId].answerHash; require(expectedAnswerHash != 0x0, 'CaptureComposableNFT: Unknown challenge'); require(challenges[challengeId].winner == address(0), 'CaptureComposableNFT: challenge already solved'); delete challenges[challengeId]; } }
contract CaptureComposableNFT is Ownable { struct Challenge { bytes32 answerHash; // a hash of valid answer address winner; // address(0) if not yet solved address from; // from is an address from which a reward will be transferred uint256 tokenId; // bundles is the address of nft contract } IERC721 public immutable bundles; mapping(uint256 => Challenge) public challenges; constructor(address _bundles) { bundles = IERC721(_bundles); } /** * @notice only the first player with correct answer gets a reward * @param controlHash see the contract docs for info and you can use calculateControlHash function * @param answer must be precise */ function solveChallenge(uint256 challengeId, bytes32 controlHash, string memory answer) external { bytes32 expectedAnswerHash = challenges[challengeId].answerHash; require(expectedAnswerHash != 0x0, 'CaptureComposableNFT: Unknown challenge'); bytes32 answerHash = keccak256(bytes(answer)); require(expectedAnswerHash == answerHash, 'CaptureComposableNFT: wrong answer'); require(keccak256(abi.encodePacked(answerHash, msg.sender)) == controlHash, 'CaptureComposableNFT: wrong controlHash'); require(challenges[challengeId].winner == address(0), 'CaptureComposableNFT: challenge already solved'); challenges[challengeId].winner = msg.sender; address from = challenges[challengeId].from; uint256 tokenId = challenges[challengeId].tokenId; bundles.safeTransferFrom(from, msg.sender, tokenId); } /** * @notice a player can check if the answer is correct before sending tx and losing gas */ function checkAnswer(uint256 challengeId, string memory answer) public view returns (bool) { return challenges[challengeId].answerHash == keccak256(bytes(answer)); } function isSolved(uint256 challengeId) external view returns (bool) { return challenges[challengeId].answerHash != 0x0 && challenges[challengeId].winner != address(0); } /** * @notice a helper function for a player to ease calculating a control hash */ function calculateControlHash(string memory answer, address solver) external pure returns (bytes32) { bytes32 answerHash = keccak256(bytes(answer)); return keccak256(abi.encodePacked(answerHash, solver)); } function newChallenge(uint256 challengeId, bytes32 answerHash, address from, uint256 tokenId) external onlyOwner { bytes32 expectedAnswerHash = challenges[challengeId].answerHash; require(expectedAnswerHash == 0x0, 'CaptureComposableNFT: challengeId already taken'); require(bundles.ownerOf(tokenId) == from, 'CaptureComposableNFT: tokenId is not owned by from address'); require(bundles.isApprovedForAll(from, address(this)), 'CaptureComposableNFT: tokenId is not approved by from address'); challenges[challengeId].answerHash = answerHash; challenges[challengeId].from = from; challenges[challengeId].tokenId = tokenId; } function dropChallenge(uint256 challengeId) external onlyOwner { bytes32 expectedAnswerHash = challenges[challengeId].answerHash; require(expectedAnswerHash != 0x0, 'CaptureComposableNFT: Unknown challenge'); require(challenges[challengeId].winner == address(0), 'CaptureComposableNFT: challenge already solved'); delete challenges[challengeId]; } }
28,558
30
// Function to mint tokens _to The address that will recieve 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 returns (bool) { _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; }
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; }
7,747
234
// Checks that a given monster is able to breed. Requires that the/current cooldown is finished (for sires) and also checks that there is/no pending pregnancy.
function _isReadyToBreed(Monster _monster) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the monster has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_monster.siringWithId == 0) && (_monster.cooldownEndBlock <= uint64(block.number)); }
function _isReadyToBreed(Monster _monster) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the monster has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_monster.siringWithId == 0) && (_monster.cooldownEndBlock <= uint64(block.number)); }
41,012
70
// require(msg.sender == _lock_ruff_addr);
transfer(_to, _value); emit WithdrawEvent(_lock_clpt_addr, _value, _to, txHash); return true;
transfer(_to, _value); emit WithdrawEvent(_lock_clpt_addr, _value, _to, txHash); return true;
13,695
18
// Deposit LP tokens to MCV2 for SYNAPSE allocation./pid The index of the pool. See `poolInfo`./amount LP token amount to deposit./to The receiver of `amount` deposit benefit.
function deposit(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); }
function deposit(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); }
26,115
80
// The bound above and below the price target at which the refershing CR will not change the collateral ratio.
uint256 public priceBand;
uint256 public priceBand;
22,475