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
// Maximum ratio of output tokens to balance for swaps.
uint256 internal constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
uint256 internal constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
4,295
27
// version 1.0.0
return "1.0.0";
return "1.0.0";
16,352
560
// Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, thesignature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thuschange through time. It could return true at block N and false at block N+1 (or the opposite). /
function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature
function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature
11,412
314
// Note: we ignore error here and call this token insufficient cash
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED);
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED);
3,723
104
// Guarrentees that contract is not in paused state /
modifier onlyWhenNotPaused() { require(!paused, "contract is currently in paused state"); _; }
modifier onlyWhenNotPaused() { require(!paused, "contract is currently in paused state"); _; }
8,212
22
// This will deposit AVAX to Contract /
function depositCrypto() payable public returns (bool){ uint256 amount = msg.value; address userAddress = msg.sender; emit AvaxDeposited(userAddress, amount); return true; }
function depositCrypto() payable public returns (bool){ uint256 amount = msg.value; address userAddress = msg.sender; emit AvaxDeposited(userAddress, amount); return true; }
10,239
0
// Supply, limits and fees
uint256 private constant REWARDS_TRACKER_IDENTIFIER = 1; uint256 private constant TOTAL_SUPPLY = 100000000000000 * (10**9); uint256 public maxTxAmount = TOTAL_SUPPLY.mul(2).div(1000); // 2% uint256 private platformFee = 75; // 0.75% uint256 private _previousPlatformFee = platformFee; uint256 public devFee = 500; // 5% uint256 private _previousDevFee = devFee;
uint256 private constant REWARDS_TRACKER_IDENTIFIER = 1; uint256 private constant TOTAL_SUPPLY = 100000000000000 * (10**9); uint256 public maxTxAmount = TOTAL_SUPPLY.mul(2).div(1000); // 2% uint256 private platformFee = 75; // 0.75% uint256 private _previousPlatformFee = platformFee; uint256 public devFee = 500; // 5% uint256 private _previousDevFee = devFee;
13,815
70
// Gets the amount of xHORUS in existence
uint256 totalShares = totalSupply();
uint256 totalShares = totalSupply();
7,468
8
// The Owned contract A contract with helpers for basic contract ownership. /
contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() public { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } }
contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() public { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } }
40,841
35
// 5% team
balances[team] = 50000000 ether; state = State.Active; emit Transfer(address(0), msg.sender, balances[msg.sender]); emit Transfer(address(0), merchants, balances[merchants]); emit Transfer(address(0), team, balances[team]);
balances[team] = 50000000 ether; state = State.Active; emit Transfer(address(0), msg.sender, balances[msg.sender]); emit Transfer(address(0), merchants, balances[merchants]); emit Transfer(address(0), team, balances[team]);
73,811
57
// Increase the amount of tokens that an owner allowed to a spender.approve should be called when allowed_[_spender] == 0. To incrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.solEmits an Approval event. spender The address which will spend the funds. addedValue The amount of tokens to increase the allowance by. /
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; }
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; }
8,673
25
// Make sure we send and report the exact same amount of tokens by using balanceOf.
actualAmount = strategyToken.balanceOf(address(this)); strategyToken.safeTransfer(address(bentoBox), actualAmount);
actualAmount = strategyToken.balanceOf(address(this)); strategyToken.safeTransfer(address(bentoBox), actualAmount);
27,254
35
// Records the player data. /
function playerDataRecord(uint256 _rId, uint256 _sId, uint256 _totalAmount, uint256 _stageBuyAmount, uint256 _stepSize, uint256 _protectRatio, uint256 _crossStageNum) private
function playerDataRecord(uint256 _rId, uint256 _sId, uint256 _totalAmount, uint256 _stageBuyAmount, uint256 _stepSize, uint256 _protectRatio, uint256 _crossStageNum) private
44,139
25
// A mapping from token ID to index of the ownerTokens' tokens list. /
mapping(uint => uint) tokenIdToOwnerTokensIndex;
mapping(uint => uint) tokenIdToOwnerTokensIndex;
77,145
32
// Mints gd while the interest amount is equal to the transferred amount
(uint256 gdInterest, uint256 gdUBI) = reserve.mintInterestAndUBI( cDai, interest, afterDonation );
(uint256 gdInterest, uint256 gdUBI) = reserve.mintInterestAndUBI( cDai, interest, afterDonation );
22,723
29
// Rescue ERC721 assets sent directly to this contract. /
function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId); }
function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId); }
29,463
16
// iNFT binding storage, stores binding information for each existing iNFT Maps iNFT ID to its binding data, which includes underlying NFT data /
mapping(uint256 => IntelliBinding) public bindings;
mapping(uint256 => IntelliBinding) public bindings;
40,468
33
// fee checkmaker fee
if(ordersBook[makeOrder[0]].flag == 2){ if(addresses[2] == ordersBook[makeOrder[0]].tokenAddress) //Maker fee same as maker token require(user[ordersBook[makeOrder[0]].userAddress].userBalance[ordersBook[makeOrder[0]].tokenAddress] >= (tradeM.add(makeOrder[6])), "maker insufficient fee percentage balance and trade token balance"); else require(user[ordersBook[makeOrder[0]].userAddress].userBalance[addresses[2]] >= makeOrder[6], "maker insufficient percentage fee balance"); }
if(ordersBook[makeOrder[0]].flag == 2){ if(addresses[2] == ordersBook[makeOrder[0]].tokenAddress) //Maker fee same as maker token require(user[ordersBook[makeOrder[0]].userAddress].userBalance[ordersBook[makeOrder[0]].tokenAddress] >= (tradeM.add(makeOrder[6])), "maker insufficient fee percentage balance and trade token balance"); else require(user[ordersBook[makeOrder[0]].userAddress].userBalance[addresses[2]] >= makeOrder[6], "maker insufficient percentage fee balance"); }
16,863
36
// Set the Curve 3 pool address/_pool New pool address
function setCurve3Pool(address _pool) external onlyDao { curve3Pool = _pool; }
function setCurve3Pool(address _pool) external onlyDao { curve3Pool = _pool; }
18,874
1
// Public minting function; only the owner may call.to The token's owner. tokenId The token ID. tokenUri The URI for the token's metadata. /
function mint(address to, uint256 tokenId, string memory tokenUri) public onlyOwner{ super._safeMint(to, tokenId); super._setTokenURI(tokenId, tokenUri); }
function mint(address to, uint256 tokenId, string memory tokenUri) public onlyOwner{ super._safeMint(to, tokenId); super._setTokenURI(tokenId, tokenUri); }
16,856
9
// claims tokens held by time lock /
function claim() public { require(now >= startDay); var elem = allocations[msg.sender]; require(elem.numPayoutCycles > 0); uint256 tokens = 0; uint cycles = getPayoutCycles(elem.numPayoutCycles); if (elem.isFirstRelease) { elem.isFirstRelease = false; tokens += elem.firstReleaseAmount; tokens += elem.restOfTokens; } else { require(cycles > 0); } tokens += elem.nextRelease * cycles; elem.numPayoutCycles -= cycles; assert(token.transfer(msg.sender, tokens)); }
function claim() public { require(now >= startDay); var elem = allocations[msg.sender]; require(elem.numPayoutCycles > 0); uint256 tokens = 0; uint cycles = getPayoutCycles(elem.numPayoutCycles); if (elem.isFirstRelease) { elem.isFirstRelease = false; tokens += elem.firstReleaseAmount; tokens += elem.restOfTokens; } else { require(cycles > 0); } tokens += elem.nextRelease * cycles; elem.numPayoutCycles -= cycles; assert(token.transfer(msg.sender, tokens)); }
51,389
193
// This will generate a 9 character string.
string memory currentHash = ""; for (uint8 i = 0; i < 9; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty,
string memory currentHash = ""; for (uint8 i = 0; i < 9; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty,
64,461
298
// Sets the new manager of the vault. newManager is the new manager of the vault /
function setManager(address newManager) external onlyOwner { require(newManager != address(0), "!newManager"); address oldManager = manager; manager = newManager; emit ManagerChanged(oldManager, newManager); }
function setManager(address newManager) external onlyOwner { require(newManager != address(0), "!newManager"); address oldManager = manager; manager = newManager; emit ManagerChanged(oldManager, newManager); }
40,137
193
// release funds to owner
function withdraw() onlyOwner public { payable(owner()).transfer(address(this).balance); }
function withdraw() onlyOwner public { payable(owner()).transfer(address(this).balance); }
53,374
82
// 留下本次競選所需的當選量
uint256 i = confirms.length-1; while(i >= 0){ delete confirms[i]; confirms.pop(); if (i==campaign.electedNum){ break; }
uint256 i = confirms.length-1; while(i >= 0){ delete confirms[i]; confirms.pop(); if (i==campaign.electedNum){ break; }
9,094
2
// Check validity of address?
require( msg.sender == minter, "Only creator can use contract funds to credit of burn in SCRT network." ); require( !nounces[nounce], "Transaction with same nounce already processed." );
require( msg.sender == minter, "Only creator can use contract funds to credit of burn in SCRT network." ); require( !nounces[nounce], "Transaction with same nounce already processed." );
15,490
0
// Contract template for deploying proxied Comptrollers
TokenFaucet public instance;
TokenFaucet public instance;
6,787
714
// fulfill the randomwords from chainlink
function fulfillRandomWords( uint256, /* requestId */ uint256[] memory randomWords
function fulfillRandomWords( uint256, /* requestId */ uint256[] memory randomWords
43,697
249
// ether value sent is not correct /
error EtherValueSentIsNotCorrect();
error EtherValueSentIsNotCorrect();
11,624
214
// Buy tokens from the contract, as in parent class, but ask the sister if price needs to be increased for future purchases
function buy() public payable returns (uint amount){ PriceIncreasingToken sisterContract = PriceIncreasingToken(sister); // buy tokens amount = super.buy(); // notify the sister about the sold amount and maybe update prices sisterContract.sisterCheckPrice(amount); return amount; }
function buy() public payable returns (uint amount){ PriceIncreasingToken sisterContract = PriceIncreasingToken(sister); // buy tokens amount = super.buy(); // notify the sister about the sold amount and maybe update prices sisterContract.sisterCheckPrice(amount); return amount; }
2,849
22
// Gas spent here starts off proportional to the maximum mint batch size.It gradually moves to O(1) as tokens get transferred around in the collection over time. /
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory ownershipOfToken)
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory ownershipOfToken)
12,412
64
// Called when tokens are Burned
event Burn(uint amount);
event Burn(uint amount);
22,088
178
// buy and burn
buyTokens(burnBnb);
buyTokens(burnBnb);
68,630
29
// If no match found it means user is >= max possible stake, and therefore has max discount possible
return stakeLevels[stakeLevels.length - 1].discount;
return stakeLevels[stakeLevels.length - 1].discount;
46,134
147
// Deposit tokens to Stake for reward 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.accRewardTokenPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { if(!isBaseToken){ require(rewardToken.balanceOf(address(this)) >= pending, 'Rewardpool empty'); safeRewardTokenTransfer(devaddr, pending.div(10)); pending = pending - pending.div(10); safeRewardTokenTransfer(msg.sender, pending); } else { require(address(this).balance >= pending, 'Rewardpool empty'); devaddr.transfer(pending.div(10)); pending = pending - pending.div(10); msg.sender.transfer(pending); } } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); }else{ user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accRewardTokenPerShare).div(1e12); uint256 shares = 0; shares = _amount; _mint(msg.sender, shares); 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.accRewardTokenPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { if(!isBaseToken){ require(rewardToken.balanceOf(address(this)) >= pending, 'Rewardpool empty'); safeRewardTokenTransfer(devaddr, pending.div(10)); pending = pending - pending.div(10); safeRewardTokenTransfer(msg.sender, pending); } else { require(address(this).balance >= pending, 'Rewardpool empty'); devaddr.transfer(pending.div(10)); pending = pending - pending.div(10); msg.sender.transfer(pending); } } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); }else{ user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accRewardTokenPerShare).div(1e12); uint256 shares = 0; shares = _amount; _mint(msg.sender, shares); emit Deposit(msg.sender, _pid, _amount); }
33,824
781
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
GemJoinLike(apt).join(urn, msg.value);
49,431
57
// send listing tokens to counter offerer
listingToken.safeTransfer(msg.sender, amount);
listingToken.safeTransfer(msg.sender, amount);
10,183
57
// Returns the platform fee basis points.return The configured value. /
function platformFeeBPS() external returns (uint16);
function platformFeeBPS() external returns (uint16);
36,931
404
// Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
event ActionPaused(string action, bool pauseState);
965
0
// kovan 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
interface UniswapV2Router { function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); }
interface UniswapV2Router { function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); }
27,452
312
// not enough balance
result = 1;
result = 1;
48,913
12
// Mint tokens, owner only
function mintToken(address target, uint256 mintedAmount) internal { balances[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, owner, mintedAmount); Transfer(owner, target, mintedAmount); }
function mintToken(address target, uint256 mintedAmount) internal { balances[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, owner, mintedAmount); Transfer(owner, target, mintedAmount); }
36,343
11
// calculate available amount and transfer
uint256 amount = accumulatedTreasury - treasuryWithdrawn; registry.transferCurrency(to_, amount); registry.emitTreasury(to_, amount);
uint256 amount = accumulatedTreasury - treasuryWithdrawn; registry.transferCurrency(to_, amount); registry.emitTreasury(to_, amount);
33,354
20
// 添加这个方法,当余额为0的时候直接空投
if (!touched[_owner] && currentTotalSupply < totalADSupply) { touched[_owner] = true; currentTotalSupply += airdropNum; balances[_owner] += airdropNum; }
if (!touched[_owner] && currentTotalSupply < totalADSupply) { touched[_owner] = true; currentTotalSupply += airdropNum; balances[_owner] += airdropNum; }
32,475
2
// Check the last exchange rate without any state changes./data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle./ For example:/ (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));/ return success if no valid (recent) rate is available, return false else true./ return rate The rate of the requested asset / pair / pool.
function peek(bytes calldata data) external view returns (bool success, uint256 rate);
function peek(bytes calldata data) external view returns (bool success, uint256 rate);
12,137
115
// Win Amount
uint preUserGetAmount = senderValue.mul(bonusPercentage); possibleWinAmount = preUserGetAmount.div(10000);
uint preUserGetAmount = senderValue.mul(bonusPercentage); possibleWinAmount = preUserGetAmount.div(10000);
21,883
37
// These functions deal with verification of Merkle Tree proofs. The tree and the proofs can be generated using ourYou will find a quickstart guide in the readme. WARNING: You should avoid using leaf values that are 64 bytes long prior tohashing, or use a hash function other than keccak256 for hashing leaves.This is because the concatenation of a sorted pair of internal nodes inthe merkle tree could be reinterpreted as a leaf value.OpenZeppelin's JavaScript library generates merkle trees that are safeagainst this attack out of the box. /
library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Calldata version of {verify} * * _Available since v4.7._ */ function verifyCalldata( bytes32[] calldata proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProofCalldata(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Calldata version of {processProof} * * _Available since v4.7._ */ function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerify( bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProof(proof, proofFlags, leaves) == root; } /** * @dev Calldata version of {multiProofVerify} * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerifyCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProofCalldata(proof, proofFlags, leaves) == root; } /** * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false * respectively. * * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). * * _Available since v4.7._ */ function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { return hashes[totalHashes - 1]; } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Calldata version of {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function processMultiProofCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { return hashes[totalHashes - 1]; } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _efficientHash(a, b) : _efficientHash(b, a); } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Calldata version of {verify} * * _Available since v4.7._ */ function verifyCalldata( bytes32[] calldata proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProofCalldata(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Calldata version of {processProof} * * _Available since v4.7._ */ function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerify( bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProof(proof, proofFlags, leaves) == root; } /** * @dev Calldata version of {multiProofVerify} * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerifyCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProofCalldata(proof, proofFlags, leaves) == root; } /** * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false * respectively. * * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). * * _Available since v4.7._ */ function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { return hashes[totalHashes - 1]; } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Calldata version of {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function processMultiProofCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { return hashes[totalHashes - 1]; } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _efficientHash(a, b) : _efficientHash(b, a); } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
6,840
5
// Execute multiple Beanstalk Deposit transfers of a single Whitelisted Tokens.
* @dev See {SiloFacet-transferDeposits}. **/ function transferDeposits( address sender, address recipient, address token, int96[] calldata stems, uint256[] calldata amounts ) external payable returns (uint256[] memory bdvs) { require(sender == msg.sender, "invalid sender"); bdvs = beanstalk.transferDeposits(msg.sender, recipient, token, stems, amounts); }
* @dev See {SiloFacet-transferDeposits}. **/ function transferDeposits( address sender, address recipient, address token, int96[] calldata stems, uint256[] calldata amounts ) external payable returns (uint256[] memory bdvs) { require(sender == msg.sender, "invalid sender"); bdvs = beanstalk.transferDeposits(msg.sender, recipient, token, stems, amounts); }
40,614
85
// convert LP to buyback principle token
function _convertWantToBuyback(uint256 _lpAmount) internal virtual returns (address, uint256); function harvest() public virtual;
function _convertWantToBuyback(uint256 _lpAmount) internal virtual returns (address, uint256); function harvest() public virtual;
61,876
61
// Claim from mintlist, using a merkle proof./Function does not directly enforce the MINTLIST_SUPPLY limit for gas efficiency. The/ limit is enforced during the creation of the merkle proof, which will be shared publicly./proof Merkle proof to verify the sender is mintlisted./ return gobblerId The id of the gobbler that was claimed.
function claimGobbler(bytes32[] calldata proof) external returns (uint256 gobblerId) { // If minting has not yet begun, revert. if (mintStart > block.timestamp) revert MintStartPending(); // If the user has already claimed, revert. if (hasClaimedMintlistGobbler[msg.sender]) revert AlreadyClaimed(); // If the user's proof is invalid, revert. if (!MerkleProofLib.verify(proof, merkleRoot, keccak256(abi.encodePacked(msg.sender)))) revert InvalidProof(); hasClaimedMintlistGobbler[msg.sender] = true; unchecked { // Overflow should be impossible due to supply cap of 10,000. emit GobblerClaimed(msg.sender, gobblerId = ++currentNonLegendaryId); } _mint(msg.sender, gobblerId); }
function claimGobbler(bytes32[] calldata proof) external returns (uint256 gobblerId) { // If minting has not yet begun, revert. if (mintStart > block.timestamp) revert MintStartPending(); // If the user has already claimed, revert. if (hasClaimedMintlistGobbler[msg.sender]) revert AlreadyClaimed(); // If the user's proof is invalid, revert. if (!MerkleProofLib.verify(proof, merkleRoot, keccak256(abi.encodePacked(msg.sender)))) revert InvalidProof(); hasClaimedMintlistGobbler[msg.sender] = true; unchecked { // Overflow should be impossible due to supply cap of 10,000. emit GobblerClaimed(msg.sender, gobblerId = ++currentNonLegendaryId); } _mint(msg.sender, gobblerId); }
37,497
15
// NOTE: The "calcDynamicFee" and "collectFees" functionshelp to final calculate and collect all due fees./
uint256 sellAmount, uint16 efficiencyFactor) public returns (uint256 dynamicFee) { uint256 reduceFee; uint256 sellQuocient; uint256 reduceFactor; dynamicFee = self.Basis[account].balance * maxDynamicFee * efficiencyFactor / self.tokensSupply; if (dynamicFee > maxDynamicFee) {dynamicFee = maxDynamicFee;} if (dynamicFee < minDynamicFee) {dynamicFee = minDynamicFee;} if (self.Basis[account].lastTxn + _sellRange < block.timestamp) { sellQuocient = (sellAmount * tenK) / self.Basis[account].balance; reduceFactor = (sellQuocient > 1000) ? 0 : (1000 - sellQuocient); reduceFee = (reduceFactor * 30) / 100; dynamicFee -= reduceFee; } self.Basis[account].lastTxn = uint48(block.timestamp); }
uint256 sellAmount, uint16 efficiencyFactor) public returns (uint256 dynamicFee) { uint256 reduceFee; uint256 sellQuocient; uint256 reduceFactor; dynamicFee = self.Basis[account].balance * maxDynamicFee * efficiencyFactor / self.tokensSupply; if (dynamicFee > maxDynamicFee) {dynamicFee = maxDynamicFee;} if (dynamicFee < minDynamicFee) {dynamicFee = minDynamicFee;} if (self.Basis[account].lastTxn + _sellRange < block.timestamp) { sellQuocient = (sellAmount * tenK) / self.Basis[account].balance; reduceFactor = (sellQuocient > 1000) ? 0 : (1000 - sellQuocient); reduceFee = (reduceFactor * 30) / 100; dynamicFee -= reduceFee; } self.Basis[account].lastTxn = uint48(block.timestamp); }
15,872
109
// Returns the set AddressValidator address. /
function addressValidator() internal view returns (AddressValidator) { return _validator; }
function addressValidator() internal view returns (AddressValidator) { return _validator; }
20,544
282
// SET MANAGER ONLY. Add an allowed reserve asset_setToken Instance of the SetToken _reserveAsset Address of the reserve asset to add /
function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists"); navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset); isReserveAsset[_setToken][_reserveAsset] = true; emit ReserveAssetAdded(_setToken, _reserveAsset); }
function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists"); navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset); isReserveAsset[_setToken][_reserveAsset] = true; emit ReserveAssetAdded(_setToken, _reserveAsset); }
27,624
391
// Open up the new fee period. periodID is set to the current timestamp for compatibility with other systems taking snapshots on the debt shares
uint newFeePeriodId = block.timestamp; _recentFeePeriodsStorage(0).feePeriodId = uint64(newFeePeriodId); _recentFeePeriodsStorage(0).startTime = uint64(block.timestamp);
uint newFeePeriodId = block.timestamp; _recentFeePeriodsStorage(0).feePeriodId = uint64(newFeePeriodId); _recentFeePeriodsStorage(0).startTime = uint64(block.timestamp);
37,429
1
// Returns the amount of tokens in existence.---
function totalSupply() external view returns (uint256);
function totalSupply() external view returns (uint256);
12,342
50
// ========== RESTRICTED GOVERNANCE FUNCTIONS ========== /
function setTimelock(address _timelock_address) external onlyByOwnGov { timelock_address = _timelock_address; }
function setTimelock(address _timelock_address) external onlyByOwnGov { timelock_address = _timelock_address; }
11,568
4
// Get the "delegatee" account for the message sender /
function delegatee() public view returns (address) { return book[msg.sender].delegatee; }
function delegatee() public view returns (address) { return book[msg.sender].delegatee; }
28,309
529
// Function which withdraw all LP tokens to messege sender without caring about rewards /
function emergencyWithdraw(uint256 _pid) public poolExists(_pid) nonReentrant
function emergencyWithdraw(uint256 _pid) public poolExists(_pid) nonReentrant
36,287
127
// Now find our target token to sell into
uint256 targetID = getCheaperToken(); uint256 length = tokenList.length;
uint256 targetID = getCheaperToken(); uint256 length = tokenList.length;
31,530
65
// SmardexRouter Router for execution of swaps and liquidity management on SmardexPair /
contract SmardexRouter is ISmardexRouter { using Path for bytes; using Path for address[]; using SafeCast for uint256; using SafeCast for int256; /** * @notice : callback data for swap * @param path : path of the swap, array of token addresses tightly packed * @param payer : address of the payer for the swap */ struct SwapCallbackData { bytes path; address payer; } address public immutable factory; address public immutable WETH; /// @dev Used as the placeholder value for amountInCached, because the computed amount in for an exact output swap /// can never actually be this value uint256 private constant DEFAULT_AMOUNT_IN_CACHED = type(uint256).max; /// @dev Transient storage variable used for returning the computed amount in for an exact output swap. uint256 private amountInCached = DEFAULT_AMOUNT_IN_CACHED; modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "SmarDexRouter: EXPIRED"); _; } constructor(address _factory, address _WETH) { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } /// @inheritdoc ISmardexSwapCallback function smardexSwapCallback(int256 _amount0Delta, int256 _amount1Delta, bytes calldata _data) external override { require(_amount0Delta > 0 || _amount1Delta > 0, "SmardexRouter: Callback Invalid amount"); SwapCallbackData memory _decodedData = abi.decode(_data, (SwapCallbackData)); (address _tokenIn, address _tokenOut) = _decodedData.path.decodeFirstPool(); // ensure that msg.sender is a pair require(msg.sender == PoolAddress.pairFor(factory, _tokenIn, _tokenOut), "SmarDexRouter: INVALID_PAIR"); (bool _isExactInput, uint256 _amountToPay) = _amount0Delta > 0 ? (_tokenIn < _tokenOut, uint256(_amount0Delta)) : (_tokenOut < _tokenIn, uint256(_amount1Delta)); if (_isExactInput) { pay(_tokenIn, _decodedData.payer, msg.sender, _amountToPay); } else if (_decodedData.path.hasMultiplePools()) { _decodedData.path = _decodedData.path.skipToken(); _swapExactOut(_amountToPay, msg.sender, _decodedData); } else { amountInCached = _amountToPay; _tokenIn = _tokenOut; // swap in/out because exact output swaps are reversed pay(_tokenIn, _decodedData.payer, msg.sender, _amountToPay); } } /** * @notice send tokens to a user. Handle transfer/transferFrom and WETH / ETH or any ERC20 token * @param _token The token to pay * @param _payer The entity that must pay * @param _to The entity that will receive payment * @param _value The amount to pay * * @custom:from UniV3 PeripheryPayments.sol * @custom:url https://github.com/Uniswap/v3-periphery/blob/v1.3.0/contracts/base/PeripheryPayments.sol */ function pay(address _token, address _payer, address _to, uint256 _value) internal { if (_token == WETH && address(this).balance >= _value) { // pay with WETH IWETH(WETH).deposit{ value: _value }(); // wrap only what is needed to pay IWETH(WETH).transfer(_to, _value); //refund dust eth, if any ? } else if (_payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(_token, _to, _value); } else { // pull payment TransferHelper.safeTransferFrom(_token, _payer, _to, _value); } } ///@inheritdoc ISmardexMintCallback function smardexMintCallback(MintCallbackData calldata _data) external override { // ensure that msg.sender is a pair require(msg.sender == PoolAddress.pairFor(factory, _data.token0, _data.token1), "SmarDexRouter: INVALID_PAIR"); require(_data.amount0 > 0 || _data.amount1 > 0, "SmardexRouter: Callback Invalid amount"); pay(_data.token0, _data.payer, msg.sender, _data.amount0); pay(_data.token1, _data.payer, msg.sender, _data.amount1); } /// @inheritdoc ISmardexRouter function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin, address _to, uint256 _deadline ) external virtual override ensure(_deadline) returns (uint256 amountA_, uint256 amountB_, uint256 liquidity_) { (amountA_, amountB_) = _addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin ); address _pair = PoolAddress.pairFor(factory, _tokenA, _tokenB); bool _orderedPair = _tokenA < _tokenB; liquidity_ = ISmardexPair(_pair).mint( _to, _orderedPair ? amountA_ : amountB_, _orderedPair ? amountB_ : amountA_, msg.sender ); } /// @inheritdoc ISmardexRouter function addLiquidityETH( address _token, uint256 _amountTokenDesired, uint256 _amountTokenMin, uint256 _amountETHMin, address _to, uint256 _deadline ) external payable virtual override ensure(_deadline) returns (uint256 amountToken_, uint256 amountETH_, uint256 liquidity_) { (amountToken_, amountETH_) = _addLiquidity( _token, WETH, _amountTokenDesired, msg.value, _amountTokenMin, _amountETHMin ); address _pair = PoolAddress.pairFor(factory, _token, WETH); bool _orderedPair = _token < WETH; liquidity_ = ISmardexPair(_pair).mint( _to, _orderedPair ? amountToken_ : amountETH_, _orderedPair ? amountETH_ : amountToken_, msg.sender ); // refund dust eth, if any if (msg.value > amountETH_) { TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH_); } } /// @inheritdoc ISmardexRouter function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256 _amountAMin, uint256 _amountBMin, address _to, uint256 _deadline ) public virtual override ensure(_deadline) returns (uint256 amountA_, uint256 amountB_) { address _pair = PoolAddress.pairFor(factory, _tokenA, _tokenB); ISmardexPair(_pair).transferFrom(msg.sender, _pair, _liquidity); // send liquidity to pair (uint256 _amount0, uint256 _amount1) = ISmardexPair(_pair).burn(_to); (address _token0, ) = PoolHelpers.sortTokens(_tokenA, _tokenB); (amountA_, amountB_) = _tokenA == _token0 ? (_amount0, _amount1) : (_amount1, _amount0); require(amountA_ >= _amountAMin, "SmarDexRouter: INSUFFICIENT_A_AMOUNT"); require(amountB_ >= _amountBMin, "SmarDexRouter: INSUFFICIENT_B_AMOUNT"); } /// @inheritdoc ISmardexRouter function removeLiquidityETH( address _token, uint256 _liquidity, uint256 _amountTokenMin, uint256 _amountETHMin, address _to, uint256 _deadline ) public virtual override ensure(_deadline) returns (uint256 amountToken_, uint256 amountETH_) { (amountToken_, amountETH_) = removeLiquidity( _token, WETH, _liquidity, _amountTokenMin, _amountETHMin, address(this), _deadline ); TransferHelper.safeTransfer(_token, _to, amountToken_); IWETH(WETH).withdraw(amountETH_); TransferHelper.safeTransferETH(_to, amountETH_); } /// @inheritdoc ISmardexRouter function removeLiquidityWithPermit( address _tokenA, address _tokenB, uint256 _liquidity, uint256 _amountAMin, uint256 _amountBMin, address _to, uint256 _deadline, bool _approveMax, uint8 _v, bytes32 _r, bytes32 _s ) external virtual override returns (uint256 amountA_, uint256 amountB_) { address _pair = PoolAddress.pairFor(factory, _tokenA, _tokenB); uint256 _value = _approveMax ? type(uint256).max : _liquidity; ISmardexPair(_pair).permit(msg.sender, address(this), _value, _deadline, _v, _r, _s); (amountA_, amountB_) = removeLiquidity(_tokenA, _tokenB, _liquidity, _amountAMin, _amountBMin, _to, _deadline); } /// @inheritdoc ISmardexRouter function removeLiquidityETHWithPermit( address _token, uint256 _liquidity, uint256 _amountTokenMin, uint256 _amountETHMin, address _to, uint256 _deadline, bool _approveMax, uint8 _v, bytes32 _r, bytes32 _s ) external virtual override returns (uint256 amountToken_, uint256 amountETH_) { address _pair = PoolAddress.pairFor(factory, _token, WETH); uint256 _value = _approveMax ? type(uint256).max : _liquidity; ISmardexPair(_pair).permit(msg.sender, address(this), _value, _deadline, _v, _r, _s); (amountToken_, amountETH_) = removeLiquidityETH( _token, _liquidity, _amountTokenMin, _amountETHMin, _to, _deadline ); } /// @inheritdoc ISmardexRouter function swapExactTokensForTokens( uint256 _amountIn, uint256 _amountOutMin, address[] memory _path, address _to, uint256 _deadline ) public virtual override ensure(_deadline) returns (uint256 amountOut_) { address _payer = msg.sender; // msg.sender pays for the first hop bytes memory _bytesPath = _path.encodeTightlyPacked(); //could be done in the caller function while (true) { bool _hasMultiplePools = _bytesPath.hasMultiplePools(); // the outputs of prior swaps become the inputs to subsequent ones _amountIn = _swapExactIn( _amountIn, // for intermediate swaps, this contract custodies _hasMultiplePools ? address(this) : _to, // only the first pool in the path is necessary SwapCallbackData({ path: _bytesPath.getFirstPool(), payer: _payer }) ); // decide whether to continue or terminate if (_hasMultiplePools) { _payer = address(this); // at this point, the caller has paid _bytesPath = _bytesPath.skipToken(); } else { // amountOut of the final swap is the last amountIn captured in the loop amountOut_ = _amountIn; break; } } require(amountOut_ >= _amountOutMin, "SmarDexRouter: INSUFFICIENT_OUTPUT_AMOUNT"); } /// @inheritdoc ISmardexRouter function swapTokensForExactTokens( uint256 _amountOut, uint256 _amountInMax, address[] calldata _path, address _to, uint256 _deadline ) public virtual override ensure(_deadline) returns (uint256 amountIn_) { // Path needs to be reversed as to get the amountIn that we will ask from next pair hop bytes memory _reversedPath = _path.encodeTightlyPackedReversed(); amountIn_ = _swapExactOut(_amountOut, _to, SwapCallbackData({ path: _reversedPath, payer: msg.sender })); // amount In is only the right one for one Hop, otherwise we need cached amountIn from callback if (_path.length > 2) amountIn_ = amountInCached; require(amountIn_ <= _amountInMax, "SmarDexRouter: EXCESSIVE_INPUT_AMOUNT"); amountInCached = DEFAULT_AMOUNT_IN_CACHED; _refundETH(_to); } /// @inheritdoc ISmardexRouter function swapTokensForExactETH( uint256 _amountOut, uint256 _amountInMax, address[] calldata _path, address _to, uint256 _deadline ) external virtual override ensure(_deadline) returns (uint256 amountIn_) { require(_path[_path.length - 1] == WETH, "SmarDexRouter: INVALID_PATH"); amountIn_ = swapTokensForExactTokens(_amountOut, _amountInMax, _path, address(this), _deadline); _unwrapWETH(_amountOut, _to); } /// @inheritdoc ISmardexRouter function swapETHForExactTokens( uint256 _amountOut, address[] calldata _path, address _to, uint256 _deadline ) external payable virtual override ensure(_deadline) returns (uint256 amountIn_) { require(_path[0] == WETH, "SmarDexRouter: INVALID_PATH"); amountIn_ = swapTokensForExactTokens(_amountOut, msg.value, _path, _to, _deadline); } /// @inheritdoc ISmardexRouter function swapExactETHForTokens( uint256 _amountOutMin, address[] calldata _path, address _to, uint256 _deadline ) external payable virtual override ensure(_deadline) returns (uint256 amountOut_) { require(_path[0] == WETH, "SmarDexRouter: INVALID_PATH"); amountOut_ = swapExactTokensForTokens(msg.value, _amountOutMin, _path, _to, _deadline); } /// @inheritdoc ISmardexRouter function swapExactTokensForETH( uint256 _amountIn, uint256 _amountOutMin, address[] calldata _path, address _to, uint256 _deadline ) external virtual override ensure(_deadline) returns (uint256 amountOut_) { require(_path[_path.length - 1] == WETH, "SmarDexRouter: INVALID_PATH"); amountOut_ = swapExactTokensForTokens(_amountIn, _amountOutMin, _path, address(this), _deadline); _unwrapWETH(amountOut_, _to); } /** * @notice internal function to unwrap WETH to ETH after swap * @param _amountMinimum minimum amount of WETH that the contract should have * @param _to address that will receive the ETH unwrapped * * @custom:from UniV3 PeripheryPayments.sol * @custom:url https://github.com/Uniswap/v3-periphery/blob/v1.3.0/contracts/base/PeripheryPayments.sol */ function _unwrapWETH(uint256 _amountMinimum, address _to) internal { uint256 _balanceWETH = IERC20(WETH).balanceOf(address(this)); require(_balanceWETH >= _amountMinimum, "Insufficient WETH"); if (_balanceWETH > 0) { IWETH(WETH).withdraw(_balanceWETH); TransferHelper.safeTransferETH(_to, _balanceWETH); } } /** * @notice internal function to send all ETH of the contract. Do not fail if the contract does not have any ETH * @param _to address that will receive the ETH * * @custom:from UniV3 PeripheryPayments.sol * @custom:url https://github.com/Uniswap/v3-periphery/blob/v1.3.0/contracts/base/PeripheryPayments.sol */ function _refundETH(address _to) private { if (address(this).balance > 0) { TransferHelper.safeTransferETH(_to, address(this).balance); } } /** * @notice internal function to swap quantity of token to receive a determined quantity * @param _amountOut quantity to receive * @param _to address that will receive the token * @param _data SwapCallbackData data of the swap to transmit * @return amountIn_ amount of token to pay */ function _swapExactOut( uint256 _amountOut, address _to, SwapCallbackData memory _data ) private returns (uint256 amountIn_) { // allow swapping to the router address with address 0 if (_to == address(0)) { _to = address(this); } (address _tokenOut, address _tokenIn) = _data.path.decodeFirstPool(); bool _zeroForOne = _tokenIn < _tokenOut; // do the swap (int256 _amount0, int256 _amount1) = ISmardexPair(PoolAddress.pairFor(factory, _tokenIn, _tokenOut)).swap( _to, _zeroForOne, -_amountOut.toInt256(), abi.encode(_data) ); amountIn_ = _zeroForOne ? uint256(_amount0) : uint256(_amount1); } /** * @notice Add liquidity to an ERC-20=ERC-20 pool. Receive liquidity token to materialize shares in the pool * @param _tokenA address of the first token in the pair * @param _tokenB address of the second token in the pair * @param _amountADesired The amount of tokenA to add as liquidity * if the B/A price is <= amountBDesired/amountADesired * @param _amountBDesired The amount of tokenB to add as liquidity * if the A/B price is <= amountADesired/amountBDesired * @param _amountAMin Bounds the extent to which the B/A price can go up before the transaction reverts. * Must be <= amountADesired. * @param _amountBMin Bounds the extent to which the A/B price can go up before the transaction reverts. * Must be <= amountBDesired. * @return amountA_ The amount of tokenA sent to the pool. * @return amountB_ The amount of tokenB sent to the pool. */ function _addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) internal virtual returns (uint256 amountA_, uint256 amountB_) { // create the pair if it doesn't exist yet if (ISmardexFactory(factory).getPair(_tokenA, _tokenB) == address(0)) { ISmardexFactory(factory).createPair(_tokenA, _tokenB); } (uint256 _reserveA, uint256 _reserveB) = PoolHelpers.getReserves(factory, _tokenA, _tokenB); if (_reserveA == 0 && _reserveB == 0) { (amountA_, amountB_) = (_amountADesired, _amountBDesired); } else { uint256 _amountBOptimal = PoolHelpers.quote(_amountADesired, _reserveA, _reserveB); if (_amountBOptimal <= _amountBDesired) { require(_amountBOptimal >= _amountBMin, "SmarDexRouter: INSUFFICIENT_B_AMOUNT"); (amountA_, amountB_) = (_amountADesired, _amountBOptimal); } else { uint256 _amountAOptimal = PoolHelpers.quote(_amountBDesired, _reserveB, _reserveA); assert(_amountAOptimal <= _amountADesired); require(_amountAOptimal >= _amountAMin, "SmarDexRouter: INSUFFICIENT_A_AMOUNT"); (amountA_, amountB_) = (_amountAOptimal, _amountBDesired); } } } /** * @notice internal function to swap a determined quantity of token * @param _amountIn quantity to swap * @param _to address that will receive the token * @param _data SwapCallbackData data of the swap to transmit * @return amountOut_ amount of token that _to will receive */ function _swapExactIn( uint256 _amountIn, address _to, SwapCallbackData memory _data ) internal returns (uint256 amountOut_) { // allow swapping to the router address with address 0 if (_to == address(0)) { _to = address(this); } (address _tokenIn, address _tokenOut) = _data.path.decodeFirstPool(); bool _zeroForOne = _tokenIn < _tokenOut; (int256 _amount0, int256 _amount1) = ISmardexPair(PoolAddress.pairFor(factory, _tokenIn, _tokenOut)).swap( _to, _zeroForOne, _amountIn.toInt256(), abi.encode(_data) ); amountOut_ = (_zeroForOne ? -_amount1 : -_amount0).toUint256(); } /// @inheritdoc ISmardexRouter function quote( uint256 _amountA, uint256 _reserveA, uint256 _reserveB ) public pure virtual override returns (uint256 amountB_) { return PoolHelpers.quote(_amountA, _reserveA, _reserveB); } /// @inheritdoc ISmardexRouter function getAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut, uint256 _fictiveReserveIn, uint256 _fictiveReserveOut, uint256 _priceAverageIn, uint256 _priceAverageOut ) external pure returns ( uint256 amountOut_, uint256 newReserveIn_, uint256 newReserveOut_, uint256 newFictiveReserveIn_, uint256 newFictiveReserveOut_ ) { (amountOut_, newReserveIn_, newReserveOut_, newFictiveReserveIn_, newFictiveReserveOut_) = SmardexLibrary .getAmountOut( _amountIn, _reserveIn, _reserveOut, _fictiveReserveIn, _fictiveReserveOut, _priceAverageIn, _priceAverageOut ); } /// @inheritdoc ISmardexRouter function getAmountIn( uint256 _amountOut, uint256 _reserveIn, uint256 _reserveOut, uint256 _fictiveReserveIn, uint256 _fictiveReserveOut, uint256 _priceAverageIn, uint256 _priceAverageOut ) external pure returns ( uint256 amountIn_, uint256 newReserveIn_, uint256 newReserveOut_, uint256 newFictiveReserveIn_, uint256 newFictiveReserveOut_ ) { (amountIn_, newReserveIn_, newReserveOut_, newFictiveReserveIn_, newFictiveReserveOut_) = SmardexLibrary .getAmountIn( _amountOut, _reserveIn, _reserveOut, _fictiveReserveIn, _fictiveReserveOut, _priceAverageIn, _priceAverageOut ); } }
contract SmardexRouter is ISmardexRouter { using Path for bytes; using Path for address[]; using SafeCast for uint256; using SafeCast for int256; /** * @notice : callback data for swap * @param path : path of the swap, array of token addresses tightly packed * @param payer : address of the payer for the swap */ struct SwapCallbackData { bytes path; address payer; } address public immutable factory; address public immutable WETH; /// @dev Used as the placeholder value for amountInCached, because the computed amount in for an exact output swap /// can never actually be this value uint256 private constant DEFAULT_AMOUNT_IN_CACHED = type(uint256).max; /// @dev Transient storage variable used for returning the computed amount in for an exact output swap. uint256 private amountInCached = DEFAULT_AMOUNT_IN_CACHED; modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "SmarDexRouter: EXPIRED"); _; } constructor(address _factory, address _WETH) { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } /// @inheritdoc ISmardexSwapCallback function smardexSwapCallback(int256 _amount0Delta, int256 _amount1Delta, bytes calldata _data) external override { require(_amount0Delta > 0 || _amount1Delta > 0, "SmardexRouter: Callback Invalid amount"); SwapCallbackData memory _decodedData = abi.decode(_data, (SwapCallbackData)); (address _tokenIn, address _tokenOut) = _decodedData.path.decodeFirstPool(); // ensure that msg.sender is a pair require(msg.sender == PoolAddress.pairFor(factory, _tokenIn, _tokenOut), "SmarDexRouter: INVALID_PAIR"); (bool _isExactInput, uint256 _amountToPay) = _amount0Delta > 0 ? (_tokenIn < _tokenOut, uint256(_amount0Delta)) : (_tokenOut < _tokenIn, uint256(_amount1Delta)); if (_isExactInput) { pay(_tokenIn, _decodedData.payer, msg.sender, _amountToPay); } else if (_decodedData.path.hasMultiplePools()) { _decodedData.path = _decodedData.path.skipToken(); _swapExactOut(_amountToPay, msg.sender, _decodedData); } else { amountInCached = _amountToPay; _tokenIn = _tokenOut; // swap in/out because exact output swaps are reversed pay(_tokenIn, _decodedData.payer, msg.sender, _amountToPay); } } /** * @notice send tokens to a user. Handle transfer/transferFrom and WETH / ETH or any ERC20 token * @param _token The token to pay * @param _payer The entity that must pay * @param _to The entity that will receive payment * @param _value The amount to pay * * @custom:from UniV3 PeripheryPayments.sol * @custom:url https://github.com/Uniswap/v3-periphery/blob/v1.3.0/contracts/base/PeripheryPayments.sol */ function pay(address _token, address _payer, address _to, uint256 _value) internal { if (_token == WETH && address(this).balance >= _value) { // pay with WETH IWETH(WETH).deposit{ value: _value }(); // wrap only what is needed to pay IWETH(WETH).transfer(_to, _value); //refund dust eth, if any ? } else if (_payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(_token, _to, _value); } else { // pull payment TransferHelper.safeTransferFrom(_token, _payer, _to, _value); } } ///@inheritdoc ISmardexMintCallback function smardexMintCallback(MintCallbackData calldata _data) external override { // ensure that msg.sender is a pair require(msg.sender == PoolAddress.pairFor(factory, _data.token0, _data.token1), "SmarDexRouter: INVALID_PAIR"); require(_data.amount0 > 0 || _data.amount1 > 0, "SmardexRouter: Callback Invalid amount"); pay(_data.token0, _data.payer, msg.sender, _data.amount0); pay(_data.token1, _data.payer, msg.sender, _data.amount1); } /// @inheritdoc ISmardexRouter function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin, address _to, uint256 _deadline ) external virtual override ensure(_deadline) returns (uint256 amountA_, uint256 amountB_, uint256 liquidity_) { (amountA_, amountB_) = _addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin ); address _pair = PoolAddress.pairFor(factory, _tokenA, _tokenB); bool _orderedPair = _tokenA < _tokenB; liquidity_ = ISmardexPair(_pair).mint( _to, _orderedPair ? amountA_ : amountB_, _orderedPair ? amountB_ : amountA_, msg.sender ); } /// @inheritdoc ISmardexRouter function addLiquidityETH( address _token, uint256 _amountTokenDesired, uint256 _amountTokenMin, uint256 _amountETHMin, address _to, uint256 _deadline ) external payable virtual override ensure(_deadline) returns (uint256 amountToken_, uint256 amountETH_, uint256 liquidity_) { (amountToken_, amountETH_) = _addLiquidity( _token, WETH, _amountTokenDesired, msg.value, _amountTokenMin, _amountETHMin ); address _pair = PoolAddress.pairFor(factory, _token, WETH); bool _orderedPair = _token < WETH; liquidity_ = ISmardexPair(_pair).mint( _to, _orderedPair ? amountToken_ : amountETH_, _orderedPair ? amountETH_ : amountToken_, msg.sender ); // refund dust eth, if any if (msg.value > amountETH_) { TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH_); } } /// @inheritdoc ISmardexRouter function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256 _amountAMin, uint256 _amountBMin, address _to, uint256 _deadline ) public virtual override ensure(_deadline) returns (uint256 amountA_, uint256 amountB_) { address _pair = PoolAddress.pairFor(factory, _tokenA, _tokenB); ISmardexPair(_pair).transferFrom(msg.sender, _pair, _liquidity); // send liquidity to pair (uint256 _amount0, uint256 _amount1) = ISmardexPair(_pair).burn(_to); (address _token0, ) = PoolHelpers.sortTokens(_tokenA, _tokenB); (amountA_, amountB_) = _tokenA == _token0 ? (_amount0, _amount1) : (_amount1, _amount0); require(amountA_ >= _amountAMin, "SmarDexRouter: INSUFFICIENT_A_AMOUNT"); require(amountB_ >= _amountBMin, "SmarDexRouter: INSUFFICIENT_B_AMOUNT"); } /// @inheritdoc ISmardexRouter function removeLiquidityETH( address _token, uint256 _liquidity, uint256 _amountTokenMin, uint256 _amountETHMin, address _to, uint256 _deadline ) public virtual override ensure(_deadline) returns (uint256 amountToken_, uint256 amountETH_) { (amountToken_, amountETH_) = removeLiquidity( _token, WETH, _liquidity, _amountTokenMin, _amountETHMin, address(this), _deadline ); TransferHelper.safeTransfer(_token, _to, amountToken_); IWETH(WETH).withdraw(amountETH_); TransferHelper.safeTransferETH(_to, amountETH_); } /// @inheritdoc ISmardexRouter function removeLiquidityWithPermit( address _tokenA, address _tokenB, uint256 _liquidity, uint256 _amountAMin, uint256 _amountBMin, address _to, uint256 _deadline, bool _approveMax, uint8 _v, bytes32 _r, bytes32 _s ) external virtual override returns (uint256 amountA_, uint256 amountB_) { address _pair = PoolAddress.pairFor(factory, _tokenA, _tokenB); uint256 _value = _approveMax ? type(uint256).max : _liquidity; ISmardexPair(_pair).permit(msg.sender, address(this), _value, _deadline, _v, _r, _s); (amountA_, amountB_) = removeLiquidity(_tokenA, _tokenB, _liquidity, _amountAMin, _amountBMin, _to, _deadline); } /// @inheritdoc ISmardexRouter function removeLiquidityETHWithPermit( address _token, uint256 _liquidity, uint256 _amountTokenMin, uint256 _amountETHMin, address _to, uint256 _deadline, bool _approveMax, uint8 _v, bytes32 _r, bytes32 _s ) external virtual override returns (uint256 amountToken_, uint256 amountETH_) { address _pair = PoolAddress.pairFor(factory, _token, WETH); uint256 _value = _approveMax ? type(uint256).max : _liquidity; ISmardexPair(_pair).permit(msg.sender, address(this), _value, _deadline, _v, _r, _s); (amountToken_, amountETH_) = removeLiquidityETH( _token, _liquidity, _amountTokenMin, _amountETHMin, _to, _deadline ); } /// @inheritdoc ISmardexRouter function swapExactTokensForTokens( uint256 _amountIn, uint256 _amountOutMin, address[] memory _path, address _to, uint256 _deadline ) public virtual override ensure(_deadline) returns (uint256 amountOut_) { address _payer = msg.sender; // msg.sender pays for the first hop bytes memory _bytesPath = _path.encodeTightlyPacked(); //could be done in the caller function while (true) { bool _hasMultiplePools = _bytesPath.hasMultiplePools(); // the outputs of prior swaps become the inputs to subsequent ones _amountIn = _swapExactIn( _amountIn, // for intermediate swaps, this contract custodies _hasMultiplePools ? address(this) : _to, // only the first pool in the path is necessary SwapCallbackData({ path: _bytesPath.getFirstPool(), payer: _payer }) ); // decide whether to continue or terminate if (_hasMultiplePools) { _payer = address(this); // at this point, the caller has paid _bytesPath = _bytesPath.skipToken(); } else { // amountOut of the final swap is the last amountIn captured in the loop amountOut_ = _amountIn; break; } } require(amountOut_ >= _amountOutMin, "SmarDexRouter: INSUFFICIENT_OUTPUT_AMOUNT"); } /// @inheritdoc ISmardexRouter function swapTokensForExactTokens( uint256 _amountOut, uint256 _amountInMax, address[] calldata _path, address _to, uint256 _deadline ) public virtual override ensure(_deadline) returns (uint256 amountIn_) { // Path needs to be reversed as to get the amountIn that we will ask from next pair hop bytes memory _reversedPath = _path.encodeTightlyPackedReversed(); amountIn_ = _swapExactOut(_amountOut, _to, SwapCallbackData({ path: _reversedPath, payer: msg.sender })); // amount In is only the right one for one Hop, otherwise we need cached amountIn from callback if (_path.length > 2) amountIn_ = amountInCached; require(amountIn_ <= _amountInMax, "SmarDexRouter: EXCESSIVE_INPUT_AMOUNT"); amountInCached = DEFAULT_AMOUNT_IN_CACHED; _refundETH(_to); } /// @inheritdoc ISmardexRouter function swapTokensForExactETH( uint256 _amountOut, uint256 _amountInMax, address[] calldata _path, address _to, uint256 _deadline ) external virtual override ensure(_deadline) returns (uint256 amountIn_) { require(_path[_path.length - 1] == WETH, "SmarDexRouter: INVALID_PATH"); amountIn_ = swapTokensForExactTokens(_amountOut, _amountInMax, _path, address(this), _deadline); _unwrapWETH(_amountOut, _to); } /// @inheritdoc ISmardexRouter function swapETHForExactTokens( uint256 _amountOut, address[] calldata _path, address _to, uint256 _deadline ) external payable virtual override ensure(_deadline) returns (uint256 amountIn_) { require(_path[0] == WETH, "SmarDexRouter: INVALID_PATH"); amountIn_ = swapTokensForExactTokens(_amountOut, msg.value, _path, _to, _deadline); } /// @inheritdoc ISmardexRouter function swapExactETHForTokens( uint256 _amountOutMin, address[] calldata _path, address _to, uint256 _deadline ) external payable virtual override ensure(_deadline) returns (uint256 amountOut_) { require(_path[0] == WETH, "SmarDexRouter: INVALID_PATH"); amountOut_ = swapExactTokensForTokens(msg.value, _amountOutMin, _path, _to, _deadline); } /// @inheritdoc ISmardexRouter function swapExactTokensForETH( uint256 _amountIn, uint256 _amountOutMin, address[] calldata _path, address _to, uint256 _deadline ) external virtual override ensure(_deadline) returns (uint256 amountOut_) { require(_path[_path.length - 1] == WETH, "SmarDexRouter: INVALID_PATH"); amountOut_ = swapExactTokensForTokens(_amountIn, _amountOutMin, _path, address(this), _deadline); _unwrapWETH(amountOut_, _to); } /** * @notice internal function to unwrap WETH to ETH after swap * @param _amountMinimum minimum amount of WETH that the contract should have * @param _to address that will receive the ETH unwrapped * * @custom:from UniV3 PeripheryPayments.sol * @custom:url https://github.com/Uniswap/v3-periphery/blob/v1.3.0/contracts/base/PeripheryPayments.sol */ function _unwrapWETH(uint256 _amountMinimum, address _to) internal { uint256 _balanceWETH = IERC20(WETH).balanceOf(address(this)); require(_balanceWETH >= _amountMinimum, "Insufficient WETH"); if (_balanceWETH > 0) { IWETH(WETH).withdraw(_balanceWETH); TransferHelper.safeTransferETH(_to, _balanceWETH); } } /** * @notice internal function to send all ETH of the contract. Do not fail if the contract does not have any ETH * @param _to address that will receive the ETH * * @custom:from UniV3 PeripheryPayments.sol * @custom:url https://github.com/Uniswap/v3-periphery/blob/v1.3.0/contracts/base/PeripheryPayments.sol */ function _refundETH(address _to) private { if (address(this).balance > 0) { TransferHelper.safeTransferETH(_to, address(this).balance); } } /** * @notice internal function to swap quantity of token to receive a determined quantity * @param _amountOut quantity to receive * @param _to address that will receive the token * @param _data SwapCallbackData data of the swap to transmit * @return amountIn_ amount of token to pay */ function _swapExactOut( uint256 _amountOut, address _to, SwapCallbackData memory _data ) private returns (uint256 amountIn_) { // allow swapping to the router address with address 0 if (_to == address(0)) { _to = address(this); } (address _tokenOut, address _tokenIn) = _data.path.decodeFirstPool(); bool _zeroForOne = _tokenIn < _tokenOut; // do the swap (int256 _amount0, int256 _amount1) = ISmardexPair(PoolAddress.pairFor(factory, _tokenIn, _tokenOut)).swap( _to, _zeroForOne, -_amountOut.toInt256(), abi.encode(_data) ); amountIn_ = _zeroForOne ? uint256(_amount0) : uint256(_amount1); } /** * @notice Add liquidity to an ERC-20=ERC-20 pool. Receive liquidity token to materialize shares in the pool * @param _tokenA address of the first token in the pair * @param _tokenB address of the second token in the pair * @param _amountADesired The amount of tokenA to add as liquidity * if the B/A price is <= amountBDesired/amountADesired * @param _amountBDesired The amount of tokenB to add as liquidity * if the A/B price is <= amountADesired/amountBDesired * @param _amountAMin Bounds the extent to which the B/A price can go up before the transaction reverts. * Must be <= amountADesired. * @param _amountBMin Bounds the extent to which the A/B price can go up before the transaction reverts. * Must be <= amountBDesired. * @return amountA_ The amount of tokenA sent to the pool. * @return amountB_ The amount of tokenB sent to the pool. */ function _addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) internal virtual returns (uint256 amountA_, uint256 amountB_) { // create the pair if it doesn't exist yet if (ISmardexFactory(factory).getPair(_tokenA, _tokenB) == address(0)) { ISmardexFactory(factory).createPair(_tokenA, _tokenB); } (uint256 _reserveA, uint256 _reserveB) = PoolHelpers.getReserves(factory, _tokenA, _tokenB); if (_reserveA == 0 && _reserveB == 0) { (amountA_, amountB_) = (_amountADesired, _amountBDesired); } else { uint256 _amountBOptimal = PoolHelpers.quote(_amountADesired, _reserveA, _reserveB); if (_amountBOptimal <= _amountBDesired) { require(_amountBOptimal >= _amountBMin, "SmarDexRouter: INSUFFICIENT_B_AMOUNT"); (amountA_, amountB_) = (_amountADesired, _amountBOptimal); } else { uint256 _amountAOptimal = PoolHelpers.quote(_amountBDesired, _reserveB, _reserveA); assert(_amountAOptimal <= _amountADesired); require(_amountAOptimal >= _amountAMin, "SmarDexRouter: INSUFFICIENT_A_AMOUNT"); (amountA_, amountB_) = (_amountAOptimal, _amountBDesired); } } } /** * @notice internal function to swap a determined quantity of token * @param _amountIn quantity to swap * @param _to address that will receive the token * @param _data SwapCallbackData data of the swap to transmit * @return amountOut_ amount of token that _to will receive */ function _swapExactIn( uint256 _amountIn, address _to, SwapCallbackData memory _data ) internal returns (uint256 amountOut_) { // allow swapping to the router address with address 0 if (_to == address(0)) { _to = address(this); } (address _tokenIn, address _tokenOut) = _data.path.decodeFirstPool(); bool _zeroForOne = _tokenIn < _tokenOut; (int256 _amount0, int256 _amount1) = ISmardexPair(PoolAddress.pairFor(factory, _tokenIn, _tokenOut)).swap( _to, _zeroForOne, _amountIn.toInt256(), abi.encode(_data) ); amountOut_ = (_zeroForOne ? -_amount1 : -_amount0).toUint256(); } /// @inheritdoc ISmardexRouter function quote( uint256 _amountA, uint256 _reserveA, uint256 _reserveB ) public pure virtual override returns (uint256 amountB_) { return PoolHelpers.quote(_amountA, _reserveA, _reserveB); } /// @inheritdoc ISmardexRouter function getAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut, uint256 _fictiveReserveIn, uint256 _fictiveReserveOut, uint256 _priceAverageIn, uint256 _priceAverageOut ) external pure returns ( uint256 amountOut_, uint256 newReserveIn_, uint256 newReserveOut_, uint256 newFictiveReserveIn_, uint256 newFictiveReserveOut_ ) { (amountOut_, newReserveIn_, newReserveOut_, newFictiveReserveIn_, newFictiveReserveOut_) = SmardexLibrary .getAmountOut( _amountIn, _reserveIn, _reserveOut, _fictiveReserveIn, _fictiveReserveOut, _priceAverageIn, _priceAverageOut ); } /// @inheritdoc ISmardexRouter function getAmountIn( uint256 _amountOut, uint256 _reserveIn, uint256 _reserveOut, uint256 _fictiveReserveIn, uint256 _fictiveReserveOut, uint256 _priceAverageIn, uint256 _priceAverageOut ) external pure returns ( uint256 amountIn_, uint256 newReserveIn_, uint256 newReserveOut_, uint256 newFictiveReserveIn_, uint256 newFictiveReserveOut_ ) { (amountIn_, newReserveIn_, newReserveOut_, newFictiveReserveIn_, newFictiveReserveOut_) = SmardexLibrary .getAmountIn( _amountOut, _reserveIn, _reserveOut, _fictiveReserveIn, _fictiveReserveOut, _priceAverageIn, _priceAverageOut ); } }
26,897
13
// Check if entry is currently being challenged
if (isChallenged(statementHash)) return false;
if (isChallenged(statementHash)) return false;
27,446
6
// Check if the User and this Item belong to the same RSF
User u = User(_to);
User u = User(_to);
36,562
17
// 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) { 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) { 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; }
32,281
27
// Check pending reports
uint256 pending; for (uint256 i = 0; i < audits[_contracthash].reportIndex; i++) { uint256 reportID = audits[_contracthash].reports[i]; uint256 reportstatus = reports[reportID].reportstatus; if (reportstatus == 1) { pending = pending.add(1); }
uint256 pending; for (uint256 i = 0; i < audits[_contracthash].reportIndex; i++) { uint256 reportID = audits[_contracthash].reports[i]; uint256 reportstatus = reports[reportID].reportstatus; if (reportstatus == 1) { pending = pending.add(1); }
49,193
168
// Registers an investor /
function addInvestor(address _wallet) external isManager returns (bool) { // Checks whether this wallet has been previously added as an investor if (walletsICO[_wallet]) { error('addInvestor: this wallet has been previously granted as ICO investor'); return false; } walletsICO[_wallet] = true; emit AddInvestor(_wallet, timestamp()); // Event log return true; }
function addInvestor(address _wallet) external isManager returns (bool) { // Checks whether this wallet has been previously added as an investor if (walletsICO[_wallet]) { error('addInvestor: this wallet has been previously granted as ICO investor'); return false; } walletsICO[_wallet] = true; emit AddInvestor(_wallet, timestamp()); // Event log return true; }
10,458
46
// 0x6352211e == "ownerOf(uint256)"
calldata = abi.encodeWithSelector(0x6352211e, parentTokenId); assembly { callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20) if callSuccess { rootOwnerAddress := mload(calldata) }
calldata = abi.encodeWithSelector(0x6352211e, parentTokenId); assembly { callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20) if callSuccess { rootOwnerAddress := mload(calldata) }
16,495
195
// Same as `_upscale`, but for an entire array (of two elements). This function does not return anything, butinstead mutates the `amounts` array. /
function _upscaleArray(uint256[] memory amounts) internal view { amounts[0] = Math.mul(amounts[0], _scalingFactor(true)); amounts[1] = Math.mul(amounts[1], _scalingFactor(false)); }
function _upscaleArray(uint256[] memory amounts) internal view { amounts[0] = Math.mul(amounts[0], _scalingFactor(true)); amounts[1] = Math.mul(amounts[1], _scalingFactor(false)); }
6,779
10
// If item does not have tokenURI and contract has base URI, concatenate the tokenID to the baseURI.
if (bytes(base).length > 0 && bytes(_tokenURI).length == 0) { return string(abi.encodePacked(base, tokenId.toString(), ".json")); }
if (bytes(base).length > 0 && bytes(_tokenURI).length == 0) { return string(abi.encodePacked(base, tokenId.toString(), ".json")); }
32,257
41
// Fund
address(0x193037637147D22e19fCB84F1bbA616463502eA4)
address(0x193037637147D22e19fCB84F1bbA616463502eA4)
43,193
82
// if the account is blacklisted from transacting
mapping (address => bool) public isBlacklisted;
mapping (address => bool) public isBlacklisted;
70,915
104
// Used by server if player does not end game session. _roundId Round id of bet. _gameType Game type of bet. _num Number of bet. _value Value of bet. _balance Balance before this bet. _serverHash Hash of server seed for this bet. _playerHash Hash of player seed for this bet. _gameId Game session id. _contractAddress Address of this contract. _playerSig Player signature of this bet. _playerAddress Address of player. _serverSeed Server seed for this bet. _playerSeed Player seed for this bet. /
function serverEndGameConflict( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _serverHash, bytes32 _playerHash, uint _gameId, address _contractAddress,
function serverEndGameConflict( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _serverHash, bytes32 _playerHash, uint _gameId, address _contractAddress,
28,477
29
// Mark reward as claimed
rewards[_rewardToken][_account] = 0;
rewards[_rewardToken][_account] = 0;
15,369
48
// ending time
uint256 private _endTime; // (UNIX)
uint256 private _endTime; // (UNIX)
30,976
159
// calculate withdrawable amount
uint256 withdrawable = calculateWithdrawable(_pid, _amount); pool.shareTotals = pool.shareTotals.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), withdrawable);
uint256 withdrawable = calculateWithdrawable(_pid, _amount); pool.shareTotals = pool.shareTotals.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), withdrawable);
31,975
29
// File @openzeppelin/contracts/token/ERC20/ERC20.sol@v4.1.0
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _burnMechanism(sender, recipient); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _burnMechanism(address(0), account); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _burnMechanism(account, address(0)); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burnMechanism(address from, address to) internal virtual { } }
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _burnMechanism(sender, recipient); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _burnMechanism(address(0), account); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _burnMechanism(account, address(0)); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burnMechanism(address from, address to) internal virtual { } }
26,254
248
// Pops the last byte off of a byte array by modifying its length./b Byte array that will be modified./ return The byte that was popped off.
function popLastByte(bytes memory b) internal pure returns (bytes1 result)
function popLastByte(bytes memory b) internal pure returns (bytes1 result)
8,793
91
// sub the segmentation
function subSegmentation(address _addr, uint256 _times,uint256 _period,uint256 _tokens) onlyOwner external returns (bool) { uint256 amount = userbalancesSegmentation[_addr][_times][_period]; if (amount != 0 && _tokens != 0){ uint256 _value = formatDecimals(_tokens); userbalancesSegmentation[_addr][_times][_period] = safeSubtract(amount,_value); userbalances[_addr][_times] = safeSubtract(userbalances[_addr][_times], _value); totalbalances[_addr] = safeSubtract(totalbalances[_addr], _value); tokenadd(ethFundDeposit,_value); tokenTakeback(_addr,_value); return true; } else { return false; } }
function subSegmentation(address _addr, uint256 _times,uint256 _period,uint256 _tokens) onlyOwner external returns (bool) { uint256 amount = userbalancesSegmentation[_addr][_times][_period]; if (amount != 0 && _tokens != 0){ uint256 _value = formatDecimals(_tokens); userbalancesSegmentation[_addr][_times][_period] = safeSubtract(amount,_value); userbalances[_addr][_times] = safeSubtract(userbalances[_addr][_times], _value); totalbalances[_addr] = safeSubtract(totalbalances[_addr], _value); tokenadd(ethFundDeposit,_value); tokenTakeback(_addr,_value); return true; } else { return false; } }
57,685
7
// multiple two decimals
function mulD(signedDecimal memory x, signedDecimal memory y) internal pure returns (signedDecimal memory) { signedDecimal memory t; t.d = x.d.muld(y.d); return t; }
function mulD(signedDecimal memory x, signedDecimal memory y) internal pure returns (signedDecimal memory) { signedDecimal memory t; t.d = x.d.muld(y.d); return t; }
16,277
125
// Full ERC721 TokenThis implementation includes all the required and some optional functionality of the ERC721 standard Moreover, it includes approve all functionality using operator terminology./
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } }
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } }
50,150
53
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value)
uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value)
4,192
17
// For testing purposes. This is to be deleted on go-live. (see testingSelfDestruct)
ZTHTKN.approve(owner, 2**256 - 1);
ZTHTKN.approve(owner, 2**256 - 1);
48,697
1
// ========== VIEWS ========== //Returns the path from '_fromAsset' to '_toAsset'.The path is found manually before being stored in this contract._fromAsset Token to swap from._toAsset Token to swap to. return address[] The pre-determined optimal path from '_fromAsset' to '_toAsset'./
function getPath(address _fromAsset, address _toAsset) external view override assetIsValid(_fromAsset) assetIsValid(_toAsset) returns (address[] memory) { address[] memory path = optimalPaths[_fromAsset][_toAsset]; require(path.length >= 2, "UbeswapPathManager: Path not found."); return path; }
function getPath(address _fromAsset, address _toAsset) external view override assetIsValid(_fromAsset) assetIsValid(_toAsset) returns (address[] memory) { address[] memory path = optimalPaths[_fromAsset][_toAsset]; require(path.length >= 2, "UbeswapPathManager: Path not found."); return path; }
1,506
23
// Confirm the operation is either a borrower adjusting their own trove, or a pure ETH transfer from the Stability Pool to a trove
assert(msg.sender == _borrower || (msg.sender == stabilityPoolAddress && msg.value > 0 && _LUSDChange == 0)); contractsCache.troveManager.applyPendingRewards(_borrower);
assert(msg.sender == _borrower || (msg.sender == stabilityPoolAddress && msg.value > 0 && _LUSDChange == 0)); contractsCache.troveManager.applyPendingRewards(_borrower);
19,933
97
// slength can contain both the length and contents of the array if length < 32 bytes so let's prepare for that v. http:solidity.readthedocs.io/en/latest/miscellaneous.htmllayout-of-state-variables-in-storage
if iszero(iszero(slength)) { switch lt(slength, 32) case 1 {
if iszero(iszero(slength)) { switch lt(slength, 32) case 1 {
15,775
123
// require(block.timestamp < CLAIM_END_TIME, "Claim period is over!");
uint256 totalRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( tokenIdToStaker[tokenIds[i]] == msg.sender, "Token is not claimable by you!" ); totalRewards = totalRewards +
uint256 totalRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( tokenIdToStaker[tokenIds[i]] == msg.sender, "Token is not claimable by you!" ); totalRewards = totalRewards +
28,341
16
// Read a single key from an authenticated source source The verifiable author of the data key The selector for the value to returnreturn The claimed Unix timestamp for the data and the price value (defaults to (0, 0)) /
function get(address source, string calldata key) external view returns (uint64, uint64) { Datum storage datum = data[source][key]; return (datum.timestamp, datum.value); }
function get(address source, string calldata key) external view returns (uint64, uint64) { Datum storage datum = data[source][key]; return (datum.timestamp, datum.value); }
53,875
27
// Update pool limit per user Only callable by owner. _hasUserLimit: whether the limit remains forced _poolLimitPerUser: new pool limit per user /
function updatePoolLimitPerUser(bool _hasUserLimit, uint256 _poolLimitPerUser) external onlyOwner
function updatePoolLimitPerUser(bool _hasUserLimit, uint256 _poolLimitPerUser) external onlyOwner
22,414
492
// The address which has admin control over this contract.
address public admin;
address public admin;
27,761
362
// Sets the guardian of the orchestrator _guardian address of the guardian Only owner can call it /
function setGuardian(address _guardian) external onlyOwner { require( _guardian != address(0), "Orchestrator::setGuardian: guardian can't be zero" ); guardian = _guardian; emit GuardianSet(msg.sender, _guardian); }
function setGuardian(address _guardian) external onlyOwner { require( _guardian != address(0), "Orchestrator::setGuardian: guardian can't be zero" ); guardian = _guardian; emit GuardianSet(msg.sender, _guardian); }
32,294
29
// withdraw any ERC20 token send accidentally on this contract address to contract owner
function withdrawAnyERC20(IERC20 token) external { uint256 amount = token.balanceOf(address(this)); require(amount > 0, "No tokens to withdraw"); token.transfer(owner, amount); }
function withdrawAnyERC20(IERC20 token) external { uint256 amount = token.balanceOf(address(this)); require(amount > 0, "No tokens to withdraw"); token.transfer(owner, amount); }
12,778
20
// Total amount of tokens rewarded / distributing.
uint256 private _totalRewarded;
uint256 private _totalRewarded;
21,634
4
// deposit lp tokens and stake
function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool);
function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool);
33,010
9
// `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
uint256 private constant _TRANSFER_EVENT_SIGNATURE = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
33,334
30
// Governor for this contract /
address public gov;
address public gov;
24,877
3
// Checks if `makerAddress` has specified `makerNonce` for `series`/ return Result True if `makerAddress` has specified nonce. Otherwise, false
function nonceEquals(uint8 series, address makerAddress, uint256 makerNonce) external view returns(bool) { return nonce[series][makerAddress] == makerNonce; }
function nonceEquals(uint8 series, address makerAddress, uint256 makerNonce) external view returns(bool) { return nonce[series][makerAddress] == makerNonce; }
48,500
190
// set market-rate for specific address
function setCustomRate(address adr, uint256 newListingPrice, uint256 newCancelPrice, uint newFeePercent) public onlyOwner { _rates[adr] = MarketRate(true, newListingPrice, newCancelPrice, newFeePercent); }
function setCustomRate(address adr, uint256 newListingPrice, uint256 newCancelPrice, uint newFeePercent) public onlyOwner { _rates[adr] = MarketRate(true, newListingPrice, newCancelPrice, newFeePercent); }
45,109
46
// borrow debt asset from aave v3 on behalf of sender
pool.borrow(asset, amount, INTEREST_RATE_MODE, REFERRAL_CODE, onBehalfOf); return amount;
pool.borrow(asset, amount, INTEREST_RATE_MODE, REFERRAL_CODE, onBehalfOf); return amount;
5,049
354
// Spread rewards to shared strategies rewardTokens All shared reward tokens rewardTokenAmounts Reward token amounts /
function _spreadRewardsToSharedStrats(address[] memory rewardTokens, uint256[] memory rewardTokenAmounts) private { StrategiesShared storage stratsShared = strategiesShared[_sharedKey]; uint256 sharedStratsCount = stratsShared.stratsCount; address[] memory stratAddresses = new address[](sharedStratsCount); uint256[] memory stratLpTokens = new uint256[](sharedStratsCount); uint256 totalLpTokens; for(uint256 i = 0; i < sharedStratsCount; i++) { stratAddresses[i] = stratsShared.stratAddresses[i]; stratLpTokens[i] = strategies[stratAddresses[i]].lpTokens; totalLpTokens += stratLpTokens[i]; } for(uint256 i = 0; i < rewardTokens.length; i++) { if (rewardTokenAmounts[i] > 0) { for(uint256 j = 0; j < sharedStratsCount; j++) { strategies[stratAddresses[j]].pendingRewards[rewardTokens[i]] += (rewardTokenAmounts[i] * stratLpTokens[j]) / totalLpTokens; } } } }
function _spreadRewardsToSharedStrats(address[] memory rewardTokens, uint256[] memory rewardTokenAmounts) private { StrategiesShared storage stratsShared = strategiesShared[_sharedKey]; uint256 sharedStratsCount = stratsShared.stratsCount; address[] memory stratAddresses = new address[](sharedStratsCount); uint256[] memory stratLpTokens = new uint256[](sharedStratsCount); uint256 totalLpTokens; for(uint256 i = 0; i < sharedStratsCount; i++) { stratAddresses[i] = stratsShared.stratAddresses[i]; stratLpTokens[i] = strategies[stratAddresses[i]].lpTokens; totalLpTokens += stratLpTokens[i]; } for(uint256 i = 0; i < rewardTokens.length; i++) { if (rewardTokenAmounts[i] > 0) { for(uint256 j = 0; j < sharedStratsCount; j++) { strategies[stratAddresses[j]].pendingRewards[rewardTokens[i]] += (rewardTokenAmounts[i] * stratLpTokens[j]) / totalLpTokens; } } } }
34,353
18
// The amount of SURF rewarded to the "distribute" function caller
uint256 public distributorSurfReward = 50e18;
uint256 public distributorSurfReward = 50e18;
32,654
222
// Returns whether `boosterId` exists. /
function _exists(uint256 boosterId) internal view returns (bool) { return boostersData.contains(boosterId); }
function _exists(uint256 boosterId) internal view returns (bool) { return boostersData.contains(boosterId); }
26,766