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
16
// Make sure token balance > 0
uint256 vnetBalance = vnetToken.balanceOf(address(this)); require(vnetBalance > 0); require(vnetSold < vnetSupply);
uint256 vnetBalance = vnetToken.balanceOf(address(this)); require(vnetBalance > 0); require(vnetSold < vnetSupply);
27,325
147
// variables used when creating 3d prisms
struct GeomVars { int256 rotX; int256 rotY; int256 rotZ; int256[3][2] extents; int256[3] center; int256 width; int256 height; int256 extent; int256 scaleNum; uint256[] hltPrismIdx; int256[3][3][] trisBack; int256[3][3][] trisFront; uint256 nPrisms; }
struct GeomVars { int256 rotX; int256 rotY; int256 rotZ; int256[3][2] extents; int256[3] center; int256 width; int256 height; int256 extent; int256 scaleNum; uint256[] hltPrismIdx; int256[3][3][] trisBack; int256[3][3][] trisFront; uint256 nPrisms; }
31,196
9
// whitelist[_contributor] = true;
whitelist[_contributor].whitelisted = true; emit WhitelistingLog(_contributor); return true;
whitelist[_contributor].whitelisted = true; emit WhitelistingLog(_contributor); return true;
7,306
1
// XXX: function() external payable { }
receive() external payable { }
receive() external payable { }
29,004
4
// Create dydx actions to run on the dydx accounts.
IDydx.ActionArgs[] memory actions = _createActions( from, to, amount, bridgeData );
IDydx.ActionArgs[] memory actions = _createActions( from, to, amount, bridgeData );
39,558
215
// Contract address of the associated ERC20 token
address token;
address token;
4,586
20
// Refund existing top bidder if found
if (highestBid.bidder != address(0)) { _refundHighestBidder(highestBid.bidder, highestBid.bid); }
if (highestBid.bidder != address(0)) { _refundHighestBidder(highestBid.bidder, highestBid.bid); }
22,988
13
// Naively set amountOutMinimum to 0. In production,use an oracle or other data source to choose a safer value for amountOutMinimum. We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount.
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ tokenIn: tokenIn, tokenOut: tokenOut, fee: fee, recipient: msg.sender, deadline: deadline, amountIn: amountIn, amountOutMinimum: amountOutMinimum,
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ tokenIn: tokenIn, tokenOut: tokenOut, fee: fee, recipient: msg.sender, deadline: deadline, amountIn: amountIn, amountOutMinimum: amountOutMinimum,
19,294
54
// Convert uint256 to bytes _buint256 that needs to be convertedreturnbytes/
function uint256ToBytes(uint256 _value) internal pure returns (bytes memory bs) { require(_value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range"); assembly { // Get a location of some free memory and store it in result as // Solidity does for memory variables. bs := mload(0x40) // Put 0x20 at the first word, the length of bytes for uint256 value mstore(bs, 0x20) //In the next word, put value in bytes format to the next 32 bytes mstore(add(bs, 0x20), _value) // Update the free-memory pointer by padding our last write location to 32 bytes mstore(0x40, add(bs, 0x40)) } }
function uint256ToBytes(uint256 _value) internal pure returns (bytes memory bs) { require(_value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range"); assembly { // Get a location of some free memory and store it in result as // Solidity does for memory variables. bs := mload(0x40) // Put 0x20 at the first word, the length of bytes for uint256 value mstore(bs, 0x20) //In the next word, put value in bytes format to the next 32 bytes mstore(add(bs, 0x20), _value) // Update the free-memory pointer by padding our last write location to 32 bytes mstore(0x40, add(bs, 0x40)) } }
16,937
23
// 1 SSTORE
ilks[_ilk].lastInc = uint48(block.timestamp); ilks[_ilk].last = uint48(block.number);
ilks[_ilk].lastInc = uint48(block.timestamp); ilks[_ilk].last = uint48(block.number);
40,063
135
// Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). /
function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; }
function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; }
10,700
0
// Multiplies two numbers, throws on overflow./
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) return 0; c = a * b; assert(c / a == b); return c; }
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) return 0; c = a * b; assert(c / a == b); return c; }
9,410
201
// Tell the Dapps collateral was added to loan
emit CollateralDeposited(account, loanID, msg.value, totalCollateral);
emit CollateralDeposited(account, loanID, msg.value, totalCollateral);
14,152
96
// calculate current bond price and remove floor if above return price_ uint /
function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } }
function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } }
8,660
3
// Used to validate authorized mint addresses
address private _signerAddress = 0xB44b7e7988A225F8C479cB08a63C04e0039B53Ff; uint256 public maleCooldown = 28 * 24 * 3600; uint256 public femaleCooldown = 3 * 24 * 3600;
address private _signerAddress = 0xB44b7e7988A225F8C479cB08a63C04e0039B53Ff; uint256 public maleCooldown = 28 * 24 * 3600; uint256 public femaleCooldown = 3 * 24 * 3600;
23,523
3
// Mints the given amount of LPToken to the recipient. only owner can call this mint function recipient address of account to receive the tokens amount amount of tokens to mint /
function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); }
function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); }
17,270
377
// If bid not placed, reissue current Set
core.issueInVault( address(currentSet), issueQuantity );
core.issueInVault( address(currentSet), issueQuantity );
12,438
53
// Change the expiry time for the token symbol _newExpiry new time period for token symbol expiry /
function changeExpiryLimit(uint256 _newExpiry) public onlyOwner { require(_newExpiry >= 1 days, "Expiry should greater than or equal to 1 day"); uint256 _oldExpiry = expiryLimit; expiryLimit = _newExpiry; emit LogChangeExpiryLimit(_oldExpiry, _newExpiry); }
function changeExpiryLimit(uint256 _newExpiry) public onlyOwner { require(_newExpiry >= 1 days, "Expiry should greater than or equal to 1 day"); uint256 _oldExpiry = expiryLimit; expiryLimit = _newExpiry; emit LogChangeExpiryLimit(_oldExpiry, _newExpiry); }
9,858
71
// Beneficiary address is the address that the remaining tokens will be transferred to for selfdestruct.
address payable public beneficiary;
address payable public beneficiary;
48,752
3
// Mappings for Retriving Information
mapping(uint256 => Campaign) public campaigns;
mapping(uint256 => Campaign) public campaigns;
31,247
14
// this is non revocable state
dismissed = true; emit FactoryDismiss();
dismissed = true; emit FactoryDismiss();
33,225
47
// set Booster address /
function setBooster(address _boostaddy) external onlyOwner { booster = IBooster(_boostaddy); }
function setBooster(address _boostaddy) external onlyOwner { booster = IBooster(_boostaddy); }
4,677
74
// transfer of money from beneficiary to mate owner
token.ownerOf(parent1Id).transfer(price);
token.ownerOf(parent1Id).transfer(price);
36,644
6
// constant value that does not change/returns the amount of initial tokens to display
function totalSupply() public view override returns (uint _totalSupply) { _totalSupply = __totalSupply; }
function totalSupply() public view override returns (uint _totalSupply) { _totalSupply = __totalSupply; }
1,180
10
// _dragon.dominantGenes, _dragon.recesiveGenes1, _dragon.recesiveGenes2,
_dragon.lastBirthDate, _dragon.owner );
_dragon.lastBirthDate, _dragon.owner );
18,992
24
// validate target is created from whitelisted vault factory
for (uint256 index = 0; index < _vaultFactorySet.length(); index++) { if (IInstanceRegistry(_vaultFactorySet.at(index)).isInstance(target)) { return true; }
for (uint256 index = 0; index < _vaultFactorySet.length(); index++) { if (IInstanceRegistry(_vaultFactorySet.at(index)).isInstance(target)) { return true; }
71,958
6
// Deploy the Governance Rules cloning the original core one and modify it according tothe desired functionalities/configurations sender Address of the caller minimumBlockNumber Amount of blocks for the duration of a proposal emergencyBlockNumber Amount of blocks for the duration of an EmergencyProposal emergencyStaking quorum Required quorum for a proposal to be accepted surveyMaxCap Amount of voting tokens needed to reach the max-cap on a proposal surveyMinStake The minimum of Token Staked needed to create a new Proposal. surveySingleReward The amount of Voting Tokens set as a reward to the issuer forevery Accepted Proposal paid automatically by the DFO Wallet.return mvdFunctionalitiesManager The
function deployGovernanceRules(
function deployGovernanceRules(
51,365
97
// Aqua Price Oracle smart contract
AquaPriceOracle public priceOracle; LibHoldings.HoldingsSet internal holdings; uint256 internal totalSupplyOfTokens; LibRedemptions.RedemptionsQueue redemptionsQueue;
AquaPriceOracle public priceOracle; LibHoldings.HoldingsSet internal holdings; uint256 internal totalSupplyOfTokens; LibRedemptions.RedemptionsQueue redemptionsQueue;
37,678
24
// map address => notifications count => Notification
mapping(address => mapping(uint256 => Notification)) notifications;
mapping(address => mapping(uint256 => Notification)) notifications;
20,559
7
// NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the`0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` /
function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); }
function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); }
2,947
66
// Given a bugId, it retrieves the next bugId reported by a hunter. Such bugs have not been cashed yet. hunter The address of a hunter previousBugId The id of the previous reported bug. Passing 0, it returns the first reported bug. /
function getNextBugFromHunter(address hunter, uint256 previousBugId) public view returns (bool, uint256) { if (!hunterReportedBugs[hunter].listExists()) { return (false, 0); } uint256 bugId; bool exists; (exists, bugId) = hunterReportedBugs[hunter].getAdjacent(previousBugId, NEXT); if (!exists || bugId == 0) { return (false, 0); } return (true, bugId); }
function getNextBugFromHunter(address hunter, uint256 previousBugId) public view returns (bool, uint256) { if (!hunterReportedBugs[hunter].listExists()) { return (false, 0); } uint256 bugId; bool exists; (exists, bugId) = hunterReportedBugs[hunter].getAdjacent(previousBugId, NEXT); if (!exists || bugId == 0) { return (false, 0); } return (true, bugId); }
25,890
13
// Ensures that the ERC20 token balances of this contract before and after/ the swap are equal/ TODO(igm): remove this once we get an audit/ This should NEVER get triggered, but it's better to be safe than sorry
modifier balanceUnchanged(address[] calldata _path, address _to) { // Populate initial balances for comparison later uint256[] memory _initialBalances = new uint256[](_path.length); for (uint256 i = 0; i < _path.length; i++) { _initialBalances[i] = IERC20(_path[i]).balanceOf(address(this)); } _; for (uint256 i = 0; i < _path.length - 1; i++) { uint256 newBalance = IERC20(_path[i]).balanceOf(address(this)); require( // if triangular arb, ignore _path[i] == _path[0] || _path[i] == _path[_path.length - 1] || // ensure tokens balances haven't changed newBalance == _initialBalances[i], "UbeswapMoolaRouter: tokens left over after swap" ); } // sends the final tokens to `_to` address address lastAddress = _path[_path.length - 1]; IERC20(lastAddress).safeTransfer( _to, // subtract the initial balance from this token IERC20(lastAddress).balanceOf(address(this)) - _initialBalances[_initialBalances.length - 1] ); }
modifier balanceUnchanged(address[] calldata _path, address _to) { // Populate initial balances for comparison later uint256[] memory _initialBalances = new uint256[](_path.length); for (uint256 i = 0; i < _path.length; i++) { _initialBalances[i] = IERC20(_path[i]).balanceOf(address(this)); } _; for (uint256 i = 0; i < _path.length - 1; i++) { uint256 newBalance = IERC20(_path[i]).balanceOf(address(this)); require( // if triangular arb, ignore _path[i] == _path[0] || _path[i] == _path[_path.length - 1] || // ensure tokens balances haven't changed newBalance == _initialBalances[i], "UbeswapMoolaRouter: tokens left over after swap" ); } // sends the final tokens to `_to` address address lastAddress = _path[_path.length - 1]; IERC20(lastAddress).safeTransfer( _to, // subtract the initial balance from this token IERC20(lastAddress).balanceOf(address(this)) - _initialBalances[_initialBalances.length - 1] ); }
28,124
41
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); }
require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); }
13,944
36
// One of the main constants variables to form x1, x2, and x3 is alpha, which has the following definition:alpha == (ap1ap2)^(-1)== [t^2(t^2 + h4)]^(-1)ap1 == t^2ap2 == t^2 + h4h4== hashConst4 Defining alpha helps decrease the calls to expmod, which is the most expensive operation we do.
uint256 alpha; ap1 = mulmod(t, t, FIELD_MODULUS); ap2 = addmod(ap1, hashConst4, FIELD_MODULUS); alpha = mulmod(ap1, ap2, FIELD_MODULUS); alpha = invert(alpha);
uint256 alpha; ap1 = mulmod(t, t, FIELD_MODULUS); ap2 = addmod(ap1, hashConst4, FIELD_MODULUS); alpha = mulmod(ap1, ap2, FIELD_MODULUS); alpha = invert(alpha);
5,667
252
// AirdropMintBase Limit Break, Inc. Base functionality of a contract mix-in that may optionally be used with extend ERC-721 tokens with airdrop minting capabilities. Inheriting contracts must implement `_mintToken`. /
abstract contract AirdropMintBase is MaxSupplyBase { error AirdropMint__AirdropBatchSizeMustBeGreaterThanZero(); error AirdropMint__CannotMintToZeroAddress(); error AirdropMint__MaxAirdropSupplyCannotBeSetToMaxUint256(); error AirdropMint__MaxAirdropSupplyCannotBeSetToZero(); error AirdropMint__MaxAirdropSupplyExceeded(); /// @dev The current amount of tokens mintable via airdrop. uint256 private _remainingAirdropSupply; /// @notice Owner bulk mint to airdrop. /// Throws if length of `to` array is zero. /// Throws if minting batch would exceed the max supply. function airdropMint(address[] calldata to) external { _requireCallerIsContractOwner(); uint256 batchSize = to.length; if(batchSize == 0) { revert AirdropMint__AirdropBatchSizeMustBeGreaterThanZero(); } uint256 currentMintedSupply = mintedSupply(); if(batchSize > _remainingAirdropSupply) { revert AirdropMint__MaxAirdropSupplyExceeded(); } _requireLessThanMaxSupply(currentMintedSupply + batchSize); unchecked { uint256 tokenIdToMint = currentMintedSupply + 1; _remainingAirdropSupply -= batchSize; _advanceNextTokenIdCounter(batchSize); for(uint256 i = 0; i < batchSize; ++i) { address recipient = to[i]; if(recipient == address(0)) { revert AirdropMint__CannotMintToZeroAddress(); } _mintToken(to[i], tokenIdToMint + i); } } } /// @notice Returns the remaining amount of tokens mintable via airdrop function remainingAirdropSupply() public view returns (uint256) { return _remainingAirdropSupply; } function _setMaxAirdropSupply(uint256 maxAirdropMints_) internal { if(maxAirdropMints_ == 0) { revert AirdropMint__MaxAirdropSupplyCannotBeSetToZero(); } if(maxAirdropMints_ == type(uint256).max) { revert AirdropMint__MaxAirdropSupplyCannotBeSetToMaxUint256(); } _remainingAirdropSupply = maxAirdropMints_; _initializeNextTokenIdCounter(); } }
abstract contract AirdropMintBase is MaxSupplyBase { error AirdropMint__AirdropBatchSizeMustBeGreaterThanZero(); error AirdropMint__CannotMintToZeroAddress(); error AirdropMint__MaxAirdropSupplyCannotBeSetToMaxUint256(); error AirdropMint__MaxAirdropSupplyCannotBeSetToZero(); error AirdropMint__MaxAirdropSupplyExceeded(); /// @dev The current amount of tokens mintable via airdrop. uint256 private _remainingAirdropSupply; /// @notice Owner bulk mint to airdrop. /// Throws if length of `to` array is zero. /// Throws if minting batch would exceed the max supply. function airdropMint(address[] calldata to) external { _requireCallerIsContractOwner(); uint256 batchSize = to.length; if(batchSize == 0) { revert AirdropMint__AirdropBatchSizeMustBeGreaterThanZero(); } uint256 currentMintedSupply = mintedSupply(); if(batchSize > _remainingAirdropSupply) { revert AirdropMint__MaxAirdropSupplyExceeded(); } _requireLessThanMaxSupply(currentMintedSupply + batchSize); unchecked { uint256 tokenIdToMint = currentMintedSupply + 1; _remainingAirdropSupply -= batchSize; _advanceNextTokenIdCounter(batchSize); for(uint256 i = 0; i < batchSize; ++i) { address recipient = to[i]; if(recipient == address(0)) { revert AirdropMint__CannotMintToZeroAddress(); } _mintToken(to[i], tokenIdToMint + i); } } } /// @notice Returns the remaining amount of tokens mintable via airdrop function remainingAirdropSupply() public view returns (uint256) { return _remainingAirdropSupply; } function _setMaxAirdropSupply(uint256 maxAirdropMints_) internal { if(maxAirdropMints_ == 0) { revert AirdropMint__MaxAirdropSupplyCannotBeSetToZero(); } if(maxAirdropMints_ == type(uint256).max) { revert AirdropMint__MaxAirdropSupplyCannotBeSetToMaxUint256(); } _remainingAirdropSupply = maxAirdropMints_; _initializeNextTokenIdCounter(); } }
12,742
258
// Add DIGG and wBTC as liquidity if any to add
_add_max_liquidity_sushiswap(digg, wbtc);
_add_max_liquidity_sushiswap(digg, wbtc);
39,046
37
// make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocksdo this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
challengeNumber = block.blockhash(block.number - 1);
11,097
14
// Total supply of staked token
uint256 public stakedSupply;
uint256 public stakedSupply;
25,032
72
// Stores a value to an address' storage slot.
function store(address target, bytes32 slot, bytes32 value) external;
function store(address target, bytes32 slot, bytes32 value) external;
30,889
36
// Sets the RariGovernanceToken distributed by ths RariGovernanceTokenDistributor. governanceToken The new RariGovernanceToken contract. /
function setGovernanceToken(RariGovernanceToken governanceToken) external onlyOwner { require(address(governanceToken) != address(0), "New governance token contract cannot be the zero address."); rariGovernanceToken = governanceToken; }
function setGovernanceToken(RariGovernanceToken governanceToken) external onlyOwner { require(address(governanceToken) != address(0), "New governance token contract cannot be the zero address."); rariGovernanceToken = governanceToken; }
42,093
4
// 판매 정보
struct PartSale { // 판매자 address seller; // 부품 ID uint256 partId; // 가격 uint256 price; }
struct PartSale { // 판매자 address seller; // 부품 ID uint256 partId; // 가격 uint256 price; }
21,283
18
// CONSTANTS //Name and symbol of the non-fungible token, as defined in ERC721./
string public constant NAME = "CryptoLibraries"; // solhint-disable-line
string public constant NAME = "CryptoLibraries"; // solhint-disable-line
40,895
268
// Emitted whenever Limit orders are cancelled by pair by a maker./maker The maker of the order./makerToken The maker token in a pair for the orders cancelled./takerToken The taker token in a pair for the orders cancelled./minValidSalt The new minimum valid salt an order with this pair must/have.
event PairCancelledLimitOrders( address maker, address makerToken, address takerToken, uint256 minValidSalt );
event PairCancelledLimitOrders( address maker, address makerToken, address takerToken, uint256 minValidSalt );
19,505
11
// Called when a swap with the Pool occurs, where the amount of tokens exiting the Pool is known. Returns the amount of tokens that will be granted to the Pool in return. All amounts inside `swapRequest`, `balanceTokenIn` and `balanceTokenOut` are upscaled. The return value is also considered upscaled, and will be downscaled (rounding up) before applying the swap feeand returning it to the Vault. /
function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut
function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 balanceTokenIn, uint256 balanceTokenOut
17,962
3
// list an nft
function addListing(address nft, uint256 price, uint256 id) public onlyOwner { erc721 = IERC721(nft); // require = owner of, isApprovedFoAll listing[address(erc721)][id] = List(price, msg.sender); emit ListingNft(nft, id, msg.sender, price, block.timestamp); }
function addListing(address nft, uint256 price, uint256 id) public onlyOwner { erc721 = IERC721(nft); // require = owner of, isApprovedFoAll listing[address(erc721)][id] = List(price, msg.sender); emit ListingNft(nft, id, msg.sender, price, block.timestamp); }
22,174
2
// timestamp of last report, used for locked profit calculations
uint256 public lastReport;
uint256 public lastReport;
24,082
83
// avoid burn by calling super._transfer directly
super._transfer(address(this), uniswapV2Pair, liquidityRewards); IUniswapV2Pair(uniswapV2Pair).sync(); emit RewardLiquidityProviders(liquidityRewards);
super._transfer(address(this), uniswapV2Pair, liquidityRewards); IUniswapV2Pair(uniswapV2Pair).sync(); emit RewardLiquidityProviders(liquidityRewards);
4,129
213
// don't bother withdrawing if we don't have staked funds
proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _debtOutstanding) );
proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _debtOutstanding) );
8,206
5
// Calculates floor(x << offset / y) with full precisionThe result will be rounded downRequirements:- The offset needs to be strictly lower than 256- The result must fit within uint256Caveats:- This function does not work with fixed-point numbers x The multiplicand as an uint256 offset The number of bit to shift x as an uint256 denominator The divisor as an uint256return result The result as an uint256 /
function shiftDivRoundDown(uint256 x, uint8 offset, uint256 denominator) internal pure returns (uint256 result) { uint256 prod0; uint256 prod1; prod0 = x << offset; // Least significant 256 bits of the product unchecked { prod1 = x >> (256 - offset); // Most significant 256 bits of the product } return _getEndOfDivRoundDown(x, 1 << offset, denominator, prod0, prod1); }
function shiftDivRoundDown(uint256 x, uint8 offset, uint256 denominator) internal pure returns (uint256 result) { uint256 prod0; uint256 prod1; prod0 = x << offset; // Least significant 256 bits of the product unchecked { prod1 = x >> (256 - offset); // Most significant 256 bits of the product } return _getEndOfDivRoundDown(x, 1 << offset, denominator, prod0, prod1); }
28,809
205
// 4. Update total loan and next interest rate
totalLoan_ += interest; totalLoan = totalLoan_; interestRate = model.getNextInterestRate(interestRate_, totalLoanable_, totalLoan_, timePassed);
totalLoan_ += interest; totalLoan = totalLoan_; interestRate = model.getNextInterestRate(interestRate_, totalLoanable_, totalLoan_, timePassed);
40,505
132
// Update current balances by subtracting the protocol fee amounts
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData);
_mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData);
4,910
6
// Percentage to send to Dividend Payer contract
uint256 pDiv = div * onePercent;
uint256 pDiv = div * onePercent;
38,062
177
// Emitted when a transaction is relayed. Useful when monitoring a relay's operation and relayed calls to a contract Note that the actual encoded function might be reverted: this is indicated in the `status` parameter. `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner. /
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
43,361
2
// upvotes a file, decreasing its vote count, votes are helpful in ranking and filtering on the front endipfsHash bytes32 return details[ipfshash].vote which will be the current vote count/
function downVote(bytes32 ipfsHash) public returns (int) { details[ipfsHash].vote -= 1; emit Vote(msg.sender, ipfsHash, details[ipfsHash].vote); return details[ipfsHash].vote; }
function downVote(bytes32 ipfsHash) public returns (int) { details[ipfsHash].vote -= 1; emit Vote(msg.sender, ipfsHash, details[ipfsHash].vote); return details[ipfsHash].vote; }
60
25
// The hub must have committed to this state update
if (lrDeltasPassiveMark[1][0] != 0 || lrDeltasPassiveMark[1][1] != 0) { verifyProofOfActiveStateUpdateAgreement( token, msg.sender, trail, previousEon, rsTxSetRoot[2], lrDeltasPassiveMark[1], operator, rsTxSetRoot[0], rsTxSetRoot[1], v);
if (lrDeltasPassiveMark[1][0] != 0 || lrDeltasPassiveMark[1][1] != 0) { verifyProofOfActiveStateUpdateAgreement( token, msg.sender, trail, previousEon, rsTxSetRoot[2], lrDeltasPassiveMark[1], operator, rsTxSetRoot[0], rsTxSetRoot[1], v);
27,251
7
// Mapping (oracleId => oracle owner).
mapping(uint64 => address) private oracleOwnersMap;
mapping(uint64 => address) private oracleOwnersMap;
17,689
23
// 10 mln
uint public constant TOTAL_TOKEN_SUPPLY = 10000000 * (1 ether / 1 wei);
uint public constant TOTAL_TOKEN_SUPPLY = 10000000 * (1 ether / 1 wei);
8,479
110
// Lock Tokens for Reserved
function lockUbxtTokens(uint256 _amount) public onlyOwner { require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), _amount), 'UBXTStaking: transfer into locked pool failed'); }
function lockUbxtTokens(uint256 _amount) public onlyOwner { require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), _amount), 'UBXTStaking: transfer into locked pool failed'); }
19,069
6
// Setters for Gov to set system params
function setSwapFee(uint256 _swapFee) external;
function setSwapFee(uint256 _swapFee) external;
10,305
32
// Assign tokens to the investor
if(msg.sender == walletAddresses[0] || msg.sender == walletAddresses[1]){ walletAngelPESales[_investor] = safeAdd(walletAngelPESales[_investor],_tokens); }
if(msg.sender == walletAddresses[0] || msg.sender == walletAddresses[1]){ walletAngelPESales[_investor] = safeAdd(walletAngelPESales[_investor],_tokens); }
22,224
121
// Liquidity Provider Utility Functions ///
function updateDepositDate(mapping(address => uint256) storage depositDate, uint256 balance, uint256 amt, address account) internal { uint256 prevDate = depositDate[account]; // prevDate + (now - prevDate) * (amt / (balance + amt)) // NOTE: prevDate = 0 implies balance = 0, and equation reduces to now uint256 newDate = (balance + amt) > 0 ? prevDate.add(block.timestamp.sub(prevDate).mul(amt).div(balance + amt)) : prevDate; depositDate[account] = newDate; emit DepositDateUpdated(account, newDate); }
function updateDepositDate(mapping(address => uint256) storage depositDate, uint256 balance, uint256 amt, address account) internal { uint256 prevDate = depositDate[account]; // prevDate + (now - prevDate) * (amt / (balance + amt)) // NOTE: prevDate = 0 implies balance = 0, and equation reduces to now uint256 newDate = (balance + amt) > 0 ? prevDate.add(block.timestamp.sub(prevDate).mul(amt).div(balance + amt)) : prevDate; depositDate[account] = newDate; emit DepositDateUpdated(account, newDate); }
60,205
81
// Gets the list of token IDs of the requested owner.owner address owning the tokens return uint256[] List of token IDs owned by the requested address/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; }
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; }
85,894
80
// This sets the start date to the end date of the previous round
fundingPhases_[currentPhase_].startDate = block.timestamp .add(remaining);
fundingPhases_[currentPhase_].startDate = block.timestamp .add(remaining);
25,922
26
// allow another account/contract to spend some tokens on your behalf throws on any error rather then return a false flag to minimize user errorsalso, to minimize the risk of the approve/transferFrom attack vector in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value _spender approved address_value allowance amountreturn true if the approval was successful, false if it wasn't/
function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success)
function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success)
75,868
96
// function to performs staking for user tokens for a specific period of time
function performStaking(uint256 tokens, uint256 time) public validatorForStaking(tokens, time) returns(bool){ _stakingCount = _stakingCount +1 ; _stakerAddress[_stakingCount] = msg.sender; _stakingEndTime[_stakingCount] = time; _stakingStartTime[_stakingCount] = now; _usersTokens[_stakingCount] = tokens; _TokenTransactionstatus[_stakingCount] = false; _transfer(msg.sender, _tokenPoolAddress, tokens); return true; }
function performStaking(uint256 tokens, uint256 time) public validatorForStaking(tokens, time) returns(bool){ _stakingCount = _stakingCount +1 ; _stakerAddress[_stakingCount] = msg.sender; _stakingEndTime[_stakingCount] = time; _stakingStartTime[_stakingCount] = now; _usersTokens[_stakingCount] = tokens; _TokenTransactionstatus[_stakingCount] = false; _transfer(msg.sender, _tokenPoolAddress, tokens); return true; }
17,832
9
// 记录retailer的资料
function goods(bytes memory rid, bytes32 rname, bytes32 rloc, bytes32 rpro, uint rcon, uint rpr) public { SupplyChain.retailer memory rnew = retailer(rid, rname, rloc, rpro, rcon, rpr); r1[rid] = rnew; rt.push(rnew); r++; }
function goods(bytes memory rid, bytes32 rname, bytes32 rloc, bytes32 rpro, uint rcon, uint rpr) public { SupplyChain.retailer memory rnew = retailer(rid, rname, rloc, rpro, rcon, rpr); r1[rid] = rnew; rt.push(rnew); r++; }
11,939
1
// Accounting mechanism. Prevents double-redeeming rewards in the same block.
uint256 rewardDebt;
uint256 rewardDebt;
21,797
213
// Gets the remaining supply of tickets
function remainingSupply() public view returns (uint16) { // may happen if we later change the supply to a lower value if (sold >= supply) { return 0; } return supply - sold; }
function remainingSupply() public view returns (uint16) { // may happen if we later change the supply to a lower value if (sold >= supply) { return 0; } return supply - sold; }
46,329
181
// Relays a transaction. For this to succeed, multiple conditions must be met:/- Paymaster's "preRelayCall" method must succeed and not revert/- the sender must be a registered Relay Worker that the user signed/- the transaction's gas price must be equal or larger than the one that was signed by the sender/- the transaction must have enough gas to run all internal transactions if they use all gas available to them/- the Paymaster must have enough balance to pay the Relay Worker for the scenario when all gas is spent// If all conditions are met, the call will be relayed and the
function relayCall( uint maxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint externalGasLimit ) external returns (bool paymasterAccepted, bytes memory returnValue);
function relayCall( uint maxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint externalGasLimit ) external returns (bool paymasterAccepted, bytes memory returnValue);
9,963
251
// checks that finish date is not reached yet(and potentially start date, but not needed for presale)AND also that the limits for the sale are not metAND that current price is non-zero (updated) /
modifier checkLimitsAndDates() { require((c_dateTo >= getTime()) && (m_currentTokensSold < c_maximumTokensSold) && (m_ETHPriceInCents > 0)); _; }
modifier checkLimitsAndDates() { require((c_dateTo >= getTime()) && (m_currentTokensSold < c_maximumTokensSold) && (m_ETHPriceInCents > 0)); _; }
43,218
113
// Timestamp for the last time taxes were deducted from a user&39;s account
mapping(address => uint256) public lastPaidTaxes;
mapping(address => uint256) public lastPaidTaxes;
20,033
190
// Retrieves the average balances held by a user for a given time frame. user The user whose balance is checked. startTimes The start time of the time frame. endTimes The end time of the time frame.return The average balance that the user held during the time frame. /
function getAverageBalancesBetween(
function getAverageBalancesBetween(
49,755
19
// set questTerminalKeyContract address/questTerminalKeyContract_ The address of the questTerminalKeyContract
function setQuestTerminalKeyContract(address questTerminalKeyContract_) external onlyOwner { questTerminalKeyContract = QuestTerminalKey(questTerminalKeyContract_); }
function setQuestTerminalKeyContract(address questTerminalKeyContract_) external onlyOwner { questTerminalKeyContract = QuestTerminalKey(questTerminalKeyContract_); }
21,654
30
// 'replace' flag set means that owner wants to replace the value, if it is not set and key doesn't exist in the database false status should be returned and database shouldn't be changed.
if (replace) {
if (replace) {
24,256
180
// Pausing bools
bool public rebasePaused = false; bool public capitalPaused = true;
bool public rebasePaused = false; bool public capitalPaused = true;
67,802
22
// deploy logic contract to serve as initial implementation for each proxy.
_targetImplementation = address(new InitialProxyImplementation());
_targetImplementation = address(new InitialProxyImplementation());
11,494
21
// Make sure the nonce is higher
require(_channel.nonce < nonce); require(msg.sender == _channel.sender || msg.sender == _channel.recipient); address signer = ecrecover(h[1], v, h[2], h[3]); require(signer == _channel.sender);
require(_channel.nonce < nonce); require(msg.sender == _channel.sender || msg.sender == _channel.recipient); address signer = ecrecover(h[1], v, h[2], h[3]); require(signer == _channel.sender);
7,633
40
// Set L2 TransferRoot
bytes memory setTransferRootMessage = abi.encodeWithSignature( "setTransferRoot(bytes32,uint256)", rootHash, totalAmount ); messengerWrapper.sendCrossDomainMessage(setTransferRootMessage);
bytes memory setTransferRootMessage = abi.encodeWithSignature( "setTransferRoot(bytes32,uint256)", rootHash, totalAmount ); messengerWrapper.sendCrossDomainMessage(setTransferRootMessage);
50,551
11
// Spec: Returns the amount which _spender is still allowed to withdrawfrom _owner. What if the allowance is higher than the balance of the owner?Callers should be careful to use min(allowance, balanceOf) to make sure that the allowance is actually present in the account!
function allowance(address, uint256 _msg_value, address _owner, address _spender) public constant returns (uint256[2] success) { if (_msg_value != 0) { return ([uint256(0), 0]); } return ([uint256(1), allowances[_owner][_spender]]); }
function allowance(address, uint256 _msg_value, address _owner, address _spender) public constant returns (uint256[2] success) { if (_msg_value != 0) { return ([uint256(0), 0]); } return ([uint256(1), allowances[_owner][_spender]]); }
14,971
33
// calculate the holders cut
uint holderCut = challenge.balance.mul(stakeholderProportionPPM).div(MILLION); challenge.voterTotal = challenge.balance.sub(holderCut); if (winningOption == 1) { challenge.passed = true; challenge.finalized = true;
uint holderCut = challenge.balance.mul(stakeholderProportionPPM).div(MILLION); challenge.voterTotal = challenge.balance.sub(holderCut); if (winningOption == 1) { challenge.passed = true; challenge.finalized = true;
47,263
8
// uint256 referals;number of referrals
address refL1; // 5) L1 referral 3% address refL2; // 6) L2 referral 2% address refL3; // 7) L3 referral 1% Building[24] myBuildings; // 8) user's buildings uint256 myHero; // 9) user's hero uint256 battleId; // 10) active battle
address refL1; // 5) L1 referral 3% address refL2; // 6) L2 referral 2% address refL3; // 7) L3 referral 1% Building[24] myBuildings; // 8) user's buildings uint256 myHero; // 9) user's hero uint256 battleId; // 10) active battle
27,853
132
// Checks if elements in array are ordered and unique /
function isOrderedSet(uint256[] memory numbers) internal pure returns (bool)
function isOrderedSet(uint256[] memory numbers) internal pure returns (bool)
28,435
205
// If over 30 mins, extrapolate APY e.g. day: (864001e18) / 3.154e7 = 2.74..e15 e.g. 30 mins: (18001e18) / 3.154e7 = 5.7..e13 e.g. epoch: (15935969071e18) / 3.154e7 = 50.4..e18
uint256 yearsSinceLastCollection = _timeSinceLastCollection.divPrecisely(SECONDS_IN_YEAR);
uint256 yearsSinceLastCollection = _timeSinceLastCollection.divPrecisely(SECONDS_IN_YEAR);
39,090
9
// check price
int betakey_price = calcBetaPrice(_betaType); int betakey_price_final = betakey_price * 10 ** 14; // 14 because betakey_price * 10 ** 18 / 10000 ==> betakey_price * 10 ** 14
int betakey_price = calcBetaPrice(_betaType); int betakey_price_final = betakey_price * 10 ** 14; // 14 because betakey_price * 10 ** 18 / 10000 ==> betakey_price * 10 ** 14
26,235
8
// the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
uint8 id;
26,464
219
// ´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.://HOOKS FOR OVERRIDING//.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•//Hook that is called before any token transfers, including minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 id) internal virtual {} /// @dev Hook that is called after any token transfers, including minting and burning. function _afterTokenTransfer(address from, address to, uint256 id) internal virtual {} /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* PRIVATE HELPERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns if `a` has bytecode of non-zero length. function _hasCode(address a) private view returns (bool result) { /// @solidity memory-safe-assembly assembly { result := extcodesize(a) // Can handle dirty upper bits. } }
function _beforeTokenTransfer(address from, address to, uint256 id) internal virtual {} /// @dev Hook that is called after any token transfers, including minting and burning. function _afterTokenTransfer(address from, address to, uint256 id) internal virtual {} /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* PRIVATE HELPERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns if `a` has bytecode of non-zero length. function _hasCode(address a) private view returns (bool result) { /// @solidity memory-safe-assembly assembly { result := extcodesize(a) // Can handle dirty upper bits. } }
21,928
206
// finalize the stake and pay interest or charge penalty accordingly arrayIndex: is the id of the stake to be finalized
function withdrawStake(uint256 arrayIndex) external nonReentrant { // Stake should exists and opened require(arrayIndex < stakesOfOwner[msg.sender].length, "Stake does not exist"); require(stakesOfOwner[msg.sender][arrayIndex].closed==false, "This stake is closed"); // charge penalty if below minimum stake time if(block.timestamp.sub(stakesOfOwner[msg.sender][arrayIndex].startDate) < minimumStakeTime){ // calculate penalty = amount * penalty / 100 uint256 the_penalty = stakesOfOwner[msg.sender][arrayIndex].amount.mul(penalty).div(100); // remaining amount= amount - penaty uint256 amountToWithdraw = stakesOfOwner[msg.sender][arrayIndex].amount.sub(the_penalty); // transfer remaining token_to_pay.transfer(msg.sender, amountToWithdraw); // penalty funds are hold by the contract, but keep the account of how much is it here collectedPenalty = collectedPenalty.add(the_penalty); // store the results in the stakes array of the user stakesOfOwner[msg.sender][arrayIndex].penalty = the_penalty; stakesOfOwner[msg.sender][arrayIndex].finishedDate = block.timestamp; stakesOfOwner[msg.sender][arrayIndex].closed = true; // pay interest if above or equal minimum stake time }else{ // get the interest uint256 interest = calculateInterest(msg.sender, arrayIndex); // transfer the interest from owner account, it has to have enough funds approved token_to_pay.transferFrom(contract_owner, msg.sender, interest); // transfer the amount from the contract itself token_to_pay.transfer(msg.sender, stakesOfOwner[msg.sender][arrayIndex].amount); // record the transaction stakesOfOwner[msg.sender][arrayIndex].interest = interest; stakesOfOwner[msg.sender][arrayIndex].finishedDate = block.timestamp; stakesOfOwner[msg.sender][arrayIndex].closed = true; } emit stakeWithdrew(arrayIndex); }
function withdrawStake(uint256 arrayIndex) external nonReentrant { // Stake should exists and opened require(arrayIndex < stakesOfOwner[msg.sender].length, "Stake does not exist"); require(stakesOfOwner[msg.sender][arrayIndex].closed==false, "This stake is closed"); // charge penalty if below minimum stake time if(block.timestamp.sub(stakesOfOwner[msg.sender][arrayIndex].startDate) < minimumStakeTime){ // calculate penalty = amount * penalty / 100 uint256 the_penalty = stakesOfOwner[msg.sender][arrayIndex].amount.mul(penalty).div(100); // remaining amount= amount - penaty uint256 amountToWithdraw = stakesOfOwner[msg.sender][arrayIndex].amount.sub(the_penalty); // transfer remaining token_to_pay.transfer(msg.sender, amountToWithdraw); // penalty funds are hold by the contract, but keep the account of how much is it here collectedPenalty = collectedPenalty.add(the_penalty); // store the results in the stakes array of the user stakesOfOwner[msg.sender][arrayIndex].penalty = the_penalty; stakesOfOwner[msg.sender][arrayIndex].finishedDate = block.timestamp; stakesOfOwner[msg.sender][arrayIndex].closed = true; // pay interest if above or equal minimum stake time }else{ // get the interest uint256 interest = calculateInterest(msg.sender, arrayIndex); // transfer the interest from owner account, it has to have enough funds approved token_to_pay.transferFrom(contract_owner, msg.sender, interest); // transfer the amount from the contract itself token_to_pay.transfer(msg.sender, stakesOfOwner[msg.sender][arrayIndex].amount); // record the transaction stakesOfOwner[msg.sender][arrayIndex].interest = interest; stakesOfOwner[msg.sender][arrayIndex].finishedDate = block.timestamp; stakesOfOwner[msg.sender][arrayIndex].closed = true; } emit stakeWithdrew(arrayIndex); }
36,385
90
// transfer balance to owner
function withdrawEther(uint256 amount) public { require(msg.sender == owner); owner.transfer(amount); }
function withdrawEther(uint256 amount) public { require(msg.sender == owner); owner.transfer(amount); }
28,505
26
// Called once when the colony is created to initialise certain storage slot values/Sets the reward inverse to the uint max 2256 - 1/_address Address of the colony network
function initialiseColony(address _address) public;
function initialiseColony(address _address) public;
6,189
34
// Emit the debenture approval event
emit MDebenture(msg.sender, _debentureAmount);
emit MDebenture(msg.sender, _debentureAmount);
33,490
107
// buyer dekla should be greater than 0
require(amount > 0);
require(amount > 0);
31,726
71
// 增加流动性,管理员调用
function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin,
function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin,
33,879
10
// we don't have slug for this collection contract
addressToCallInfoMap[_collectionAddress] = CallInfo(0, 0, _callback); bytes32 result = requestOpenSeaCollectionSlug(_collectionAddress); addressToCallInfoMap[_collectionAddress].slugRequestId = result;
addressToCallInfoMap[_collectionAddress] = CallInfo(0, 0, _callback); bytes32 result = requestOpenSeaCollectionSlug(_collectionAddress); addressToCallInfoMap[_collectionAddress].slugRequestId = result;
7,402
84
// Darknodes are stored in the darknode struct. The owner is the/ address that registered the darknode, the bond is the amount of REN that/ was transferred during registration, and the public key is the/ encryption key that should be used when sending sensitive information to/ the darknode.
struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; }
struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; }
8,301
21
// Creates a wrapped asset using AssetMeta
function _createWrapped(uint16 tokenChain, bytes32 tokenAddress, bytes32 name, bytes32 symbol) internal returns (address token) { require(tokenChain != chainId(), "can only wrap tokens from foreign chains"); require(wrappedAsset(tokenChain, tokenAddress) == address(0), "wrapped asset already exists"); // initialize the NFTImplementation bytes memory initialisationArgs = abi.encodeWithSelector( NFTImplementation.initialize.selector, bytes32ToString(name), bytes32ToString(symbol), address(this), tokenChain, tokenAddress ); // initialize the BeaconProxy bytes memory constructorArgs = abi.encode(address(this), initialisationArgs); // deployment code bytes memory bytecode = abi.encodePacked(type(BridgeNFT).creationCode, constructorArgs); bytes32 salt = keccak256(abi.encodePacked(tokenChain, tokenAddress)); assembly { token := create2(0, add(bytecode, 0x20), mload(bytecode), salt) if iszero(extcodesize(token)) { revert(0, 0) } } _setWrappedAsset(tokenChain, tokenAddress, token); }
function _createWrapped(uint16 tokenChain, bytes32 tokenAddress, bytes32 name, bytes32 symbol) internal returns (address token) { require(tokenChain != chainId(), "can only wrap tokens from foreign chains"); require(wrappedAsset(tokenChain, tokenAddress) == address(0), "wrapped asset already exists"); // initialize the NFTImplementation bytes memory initialisationArgs = abi.encodeWithSelector( NFTImplementation.initialize.selector, bytes32ToString(name), bytes32ToString(symbol), address(this), tokenChain, tokenAddress ); // initialize the BeaconProxy bytes memory constructorArgs = abi.encode(address(this), initialisationArgs); // deployment code bytes memory bytecode = abi.encodePacked(type(BridgeNFT).creationCode, constructorArgs); bytes32 salt = keccak256(abi.encodePacked(tokenChain, tokenAddress)); assembly { token := create2(0, add(bytecode, 0x20), mload(bytecode), salt) if iszero(extcodesize(token)) { revert(0, 0) } } _setWrappedAsset(tokenChain, tokenAddress, token); }
15,441
7
// So we can enumerate them
uint256 public totalTokens = 0; mapping(uint256 => uint256) public indexToTokenId; mapping(uint256 => uint256) public tokenIdToStreamId; constructor( IERC721Full _tokenContract, // How to make this generic to not accept a token at construction IERC20 _paymentToken, // DAI ... or even zkDAI ? IERC1620 _stream
uint256 public totalTokens = 0; mapping(uint256 => uint256) public indexToTokenId; mapping(uint256 => uint256) public tokenIdToStreamId; constructor( IERC721Full _tokenContract, // How to make this generic to not accept a token at construction IERC20 _paymentToken, // DAI ... or even zkDAI ? IERC1620 _stream
15,816
193
// Remember the initial block number // Short-circuit accumulating 0 interest // Read the previous values out of storage // Calculate the current borrow interest rate // Calculate the number of blocks elapsed since the last accrual //Calculate the interest accumulated into borrows and reserves and the new index: simpleInterestFactor = borrowRateblockDelta interestAccumulated = simpleInterestFactortotalBorrows totalBorrowsNew = interestAccumulated + totalBorrows totalReservesNew = interestAccumulatedreserveFactor + totalReserves borrowIndexNew = simpleInterestFactorborrowIndex + borrowIndex /
Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew;
Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew;
13,612
59
// Mapping of asset to path
mapping(address => address[]) public pathes;
mapping(address => address[]) public pathes;
31,599
26
// pre-tge variables
uint8 public basicRate = 100; uint8 public preTgeBonus = 45; address public preTgeManager; address public multisigWallet; bool public isClosed = false;
uint8 public basicRate = 100; uint8 public preTgeBonus = 45; address public preTgeManager; address public multisigWallet; bool public isClosed = false;
37,842
196
// Get status for a specific loanWe rely on correct implementation of LoanToken id Loan IDreturn Status of loan /
function status(address id) public view returns (LoanStatus) { Loan storage loan = loans[id]; // Void loan doesn't exist because timestamp is zero if (loan.creator == address(0) && loan.timestamp == 0) { return LoanStatus.Void; } // Retracted loan was cancelled by borrower if (loan.creator == address(0) && loan.timestamp != 0) { return LoanStatus.Retracted; } // get internal status ILoanToken2.Status loanInternalStatus = ILoanToken2(id).status(); // Running is Funded || Withdrawn if (loanInternalStatus == ILoanToken2.Status.Funded || loanInternalStatus == ILoanToken2.Status.Withdrawn) { return LoanStatus.Running; } // Settled has been paid back in full and past term if (loanInternalStatus == ILoanToken2.Status.Settled) { return LoanStatus.Settled; } // Defaulted has not been paid back in full and past term if (loanInternalStatus == ILoanToken2.Status.Defaulted) { return LoanStatus.Defaulted; } // Liquidated is same as defaulted and stakers have been liquidated if (loanInternalStatus == ILoanToken2.Status.Liquidated) { return LoanStatus.Liquidated; } // otherwise return Pending return LoanStatus.Pending; }
function status(address id) public view returns (LoanStatus) { Loan storage loan = loans[id]; // Void loan doesn't exist because timestamp is zero if (loan.creator == address(0) && loan.timestamp == 0) { return LoanStatus.Void; } // Retracted loan was cancelled by borrower if (loan.creator == address(0) && loan.timestamp != 0) { return LoanStatus.Retracted; } // get internal status ILoanToken2.Status loanInternalStatus = ILoanToken2(id).status(); // Running is Funded || Withdrawn if (loanInternalStatus == ILoanToken2.Status.Funded || loanInternalStatus == ILoanToken2.Status.Withdrawn) { return LoanStatus.Running; } // Settled has been paid back in full and past term if (loanInternalStatus == ILoanToken2.Status.Settled) { return LoanStatus.Settled; } // Defaulted has not been paid back in full and past term if (loanInternalStatus == ILoanToken2.Status.Defaulted) { return LoanStatus.Defaulted; } // Liquidated is same as defaulted and stakers have been liquidated if (loanInternalStatus == ILoanToken2.Status.Liquidated) { return LoanStatus.Liquidated; } // otherwise return Pending return LoanStatus.Pending; }
13,859