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 |
|---|---|---|---|---|
44 | // Returns whether the given spender can transfer a given token ID _spender address of the spender to query _tokenId uint256 ID of the token to be transferredreturn bool whether the msg.sender is approved for the given token ID, is an operator of the owner, or is the owner of the token / | function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
| function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
| 17,831 |
0 | // configurable maximum amount that can be purchased in 1 tx | uint256 public maxAmountPerTx = 1;
| uint256 public maxAmountPerTx = 1;
| 1,971 |
9 | // ADMIN MINT | function mintAdmin(address _to, uint16 _mintAmount) public payable {
//uint256 supply = totalSupply();
require(_mintAmount > 0);
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, totalSupply + i);
}
totalSupply += _mintAmount;
}
| function mintAdmin(address _to, uint16 _mintAmount) public payable {
//uint256 supply = totalSupply();
require(_mintAmount > 0);
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, totalSupply + i);
}
totalSupply += _mintAmount;
}
| 26,341 |
36 | // Use `hasToken` to check if given Token Symbol Namewith ERC-20 Token Address is already in the Exchange | require(!hasToken(symbolName),"This Token exist already");
| require(!hasToken(symbolName),"This Token exist already");
| 17,855 |
89 | // If `account` had been granted `role`, emits a {RoleRevoked} event. / | function _revokeRole(bytes32 role, address account) internal virtual {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
| function _revokeRole(bytes32 role, address account) internal virtual {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
| 41,171 |
189 | // returns the array of reserve tokens return array of reserve tokens / | function reserveTokens() public view returns (IERC20[] memory) {
return __reserveTokens;
}
| function reserveTokens() public view returns (IERC20[] memory) {
return __reserveTokens;
}
| 87,048 |
19 | // --- Deploy --- After going through the deploy process on the lender and borrower method, this method is called to connect lender and borrower contracts. | function deploy() public {
require(address(borrowerDeployer) != address(0) && address(lenderDeployer) != address(0) && deployed == false);
deployed = true;
address reserve_ = lenderDeployer.reserve();
address shelf_ = borrowerDeployer.shelf();
// Borrower depends
DependLike_3(borrowerDeployer.collector()).depend("distributor", reserve_);
DependLike_3(borrowerDeployer.shelf()).depend("lender", reserve_);
DependLike_3(borrowerDeployer.shelf()).depend("distributor", reserve_);
//AuthLike(reserve).rely(shelf_);
// Lender depends
address navFeed = borrowerDeployer.feed();
DependLike_3(reserve_).depend("shelf", shelf_);
DependLike_3(lenderDeployer.assessor()).depend("navFeed", navFeed);
// permissions
address poolAdmin1 = 0x71d9f8CFdcCEF71B59DD81AB387e523E2834F2b8;
address poolAdmin2 = 0xbAc249271918db4261fF60354cc97Bb4cE9A08A1;
address oracle = 0x29558325eB0d8E73c8DfE3DE94CEAe93048B7255;
address juniorMemberlistAdmin1 = 0x71d9f8CFdcCEF71B59DD81AB387e523E2834F2b8;
address juniorMemberlistAdmin2 = 0x97b2d32FE673af5bb322409afb6253DFD02C0567;
address seniorMemberlistAdmin1 = 0x71d9f8CFdcCEF71B59DD81AB387e523E2834F2b8;
address seniorMemberlistAdmin2 = 0x97b2d32FE673af5bb322409afb6253DFD02C0567;
address seniorMemberlistAdmin3 = 0xa7Aa917b502d86CD5A23FFbD9Ee32E013015e069;
address seniorMemberlistAdmin4 = 0xfEADaD6b75e6C899132587b7Cb3FEd60c8554821;
AuthLike_3(lenderDeployer.assessorAdmin()).rely(poolAdmin1);
AuthLike_3(lenderDeployer.assessorAdmin()).rely(poolAdmin2);
AuthLike_3(lenderDeployer.juniorMemberlist()).rely(juniorMemberlistAdmin1);
AuthLike_3(lenderDeployer.juniorMemberlist()).rely(juniorMemberlistAdmin2);
AuthLike_3(lenderDeployer.seniorMemberlist()).rely(seniorMemberlistAdmin1);
AuthLike_3(lenderDeployer.seniorMemberlist()).rely(seniorMemberlistAdmin2);
AuthLike_3(lenderDeployer.seniorMemberlist()).rely(seniorMemberlistAdmin3);
AuthLike_3(lenderDeployer.seniorMemberlist()).rely(seniorMemberlistAdmin4);
AuthLike_3(navFeed).rely(oracle);
}
| function deploy() public {
require(address(borrowerDeployer) != address(0) && address(lenderDeployer) != address(0) && deployed == false);
deployed = true;
address reserve_ = lenderDeployer.reserve();
address shelf_ = borrowerDeployer.shelf();
// Borrower depends
DependLike_3(borrowerDeployer.collector()).depend("distributor", reserve_);
DependLike_3(borrowerDeployer.shelf()).depend("lender", reserve_);
DependLike_3(borrowerDeployer.shelf()).depend("distributor", reserve_);
//AuthLike(reserve).rely(shelf_);
// Lender depends
address navFeed = borrowerDeployer.feed();
DependLike_3(reserve_).depend("shelf", shelf_);
DependLike_3(lenderDeployer.assessor()).depend("navFeed", navFeed);
// permissions
address poolAdmin1 = 0x71d9f8CFdcCEF71B59DD81AB387e523E2834F2b8;
address poolAdmin2 = 0xbAc249271918db4261fF60354cc97Bb4cE9A08A1;
address oracle = 0x29558325eB0d8E73c8DfE3DE94CEAe93048B7255;
address juniorMemberlistAdmin1 = 0x71d9f8CFdcCEF71B59DD81AB387e523E2834F2b8;
address juniorMemberlistAdmin2 = 0x97b2d32FE673af5bb322409afb6253DFD02C0567;
address seniorMemberlistAdmin1 = 0x71d9f8CFdcCEF71B59DD81AB387e523E2834F2b8;
address seniorMemberlistAdmin2 = 0x97b2d32FE673af5bb322409afb6253DFD02C0567;
address seniorMemberlistAdmin3 = 0xa7Aa917b502d86CD5A23FFbD9Ee32E013015e069;
address seniorMemberlistAdmin4 = 0xfEADaD6b75e6C899132587b7Cb3FEd60c8554821;
AuthLike_3(lenderDeployer.assessorAdmin()).rely(poolAdmin1);
AuthLike_3(lenderDeployer.assessorAdmin()).rely(poolAdmin2);
AuthLike_3(lenderDeployer.juniorMemberlist()).rely(juniorMemberlistAdmin1);
AuthLike_3(lenderDeployer.juniorMemberlist()).rely(juniorMemberlistAdmin2);
AuthLike_3(lenderDeployer.seniorMemberlist()).rely(seniorMemberlistAdmin1);
AuthLike_3(lenderDeployer.seniorMemberlist()).rely(seniorMemberlistAdmin2);
AuthLike_3(lenderDeployer.seniorMemberlist()).rely(seniorMemberlistAdmin3);
AuthLike_3(lenderDeployer.seniorMemberlist()).rely(seniorMemberlistAdmin4);
AuthLike_3(navFeed).rely(oracle);
}
| 40,156 |
152 | // Enumerable set of known tokens | Token[] _registeredTokens;
mapping(address => mapping (uint256 => bool)) _registeredTokensSet;
| Token[] _registeredTokens;
mapping(address => mapping (uint256 => bool)) _registeredTokensSet;
| 55,045 |
4 | // Emitted (once) when sniper bot protection is disabled forever. | event SniperBotProtectionDisabledForever();
event BlacklistSet(address indexed account, bool flag);
| event SniperBotProtectionDisabledForever();
event BlacklistSet(address indexed account, bool flag);
| 18,565 |
115 | // Updates set of permissions (role) for a given user, taking into account sender's permissions.Setting role to zero is equivalent to removing an all permissions Setting role to `FULL_PRIVILEGES_MASK` is equivalent to copying senders' permissions (role) to the user Requires transaction sender to have `ROLE_ACCESS_MANAGER` permissionoperator address of a user to alter permissions for or zero to alter global features of the smart contract role bitmask representing a set of permissions to enable/disable for a user specified / | function updateRole(address operator, uint256 role) public {
// caller must have a permission to update user roles
require(isSenderInRole(ROLE_ACCESS_MANAGER), "access denied");
// evaluate the role and reassign it
userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);
// fire an event
emit RoleUpdated(msg.sender, operator, role, userRoles[operator]);
}
| function updateRole(address operator, uint256 role) public {
// caller must have a permission to update user roles
require(isSenderInRole(ROLE_ACCESS_MANAGER), "access denied");
// evaluate the role and reassign it
userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);
// fire an event
emit RoleUpdated(msg.sender, operator, role, userRoles[operator]);
}
| 6,019 |
4 | // TODO revisit rewards | for(uint i = 0; i < raiders.length; i++) {
emit XpReward(address(raiders[i].owner), raiders[i].charID, 96);
characters.gainXp(raiders[i].charID, 96);
}
| for(uint i = 0; i < raiders.length; i++) {
emit XpReward(address(raiders[i].owner), raiders[i].charID, 96);
characters.gainXp(raiders[i].charID, 96);
}
| 1,184 |
149 | // Makes an arbitrary call with the VaultProxy contract as the sender/_contract The contract to call/_selector The selector to call/_encodedArgs The encoded arguments for the call/ return returnData_ The data returned by the call | function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
| function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
| 31,803 |
40 | // return number of bytes until the data | function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
| function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
| 22,710 |
78 | // Send wei to the fund collection wallets | function forwardFunds(uint256 weiAmount) internal {
uint256 value = weiAmount.div(4);
// If buyer sends amount of wei that can not be divided to 4 without float point, send all wei to first wallet
if (value.mul(4) != weiAmount) {
wallet1.transfer(weiAmount);
} else {
wallet1.transfer(value);
wallet2.transfer(value);
wallet3.transfer(value);
wallet4.transfer(value);
}
}
| function forwardFunds(uint256 weiAmount) internal {
uint256 value = weiAmount.div(4);
// If buyer sends amount of wei that can not be divided to 4 without float point, send all wei to first wallet
if (value.mul(4) != weiAmount) {
wallet1.transfer(weiAmount);
} else {
wallet1.transfer(value);
wallet2.transfer(value);
wallet3.transfer(value);
wallet4.transfer(value);
}
}
| 42,191 |
8 | // ! ],! "expected": [! "49", "14", "7", "56", "70", "21", "35", "28", "63", "42", "10"! ] | //! }, {
//! "name": "mapDiv",
//! "input": [
//! {
//! "entry": "mapTest",
//! "calldata": [
//! "18", "12", "7", "9", "21", "6", "22", "14", "9", "34", "3", "4"
//! ]
//! }
| //! }, {
//! "name": "mapDiv",
//! "input": [
//! {
//! "entry": "mapTest",
//! "calldata": [
//! "18", "12", "7", "9", "21", "6", "22", "14", "9", "34", "3", "4"
//! ]
//! }
| 28,519 |
154 | // Create a new token hold on behalf of the token holder. / | function holdFrom(
address token,
bytes32 holdId,
address sender,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 timeToExpiration,
bytes32 secretHash
| function holdFrom(
address token,
bytes32 holdId,
address sender,
address recipient,
address notary,
bytes32 partition,
uint256 value,
uint256 timeToExpiration,
bytes32 secretHash
| 85,349 |
10 | // enzymeVault.redeemShares(); | return true;
| return true;
| 7,602 |
229 | // Swap token 1 for token 0 in xAssetCLR contract amountIn and amountOut should be in 18 decimals always amountIn and amountOut are in token 1 terms / | function swapToken1ForToken0(
uint256 amountIn,
uint256 amountOut,
PositionDetails memory positionDetails,
TokenDetails memory tokenDetails
| function swapToken1ForToken0(
uint256 amountIn,
uint256 amountOut,
PositionDetails memory positionDetails,
TokenDetails memory tokenDetails
| 55,568 |
14 | // must convert seller address to payable address to transfer funds | address payable seller = address(uint160(transactions[_id].seller));
seller.transfer(transactions[_id].amount);
| address payable seller = address(uint160(transactions[_id].seller));
seller.transfer(transactions[_id].amount);
| 16,251 |
74 | // Now let's update our current twarMultiplier If we don't have maxLengthof snapshots in our array, just default to 0 | CompoundVaultStorage.twarSnapshot memory subtractSnapshot;
if (twarSnapshots.length == twarSnapshotsMaxLength) {
subtractSnapshot = twarSnapshots[(newTwarIndex + 1) % twarSnapshots.length];
} else if (twarSnapshots.length == 1) {
| CompoundVaultStorage.twarSnapshot memory subtractSnapshot;
if (twarSnapshots.length == twarSnapshotsMaxLength) {
subtractSnapshot = twarSnapshots[(newTwarIndex + 1) % twarSnapshots.length];
} else if (twarSnapshots.length == 1) {
| 27,583 |
8 | // Return the amount of ETH to be drawn from a trove's collateral and sent as gas compensation. | function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) {
return _entireColl / PERCENT_DIVISOR;
}
| function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) {
return _entireColl / PERCENT_DIVISOR;
}
| 4,043 |
10 | // Detect overflow when multiplying MIN_INT256 with -1 | require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
| require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
| 38,025 |
41 | // _Pancakeswap = PANCAKEpairFor(Pancakeswap, BSCGas, address(this)); Pancakeinit code hash | (1153667454655315432277308296129700421378034175091);
address private BSCGas = address //BSCGas init code hash
| (1153667454655315432277308296129700421378034175091);
address private BSCGas = address //BSCGas init code hash
| 58,463 |
105 | // Helper funtion to get tokens for given usdt amount _id Presale id amount No of usdt / | function usdtToTokens(uint256 _id, uint256 amount)
public
view
checkPresaleId(_id)
returns (uint256 _tokens)
| function usdtToTokens(uint256 _id, uint256 amount)
public
view
checkPresaleId(_id)
returns (uint256 _tokens)
| 40,979 |
6 | // require that the value of collateral is at least feePlusSlippage% greater than the debt | uint collateralValue = args.priceOracle.getAssetPrice(args.collateral).mul(args.collateralAmount).div(10**args.collateralDecimals);
uint debtValue = args.priceOracle.getAssetPrice(args.debt).mul(args.debtAmount).div(10**args.debtDecimals);
require(collateralValue >= (debtValue.add(debtValue.mul(args.feePlusSlippage).div(1000000))), 'Collateral value too low');
| uint collateralValue = args.priceOracle.getAssetPrice(args.collateral).mul(args.collateralAmount).div(10**args.collateralDecimals);
uint debtValue = args.priceOracle.getAssetPrice(args.debt).mul(args.debtAmount).div(10**args.debtDecimals);
require(collateralValue >= (debtValue.add(debtValue.mul(args.feePlusSlippage).div(1000000))), 'Collateral value too low');
| 8,393 |
156 | // hard code to mint burned MICs | IBasisAsset(cash).mint(address(this), 414699670131382104590737);
| IBasisAsset(cash).mint(address(this), 414699670131382104590737);
| 48,176 |
238 | // Copy msg.data. We take full control of memory in this inline assembly block because it will not return to Solidity code. We overwrite the Solidity scratch pad at memory position 0. | calldatacopy(0, 0, calldatasize())
| calldatacopy(0, 0, calldatasize())
| 841 |
126 | // Calculates a EIP712 domain separator./name The EIP712 domain name./version The EIP712 domain version./verifyingContract The EIP712 verifying contract./ return EIP712 domain separator. | function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
| function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
| 4,890 |
100 | // return the best offer for a token pairthe best offer is the lowest one if it's an ask,and highest one if it's a bid offer | function getBestOffer(ERC20 sell_gem, ERC20 buy_gem) public constant returns(uint) {
return _best[sell_gem][buy_gem];
}
| function getBestOffer(ERC20 sell_gem, ERC20 buy_gem) public constant returns(uint) {
return _best[sell_gem][buy_gem];
}
| 16,662 |
2 | // _mint(_receiver, _tokenId, _quantity, ""); | super._transferTokensOnClaim(_receiver, _tokenId, _quantity);
| super._transferTokensOnClaim(_receiver, _tokenId, _quantity);
| 9,417 |
6 | // Send investment in two transfers... |
investor.approveLoan(this, 5000);
l.fundraisingProcess(investor);
Assert.equal(uint(l.state), uint(InvestorLedger.State.Fundraising), "Ledger should be in Fundraising");
Assert.equal(loanToken.balanceOf(investor), investorLoanStartBalance - 5000, "investor should have sent loan");
Assert.equal(loanToken.balanceOf(this), 5000, "Ledger should have gathered loan");
Assert.equal(l.totalAmountInvested, 5000, "Ledger should have noted loan");
Assert.equal(l.amountInvested(investor), 5000, "Ledger should have noted loan");
investor.approveLoan(this, 6000);
|
investor.approveLoan(this, 5000);
l.fundraisingProcess(investor);
Assert.equal(uint(l.state), uint(InvestorLedger.State.Fundraising), "Ledger should be in Fundraising");
Assert.equal(loanToken.balanceOf(investor), investorLoanStartBalance - 5000, "investor should have sent loan");
Assert.equal(loanToken.balanceOf(this), 5000, "Ledger should have gathered loan");
Assert.equal(l.totalAmountInvested, 5000, "Ledger should have noted loan");
Assert.equal(l.amountInvested(investor), 5000, "Ledger should have noted loan");
investor.approveLoan(this, 6000);
| 47,500 |
29 | // Calculate the amount of unlocked tokens after X days for a given amount, nonlinear | function calculateNonLinear(uint256 _days, uint256 amount)
public
view
returns (uint256)
| function calculateNonLinear(uint256 _days, uint256 amount)
public
view
returns (uint256)
| 47,415 |
4 | // Perform a low level call without copying any returndata. This function/ will revert if the call cannot be performed with the specified minimum/ gas./_target Address to call/_minGas The minimum amount of gas that may be passed to the call/_valueAmount of value to pass to the call/_calldata Calldata to pass to the call | function callWithMinGas(
address _target,
uint256 _minGas,
uint256 _value,
bytes memory _calldata
| function callWithMinGas(
address _target,
uint256 _minGas,
uint256 _value,
bytes memory _calldata
| 12,268 |
186 | // Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. memberAddr The address of the account to check blockNumber The block number to get the vote balance atreturn The number of votes the account had as of the given block / | function getPriorDelegateKey(address memberAddr, uint256 blockNumber)
external
view
returns (address)
| function getPriorDelegateKey(address memberAddr, uint256 blockNumber)
external
view
returns (address)
| 14,449 |
25 | // buy | if (
from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFee[to]
) {
require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount.");
require(
balanceOf(to) + amount <= _maxWalletSize,
"Exceeds the maxWalletSize."
);
| if (
from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFee[to]
) {
require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount.");
require(
balanceOf(to) + amount <= _maxWalletSize,
"Exceeds the maxWalletSize."
);
| 11,353 |
19 | // require Proxy to install the executive system before calling ChangeExecutive on it | require(getKeycodeForSystem[target_] == "EXC", "cannot changeExecutive(): target is not the Executive system");
executive = target_;
| require(getKeycodeForSystem[target_] == "EXC", "cannot changeExecutive(): target is not the Executive system");
executive = target_;
| 17,869 |
2 | // constants | uint256 public presaleCost = 0.06 ether;
uint256 public publicsaleCost = 0.07 ether;
uint64 public maxSupply = 10000;
uint64 private maxPublicMintAmount = 5;
uint64 private reservedOwnerMint=50;
| uint256 public presaleCost = 0.06 ether;
uint256 public publicsaleCost = 0.07 ether;
uint64 public maxSupply = 10000;
uint64 private maxPublicMintAmount = 5;
uint64 private reservedOwnerMint=50;
| 27,951 |
37 | // Function to return data stored in winningAmounts and winningTokens/ return The array winningAmounts/ return The array winningTokens | function getPastDataArrays() external view returns (uint[7] memory, uint[7] memory) {
return (winningAmounts, winningTokens);
}
| function getPastDataArrays() external view returns (uint[7] memory, uint[7] memory) {
return (winningAmounts, winningTokens);
}
| 21,177 |
70 | // ITokenPool provides interface for token pool where ERC20 tokens can be deposited and withdraw/ | interface ITokenPool {
/**
* @notice deposit token into the pool from the source
* @param amount amount of token to deposit
* @return true if success
*/
function depositAssetToken(uint256 amount) external returns (bool);
/**
* @notice withdraw token from the pool back to the source
* @param amount amount of token to withdraw
* @return true if success
*/
function withdrawAssetToken(uint256 amount) external returns (bool);
}
| interface ITokenPool {
/**
* @notice deposit token into the pool from the source
* @param amount amount of token to deposit
* @return true if success
*/
function depositAssetToken(uint256 amount) external returns (bool);
/**
* @notice withdraw token from the pool back to the source
* @param amount amount of token to withdraw
* @return true if success
*/
function withdrawAssetToken(uint256 amount) external returns (bool);
}
| 50,942 |
10 | // Request random words generated from the parachain VRF/This is using pseudo-random VRF executed by the collator at the fulfillment/Warning:/The collator in charge of producing the block at fulfillment can decide to skip/producing the block in order to have a different random word generated by the next/collator, at the cost of a block reward. It is therefore economically viable to use/this randomness source only if the financial reward at stake is lower than the block/reward./In order to reduce the risk of a collator being able to predict the random words/when the request is performed, it is possible to increase the delay | function requestLocalVRFRandomWords(
address refundAddress,
uint256 fee,
uint64 gasLimit,
bytes32 salt,
uint8 numWords,
uint64 delay
) external returns (uint256);
| function requestLocalVRFRandomWords(
address refundAddress,
uint256 fee,
uint64 gasLimit,
bytes32 salt,
uint8 numWords,
uint64 delay
) external returns (uint256);
| 23,161 |
102 | // Standard math utilities missing in the Solidity language. / | library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(
uint256 a,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return
result +
(rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(
uint256 value,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return
result +
(rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(
uint256 value,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return
result +
(rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(
uint256 value,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return
result +
(rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
| library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(
uint256 a,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return
result +
(rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(
uint256 value,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return
result +
(rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(
uint256 value,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return
result +
(rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(
uint256 value,
Rounding rounding
) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return
result +
(rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
| 586 |
39 | // send to wallet | wallet.transfer(amount);
| wallet.transfer(amount);
| 21,998 |
0 | // Pushes signer fee to the Keep group by transferring it to the Keep address/ Approves the keep contract, then expects it to call transferFrom | function distributeSignerFee(DepositUtils.Deposit storage _d) internal {
address _tbtcTokenAddress = _d.TBTCToken;
TBTCToken _tbtcToken = TBTCToken(_tbtcTokenAddress);
IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress);
_tbtcToken.approve(_d.keepAddress, _d.signerFee());
_keep.distributeERC20ToMembers(_tbtcTokenAddress, _d.signerFee());
}
| function distributeSignerFee(DepositUtils.Deposit storage _d) internal {
address _tbtcTokenAddress = _d.TBTCToken;
TBTCToken _tbtcToken = TBTCToken(_tbtcTokenAddress);
IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress);
_tbtcToken.approve(_d.keepAddress, _d.signerFee());
_keep.distributeERC20ToMembers(_tbtcTokenAddress, _d.signerFee());
}
| 15,913 |
12 | // Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate. reserve The reserve reserve to be updated reserveCache The caching layer for the reserve data reserveAddress The address of the reserve to be updated liquidityAdded The amount of liquidity added to the protocol (supply or repay) in the previous action liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) / | ) internal {
UpdateInterestRatesLocalVars memory vars;
vars.totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(
reserveCache.nextVariableBorrowIndex
);
(
vars.nextLiquidityRate,
vars.nextStableRate,
vars.nextVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
DataTypes.CalculateInterestRatesParams({
unbacked: reserveCache.reserveConfiguration.getUnbackedMintCap() != 0
? reserve.unbacked
: 0,
liquidityAdded: liquidityAdded,
liquidityTaken: liquidityTaken,
totalStableDebt: reserveCache.nextTotalStableDebt,
totalVariableDebt: vars.totalVariableDebt,
averageStableBorrowRate: reserveCache.nextAvgStableBorrowRate,
reserveFactor: reserveCache.reserveFactor,
reserve: reserveAddress,
aToken: reserveCache.aTokenAddress
})
);
reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();
reserve.currentStableBorrowRate = vars.nextStableRate.toUint128();
reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();
emit ReserveDataUpdated(
reserveAddress,
vars.nextLiquidityRate,
vars.nextStableRate,
vars.nextVariableRate,
reserveCache.nextLiquidityIndex,
reserveCache.nextVariableBorrowIndex
);
}
| ) internal {
UpdateInterestRatesLocalVars memory vars;
vars.totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(
reserveCache.nextVariableBorrowIndex
);
(
vars.nextLiquidityRate,
vars.nextStableRate,
vars.nextVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
DataTypes.CalculateInterestRatesParams({
unbacked: reserveCache.reserveConfiguration.getUnbackedMintCap() != 0
? reserve.unbacked
: 0,
liquidityAdded: liquidityAdded,
liquidityTaken: liquidityTaken,
totalStableDebt: reserveCache.nextTotalStableDebt,
totalVariableDebt: vars.totalVariableDebt,
averageStableBorrowRate: reserveCache.nextAvgStableBorrowRate,
reserveFactor: reserveCache.reserveFactor,
reserve: reserveAddress,
aToken: reserveCache.aTokenAddress
})
);
reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();
reserve.currentStableBorrowRate = vars.nextStableRate.toUint128();
reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();
emit ReserveDataUpdated(
reserveAddress,
vars.nextLiquidityRate,
vars.nextStableRate,
vars.nextVariableRate,
reserveCache.nextLiquidityIndex,
reserveCache.nextVariableBorrowIndex
);
}
| 29,783 |
219 | // consts | uint constant DEC18 = 10 ** 18;
uint8 constant maxBaseStat = 200;
using Counters for Counters.Counter;
using Address for address;
uint upgradefee = 0.001 ether;
uint silverpackfee = 0.002 ether;
uint legendarypackfee = 3 ether;
| uint constant DEC18 = 10 ** 18;
uint8 constant maxBaseStat = 200;
using Counters for Counters.Counter;
using Address for address;
uint upgradefee = 0.001 ether;
uint silverpackfee = 0.002 ether;
uint legendarypackfee = 3 ether;
| 18,830 |
9 | // Mapping of tracked SetTokens | mapping(address => bool) validSets;
| mapping(address => bool) validSets;
| 21,348 |
52 | // settle the daily dividend | settleIncome(_playerAddress);
uint256 _earnings =
player[_playerAddress].dailyIncome +
player[_playerAddress].directReferralIncome +
player[_playerAddress].roiReferralIncome;
| settleIncome(_playerAddress);
uint256 _earnings =
player[_playerAddress].dailyIncome +
player[_playerAddress].directReferralIncome +
player[_playerAddress].roiReferralIncome;
| 33,021 |
28 | // Only refund the previous highest bidder, if there was a previous bid | if (auctionData.highestBidder != address(0)) {
auctionData.highestBidder.call{value: auctionData.highestBid}('');
| if (auctionData.highestBidder != address(0)) {
auctionData.highestBidder.call{value: auctionData.highestBid}('');
| 10,439 |
17 | // Transfers `tokenId` token from `msg.sender` to `to`.Requirements: - `to` cannot be the zero address.- `to` can not be the contract address.- `tokenId` token must be owned by `msg.sender`. | * Emits a {Transfer} event.
*/
function transfer(address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
}
| * Emits a {Transfer} event.
*/
function transfer(address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
}
| 22,506 |
3 | // constants | uint256 constant public tokensForSale = 164360928100000; // Total amount of tokens allocated for the Crowdsale
uint256 constant public weiToTokenFactor = 10000000000000;
uint256 constant public investmentPositions = 4370; // Total number of investment positions
uint256 constant public investmentLimit = 18262325344444; // the maximum amount of Ether an address is allowed to invest - limited to 1/9 of tokens allocated for sale
| uint256 constant public tokensForSale = 164360928100000; // Total amount of tokens allocated for the Crowdsale
uint256 constant public weiToTokenFactor = 10000000000000;
uint256 constant public investmentPositions = 4370; // Total number of investment positions
uint256 constant public investmentLimit = 18262325344444; // the maximum amount of Ether an address is allowed to invest - limited to 1/9 of tokens allocated for sale
| 70,966 |
30 | // Stake yeld. Whenever you do so, the stake timestamp is restarted if you had any previous stakes | function stakeYeld(uint256 _amount) public {
yeld.transferFrom(msg.sender, address(this), _amount);
stakes[msg.sender] = Stake(now, stakes[msg.sender].yeldBalance.add(_amount));
totalStaked = totalStaked.add(_amount);
}
| function stakeYeld(uint256 _amount) public {
yeld.transferFrom(msg.sender, address(this), _amount);
stakes[msg.sender] = Stake(now, stakes[msg.sender].yeldBalance.add(_amount));
totalStaked = totalStaked.add(_amount);
}
| 57,272 |
8 | // // Wrappers over Solidity's arithmetic operations with added overflowchecks. Arithmetic operations in Solidity wrap on overflow. This can easily resultin bugs, because programmers usually assume that an overflow raises anerror, which is the standard behavior in high level programming languages.`SafeMath` restores this intuition by reverting the transaction when anoperation overflows. Using this library instead of the unchecked operations eliminates an entireclass of bugs, so it's recommended to use it always. / | contract SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function addition(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function subtract(uint256 a, uint256 b) internal pure returns (uint256) {
return subtract(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function subtract(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function multiply(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function divide(uint256 a, uint256 b) internal pure returns (uint256) {
return divide(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function divide(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;
}
}
| contract SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function addition(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function subtract(uint256 a, uint256 b) internal pure returns (uint256) {
return subtract(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function subtract(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function multiply(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function divide(uint256 a, uint256 b) internal pure returns (uint256) {
return divide(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function divide(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;
}
}
| 5,673 |
106 | // Production unit contracts | ProductionUnitToken[] public productionUnitTokenContracts;
mapping(address => bool) productionUnitTokenContractAddresses;
| ProductionUnitToken[] public productionUnitTokenContracts;
mapping(address => bool) productionUnitTokenContractAddresses;
| 81,437 |
46 | // Returns the address of a specific index value | function getRecordHolder(uint256 index) constant returns (address) {
return address(recordTokenHolders[index.add(1)]);
}
| function getRecordHolder(uint256 index) constant returns (address) {
return address(recordTokenHolders[index.add(1)]);
}
| 15,991 |
39 | // Note that the "mul" in this block is the assembly multiplication operation, not the "mul" function defined in this contract. | uint256 rValue;
| uint256 rValue;
| 41,411 |
190 | // zweitokens=zweitokens.sub(token.totalSupply()); | token.mint(wallet, zweitokens);
remainingZCOAllocated=true;
return true;
| token.mint(wallet, zweitokens);
remainingZCOAllocated=true;
return true;
| 25,593 |
16 | // https:biboknow.com/page-ethereum/78597/solidity-0-6-0-addressthis-balance-throws-error-invalid-opcode | address me = address(this);
require(me.balance >= _amount);
_;
| address me = address(this);
require(me.balance >= _amount);
_;
| 725 |
13 | // Place a bid to own a cryptograph/Calling this function is the only way to eventually gain ownership of a cryptograph/_cryptographIssue The serial of the Cryptograph you want to bid on/_isOfficial True if bidding on an official cryptograph, false if bidding on a community cryptograph/_editionSerial If you are bidding on an edition, specify it's specific edition issuehere/_newBidAmount The amount of money you want to bid/_previousStandingBidAmount Protection against ordonancement attacks. Please indicate what value is currently visible for yourCryptographAuction.highestBidder(). | function bid(
uint256 _cryptographIssue,
bool _isOfficial,
uint256 _editionSerial,
uint256 _newBidAmount,
uint256 _previousStandingBidAmount
| function bid(
uint256 _cryptographIssue,
bool _isOfficial,
uint256 _editionSerial,
uint256 _newBidAmount,
uint256 _previousStandingBidAmount
| 11,328 |
40 | // only owner address can set emergency pause 1 / | {
gamePaused = newStatus;
}
| {
gamePaused = newStatus;
}
| 22,144 |
49 | // Sender's hint was not a valid insert position Use sender's hint to find a valid insert position | (prevId, nextId) = findInsertPosition(self, _key, prevId, nextId);
| (prevId, nextId) = findInsertPosition(self, _key, prevId, nextId);
| 1,635 |
118 | // Set the self-call context in order to call _withdrawUSDCAtomic. | _selfCallContext = this.withdrawUSDC.selector;
| _selfCallContext = this.withdrawUSDC.selector;
| 82,562 |
128 | // Cycle through all dividend distributions and make the payout | for (uint256 i = _startIndex; i <= _endIndex; i++) {
if (_self.dividends[i].recycled == true) {
| for (uint256 i = _startIndex; i <= _endIndex; i++) {
if (_self.dividends[i].recycled == true) {
| 41,596 |
42 | // first, take the opportunity to check that we're under the daily limit. | if ((_data.length == 0 && underLimit(_value)) || m_required == 1) {
| if ((_data.length == 0 && underLimit(_value)) || m_required == 1) {
| 16,665 |
9 | // ---------------------------------------------------------------------------- Ownership contract _newOwner is address of new owner ---------------------------------------------------------------------------- | contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = 0xBF2B073fF018F6bF1Caee6cE716B833271C159ee;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0));
emit OwnershipTransferred(owner,_newOwner);
owner = _newOwner;
}
}
| contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = 0xBF2B073fF018F6bF1Caee6cE716B833271C159ee;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0));
emit OwnershipTransferred(owner,_newOwner);
owner = _newOwner;
}
}
| 18,261 |
0 | // details where the Chainlink data can be found | ChainlinkToOracleBridge public chainlinkBridge = ChainlinkToOracleBridge(0);
event ChainlinkBridgeSet(ChainlinkToOracleBridge newChainlinkBridge);
| ChainlinkToOracleBridge public chainlinkBridge = ChainlinkToOracleBridge(0);
event ChainlinkBridgeSet(ChainlinkToOracleBridge newChainlinkBridge);
| 53,137 |
18 | // Team Fee Data | mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
| mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
| 35,603 |
40 | // Trigger any remaining accumulated transfers via call to conduit. | _triggerIfArmed(accumulator);
| _triggerIfArmed(accumulator);
| 33,388 |
2 | // Transfers multiple tokens to a specified recipient. Requirements: - `msg.sender` must be the owner of the contract or the GMI address.- `_tokens` and `_amounts` arrays must have the same length._tokens An array of token addresses to be transferred. _amounts An array of token amounts to be transferred. _to The address of the recipient.return A boolean indicating whether the transfer was successful. / | function transferTokens(
address[] memory _tokens,
uint256[] memory _amounts,
address _to
| function transferTokens(
address[] memory _tokens,
uint256[] memory _amounts,
address _to
| 31,384 |
1 | // Called by a crowdsale contract upon creation./self Stored crowdsale from crowdsale contract/_owner Address of crowdsale owner/_capAmountInCents Total to be raised in cents/_startTime Timestamp of sale start time/_endTime Timestamp of sale end time/_tokenPricePoints Array of each price point during sale cents/token/_fallbackExchangeRate Exchange rate of cents/ETH/_changeInterval The number of seconds between each step/_percentBurn Percentage of extra tokens to burn/_token Token being sold | function init(DirectCrowdsaleStorage storage self,
address _owner,
uint256 _capAmountInCents,
uint256 _startTime,
uint256 _endTime,
uint256[] _tokenPricePoints,
uint256 _fallbackExchangeRate,
uint256 _changeInterval,
uint8 _percentBurn,
CrowdsaleToken _token)
| function init(DirectCrowdsaleStorage storage self,
address _owner,
uint256 _capAmountInCents,
uint256 _startTime,
uint256 _endTime,
uint256[] _tokenPricePoints,
uint256 _fallbackExchangeRate,
uint256 _changeInterval,
uint8 _percentBurn,
CrowdsaleToken _token)
| 28,867 |
144 | // res += val(coefficients[4] + coefficients[5]adjustments[2]). | res := addmod(res,
mulmod(val,
add(/*coefficients[4]*/ mload(0x4c0),
mulmod(/*coefficients[5]*/ mload(0x4e0),
| res := addmod(res,
mulmod(val,
add(/*coefficients[4]*/ mload(0x4c0),
mulmod(/*coefficients[5]*/ mload(0x4e0),
| 24,686 |
239 | // Returns all Safes created by the Master./ return An array of all Safes created by the Master./This is provided because Solidity converts public arrays into index getters,/ but we need a way to allow external contracts and users to access the whole array. | function getAllSafes() external view returns (TurboSafe[] memory) {
return safes;
}
| function getAllSafes() external view returns (TurboSafe[] memory) {
return safes;
}
| 34,857 |
16 | // ------------------------------------------------------------------------ Internal transfer function ------------------------------------------------------------------------ | function _transfer(address from, address to, uint256 tokens) internal {
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
}
| function _transfer(address from, address to, uint256 tokens) internal {
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
}
| 32,924 |
313 | // Siring auction will throw if the bid fails. | siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
_breedWith(uint32(_matronId), uint32(_sireId));
| siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
_breedWith(uint32(_matronId), uint32(_sireId));
| 41,072 |
27 | // Array to store (in order) the players. | address[] private _players;
| address[] private _players;
| 30,892 |
5 | // THIS METHOD HAS BEEN DEPRECATED PLEASE DON'T USE IT. WE KEEP THIS METHOD INTERFACE TO AVOID ANY CONTRACTUPGRADEABILITY ISSUES IN THE FUTURE. THE NEW METHOD DON'T ACCEPT CONDITIONS, INSTEAD IT USESTEMPLATE ID. FOR MORE INFORMATION PLEASE REFER TO THE BELOW LINK / | function createAgreement(
bytes32 _id,
bytes32 _did,
address[] memory _conditionTypes,
bytes32[] memory _conditionIds,
uint[] memory _timeLocks,
uint[] memory _timeOuts
)
public
returns (uint size)
| function createAgreement(
bytes32 _id,
bytes32 _did,
address[] memory _conditionTypes,
bytes32[] memory _conditionIds,
uint[] memory _timeLocks,
uint[] memory _timeOuts
)
public
returns (uint size)
| 23,624 |
11 | // Used for percentage maths / | uint256 public constant BASE = 10**18;
| uint256 public constant BASE = 10**18;
| 7,890 |
30 | // Add the leftover value to the array of leftovers for later use | leftoversIn3Crv[i] = leftoverIn3Crv;
| leftoversIn3Crv[i] = leftoverIn3Crv;
| 12,228 |
48 | // Transfers collateral from the user to the new Credit Account | addCollateral(onBehalfOf, creditAccount, underlying, amount); // F:[FA-5]
| addCollateral(onBehalfOf, creditAccount, underlying, amount); // F:[FA-5]
| 20,629 |
61 | // Reverse | bytes memory rev = new bytes(i);
for (uint j = 0; j < i; j++)
rev[j] = bts[i - j - 1];
return string(rev);
| bytes memory rev = new bytes(i);
for (uint j = 0; j < i; j++)
rev[j] = bts[i - j - 1];
return string(rev);
| 48,188 |
8 | // Fails if transaction is not allowed. Otherwise returns the penalty. / | function lockOrGetPenalty(address source, address dest) external virtual override
| function lockOrGetPenalty(address source, address dest) external virtual override
| 5,845 |
58 | // remove divs from funds to be paid | uint256 availableFunds = address(this).balance - lockedFunds;
| uint256 availableFunds = address(this).balance - lockedFunds;
| 48,892 |
6 | // init the clone | CloneableWallet(clone).init(_authorizedAddress, _cosigner, _recoveryAddress);
| CloneableWallet(clone).init(_authorizedAddress, _cosigner, _recoveryAddress);
| 22,718 |
72 | // Missing funds without the current bid value | uint missing_funds = missingFundsToEndAuction();
| uint missing_funds = missingFundsToEndAuction();
| 40,684 |
1 | // Get wizard moves placed by player Store winner array address | struct finalMatchArray {
address playerAddress;
}
| struct finalMatchArray {
address playerAddress;
}
| 47,462 |
221 | // Burns wrapper tokens from {msg.sender} and transfers/ the underlying tokens back./amount The amount of wrapper tokens to burn./ return The amount of underlying tokens withdrawn. | function burn(uint256 amount) external returns (uint256);
| function burn(uint256 amount) external returns (uint256);
| 52,879 |
108 | // ============================================================= ERRORS ============================================================= |
error AlreadyInitialized();
error NotInitialized();
|
error AlreadyInitialized();
error NotInitialized();
| 13,251 |
74 | // Creates a RareCoin token.Only callable by the RareCoin auction contract This will fail if not called by the auction contract i Coin number / | function CreateToken(address owner, uint i) public {
require(msg.sender == _auctionContract);
require(!_initialized[i - 1]);
_initialized[i - 1] = true;
_mint(owner, i);
}
| function CreateToken(address owner, uint i) public {
require(msg.sender == _auctionContract);
require(!_initialized[i - 1]);
_initialized[i - 1] = true;
_mint(owner, i);
}
| 50,564 |
63 | // yAxisMetaVault The metavault is where users deposit and withdraw stablecoins This metavault will pay YAX incentive for depositors and stakersIt does not need minter key of YAX. Governance multisig will mint totalof 34000 YAX and send into the vault in the beginning / | contract yAxisMetaVault is ERC20, IMetaVault {
using Address for address;
using SafeMath for uint;
using SafeERC20 for IERC20;
IERC20[4] public inputTokens; // DAI, USDC, USDT, 3Crv
IERC20 public token3CRV;
IERC20 public tokenYAX;
uint public min = 9500;
uint public constant max = 10000;
uint public earnLowerlimit = 5 ether; // minimum to invest is 5 3CRV
uint public totalDepositCap = 10000000 ether; // initial cap set at 10 million dollar
address public governance;
address public controller;
uint public insurance;
IVaultManager public vaultManager;
IConverter public converter;
bool public acceptContractDepositor = false; // dont accept contract at beginning
struct UserInfo {
uint amount;
uint yaxRewardDebt;
uint accEarned;
}
uint public lastRewardBlock;
uint public accYaxPerShare;
uint public yaxPerBlock;
mapping(address => UserInfo) public userInfo;
address public treasuryWallet = 0x362Db1c17db4C79B51Fe6aD2d73165b1fe9BaB4a;
uint public constant BLOCKS_PER_WEEK = 46500;
// Block number when each epoch ends.
uint[5] public epochEndBlocks;
// Reward multipler for each of 5 epoches (epochIndex: reward multipler)
uint[6] public epochRewardMultiplers = [86000, 64000, 43000, 21000, 10000, 1];
/**
* @notice Emitted when a user deposits funds
*/
event Deposit(address indexed user, uint amount);
/**
* @notice Emitted when a user withdraws funds
*/
event Withdraw(address indexed user, uint amount);
/**
* @notice Emitted when YAX is paid to a user
*/
event RewardPaid(address indexed user, uint reward);
/**
* @param _tokenDAI The address of the DAI token
* @param _tokenUSDC The address of the USDC token
* @param _tokenUSDT The address of the USDT token
* @param _token3CRV The address of the 3CRV token
* @param _tokenYAX The address of the YAX token
* @param _yaxPerBlock The amount of YAX rewarded per block
* @param _startBlock The starting block for rewards
*/
constructor (IERC20 _tokenDAI, IERC20 _tokenUSDC, IERC20 _tokenUSDT, IERC20 _token3CRV, IERC20 _tokenYAX,
uint _yaxPerBlock, uint _startBlock) public ERC20("yAxis.io:MetaVault:3CRV", "MVLT") {
inputTokens[0] = _tokenDAI;
inputTokens[1] = _tokenUSDC;
inputTokens[2] = _tokenUSDT;
inputTokens[3] = _token3CRV;
token3CRV = _token3CRV;
tokenYAX = _tokenYAX;
yaxPerBlock = _yaxPerBlock; // supposed to be 0.000001 YAX (1000000000000 = 1e12 wei)
lastRewardBlock = (_startBlock > block.number) ? _startBlock : block.number; // supposed to be 11,163,000 (Sat Oct 31 2020 06:30:00 GMT+0)
epochEndBlocks[0] = lastRewardBlock + BLOCKS_PER_WEEK * 2; // weeks 1-2
epochEndBlocks[1] = epochEndBlocks[0] + BLOCKS_PER_WEEK * 2; // weeks 3-4
epochEndBlocks[2] = epochEndBlocks[1] + BLOCKS_PER_WEEK * 4; // month 2
epochEndBlocks[3] = epochEndBlocks[2] + BLOCKS_PER_WEEK * 8; // month 3-4
epochEndBlocks[4] = epochEndBlocks[3] + BLOCKS_PER_WEEK * 8; // month 5-6
governance = msg.sender;
}
/**
* @dev Throws if called by a contract and we are not allowing.
*/
modifier checkContract() {
if (!acceptContractDepositor) {
require(!address(msg.sender).isContract() && msg.sender == tx.origin, "Sorry we do not accept contract!");
}
_;
}
/**
* @notice Returns the current token3CRV balance of the vault and controller, minus insurance
* @dev Ignore insurance fund for balance calculations
*/
function balance() public override view returns (uint) {
uint bal = token3CRV.balanceOf(address(this));
if (controller != address(0)) bal = bal.add(IController(controller).balanceOf(address(token3CRV)));
return bal.sub(insurance);
}
/**
* @notice Called by Governance to set the value for min
* @param _min The new min value
*/
function setMin(uint _min) external {
require(msg.sender == governance, "!governance");
min = _min;
}
/**
* @notice Called by Governance to set the value for the governance address
* @param _governance The new governance value
*/
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
/**
* @notice Called by Governance to set the value for the controller address
* @param _controller The new controller value
*/
function setController(address _controller) public override {
require(msg.sender == governance, "!governance");
controller = _controller;
}
/**
* @notice Called by Governance to set the value for the converter address
* @param _converter The new converter value
* @dev Requires that the return address of token() from the converter is the
* same as token3CRV
*/
function setConverter(IConverter _converter) public {
require(msg.sender == governance, "!governance");
require(_converter.token() == address(token3CRV), "!token3CRV");
converter = _converter;
}
/**
* @notice Called by Governance to set the value for the vaultManager address
* @param _vaultManager The new vaultManager value
*/
function setVaultManager(IVaultManager _vaultManager) public {
require(msg.sender == governance, "!governance");
vaultManager = _vaultManager;
}
/**
* @notice Called by Governance to set the value for the earnLowerlimit
* @dev earnLowerlimit determines the minimum balance of this contract for earn
* to be called
* @param _earnLowerlimit The new earnLowerlimit value
*/
function setEarnLowerlimit(uint _earnLowerlimit) public {
require(msg.sender == governance, "!governance");
earnLowerlimit = _earnLowerlimit;
}
/**
* @notice Called by Governance to set the value for the totalDepositCap
* @dev totalDepositCap is the maximum amount of value that can be deposited
* to the metavault at a time
* @param _totalDepositCap The new totalDepositCap value
*/
function setTotalDepositCap(uint _totalDepositCap) public {
require(msg.sender == governance, "!governance");
totalDepositCap = _totalDepositCap;
}
/**
* @notice Called by Governance to set the value for acceptContractDepositor
* @dev acceptContractDepositor allows the metavault to accept deposits from
* smart contract addresses
* @param _acceptContractDepositor The new acceptContractDepositor value
*/
function setAcceptContractDepositor(bool _acceptContractDepositor) public {
require(msg.sender == governance, "!governance");
acceptContractDepositor = _acceptContractDepositor;
}
/**
* @notice Called by Governance to set the value for yaxPerBlock
* @dev Makes a call to updateReward()
* @param _yaxPerBlock The new yaxPerBlock value
*/
function setYaxPerBlock(uint _yaxPerBlock) public {
require(msg.sender == governance, "!governance");
updateReward();
yaxPerBlock = _yaxPerBlock;
}
/**
* @notice Called by Governance to set the value for epochEndBlocks at the given index
* @dev Throws if _index >= 5
* @dev Throws if _epochEndBlock > the current block.number
* @dev Throws if the stored block.number at the given index is > the current block.number
* @param _index The index to set of epochEndBlocks
* @param _epochEndBlock The new epochEndBlocks value at the index
*/
function setEpochEndBlock(uint8 _index, uint256 _epochEndBlock) public {
require(msg.sender == governance, "!governance");
require(_index < 5, "_index out of range");
require(_epochEndBlock > block.number, "Too late to update");
require(epochEndBlocks[_index] > block.number, "Too late to update");
epochEndBlocks[_index] = _epochEndBlock;
}
/**
* @notice Called by Governance to set the value for epochRewardMultiplers at the given index
* @dev Throws if _index < 1 or > 5
* @dev Throws if the stored block.number at the previous index is > the current block.number
* @param _index The index to set of epochRewardMultiplers
* @param _epochRewardMultipler The new epochRewardMultiplers value at the index
*/
function setEpochRewardMultipler(uint8 _index, uint256 _epochRewardMultipler) public {
require(msg.sender == governance, "!governance");
require(_index > 0 && _index < 6, "Index out of range");
require(epochEndBlocks[_index - 1] > block.number, "Too late to update");
epochRewardMultiplers[_index] = _epochRewardMultipler;
}
/**
* @notice Return reward multiplier over the given _from to _to block.
* @param _from The from block
* @param _to The to block
*/
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
// start at the end of the epochs
for (uint8 epochId = 5; epochId >= 1; --epochId) {
// if _to (the current block number if called within this contract) is after the previous epoch ends
if (_to >= epochEndBlocks[epochId - 1]) {
// if the last reward block is after the previous epoch: return the number of blocks multiplied by this epochs multiplier
if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardMultiplers[epochId]);
// get the multiplier amount for the remaining reward of the current epoch
uint256 multiplier = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]);
// if epoch is 1: return the remaining current epoch reward with the first epoch reward
if (epochId == 1) return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0]));
// for all epochs in between the first and current epoch
for (epochId = epochId - 1; epochId >= 1; --epochId) {
// if the last reward block is after the previous epoch: return the current remaining reward with the previous epoch
if (_from >= epochEndBlocks[epochId - 1]) return multiplier.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardMultiplers[epochId]));
// accumulate the multipler with the reward from the epoch
multiplier = multiplier.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]));
}
// return the accumulated multiplier with the reward from the first epoch
return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0]));
}
}
// return the reward amount between _from and _to in the first epoch
return _to.sub(_from).mul(epochRewardMultiplers[0]);
}
/**
* @notice Called by Governance to set the value for the treasuryWallet
* @param _treasuryWallet The new treasuryWallet value
*/
function setTreasuryWallet(address _treasuryWallet) public {
require(msg.sender == governance, "!governance");
treasuryWallet = _treasuryWallet;
}
/**
* @notice Called by Governance or the controller to claim the amount stored in the insurance fund
* @dev If called by the controller, insurance will auto compound the vault, increasing getPricePerFullShare
*/
function claimInsurance() external override {
// if claim by controller for auto-compounding (current insurance will stay to increase sharePrice)
// otherwise send the fund to treasuryWallet
if (msg.sender != controller) {
// claim by governance for insurance
require(msg.sender == governance, "!governance");
token3CRV.safeTransfer(treasuryWallet, insurance);
}
insurance = 0;
}
/**
* @notice Get the address of the 3CRV token
*/
function token() public override view returns (address) {
return address(token3CRV);
}
/**
* @notice Get the amount that the metavault allows to be borrowed
* @dev min and max are used to keep small withdrawals cheap
*/
function available() public override view returns (uint) {
return token3CRV.balanceOf(address(this)).mul(min).div(max);
}
/**
* @notice If the controller is set, returns the withdrawFee of the 3CRV token for the given _amount
* @param _amount The amount being queried to withdraw
*/
function withdrawFee(uint _amount) public override view returns (uint) {
return (controller == address(0)) ? 0 : IController(controller).withdrawFee(address(token3CRV), _amount);
}
/**
* @notice Sends accrued 3CRV tokens on the metavault to the controller to be deposited to strategies
*/
function earn() public override {
if (controller != address(0)) {
IController _contrl = IController(controller);
if (_contrl.investEnabled()) {
uint _bal = available();
token3CRV.safeTransfer(controller, _bal);
_contrl.earn(address(token3CRV), _bal);
}
}
}
/**
* @notice Returns the amount of 3CRV given for the amounts deposited
* @param amounts The stablecoin amounts being deposited
*/
function calc_token_amount_deposit(uint[3] calldata amounts) external override view returns (uint) {
return converter.calc_token_amount(amounts, true);
}
/**
* @notice Returns the amount given in the desired token for the given shares
* @param _shares The amount of shares to withdraw
* @param _output The desired token to withdraw
*/
function calc_token_amount_withdraw(uint _shares, address _output) external override view returns (uint) {
uint _withdrawFee = withdrawFee(_shares);
if (_withdrawFee > 0) {
_shares = _shares.mul(10000 - _withdrawFee).div(10000);
}
uint r = (balance().mul(_shares)).div(totalSupply());
if (_output == address(token3CRV)) {
return r;
}
return converter.calc_token_amount_withdraw(r, _output);
}
/**
* @notice Returns the amount of 3CRV that would be given for the amount of input tokens
* @param _input The stablecoin to convert to 3CRV
* @param _amount The amount of stablecoin to convert
*/
function convert_rate(address _input, uint _amount) external override view returns (uint) {
return converter.convert_rate(_input, address(token3CRV), _amount);
}
/**
* @notice Deposit a single stablecoin to the metavault
* @dev Users must approve the metavault to spend their stablecoin
* @param _amount The amount of the stablecoin to deposit
* @param _input The address of the stablecoin being deposited
* @param _min_mint_amount The expected amount of shares to receive
* @param _isStake Stakes shares or not
*/
function deposit(uint _amount, address _input, uint _min_mint_amount, bool _isStake) external override checkContract {
require(_amount > 0, "!_amount");
uint _pool = balance();
uint _before = token3CRV.balanceOf(address(this));
if (_input == address(token3CRV)) {
token3CRV.safeTransferFrom(msg.sender, address(this), _amount);
} else if (converter.convert_rate(_input, address(token3CRV), _amount) > 0) {
IERC20(_input).safeTransferFrom(msg.sender, address(converter), _amount);
converter.convert(_input, address(token3CRV), _amount);
}
uint _after = token3CRV.balanceOf(address(this));
require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap");
_amount = _after.sub(_before); // Additional check for deflationary tokens
require(_amount >= _min_mint_amount, "slippage");
if (_amount > 0) {
if (!_isStake) {
_deposit(msg.sender, _pool, _amount);
} else {
uint _shares = _deposit(address(this), _pool, _amount);
_stakeShares(_shares);
}
}
}
/**
* @notice Deposits multiple stablecoins simultaneously to the metavault
* @dev 0: DAI, 1: USDC, 2: USDT, 3: 3CRV
* @dev Users must approve the metavault to spend their stablecoin
* @param _amounts The amounts of each stablecoin being deposited
* @param _min_mint_amount The expected amount of shares to receive
* @param _isStake Stakes shares or not
*/
function depositAll(uint[4] calldata _amounts, uint _min_mint_amount, bool _isStake) external checkContract {
uint _pool = balance();
uint _before = token3CRV.balanceOf(address(this));
bool hasStables = false;
for (uint8 i = 0; i < 4; i++) {
uint _inputAmount = _amounts[i];
if (_inputAmount > 0) {
if (i == 3) {
inputTokens[i].safeTransferFrom(msg.sender, address(this), _inputAmount);
} else if (converter.convert_rate(address(inputTokens[i]), address(token3CRV), _inputAmount) > 0) {
inputTokens[i].safeTransferFrom(msg.sender, address(converter), _inputAmount);
hasStables = true;
}
}
}
if (hasStables) {
uint[3] memory _stablesAmounts;
_stablesAmounts[0] = _amounts[0];
_stablesAmounts[1] = _amounts[1];
_stablesAmounts[2] = _amounts[2];
converter.convert_stables(_stablesAmounts);
}
uint _after = token3CRV.balanceOf(address(this));
require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap");
uint _totalDepositAmount = _after.sub(_before); // Additional check for deflationary tokens
require(_totalDepositAmount >= _min_mint_amount, "slippage");
if (_totalDepositAmount > 0) {
if (!_isStake) {
_deposit(msg.sender, _pool, _totalDepositAmount);
} else {
uint _shares = _deposit(address(this), _pool, _totalDepositAmount);
_stakeShares(_shares);
}
}
}
/**
* @notice Stakes metavault shares
* @param _shares The amount of shares to stake
*/
function stakeShares(uint _shares) external {
uint _before = balanceOf(address(this));
IERC20(address(this)).transferFrom(msg.sender, address(this), _shares);
uint _after = balanceOf(address(this));
_shares = _after.sub(_before);
// Additional check for deflationary tokens
_stakeShares(_shares);
}
function _deposit(address _mintTo, uint _pool, uint _amount) internal returns (uint _shares) {
if (address(vaultManager) != address(0)) {
// expected 0.1% of deposits go into an insurance fund (or auto-compounding if called by controller) in-case of negative profits to protect withdrawals
// it is updated by governance (community vote)
uint _insuranceFee = vaultManager.insuranceFee();
if (_insuranceFee > 0) {
uint _insurance = _amount.mul(_insuranceFee).div(10000);
_amount = _amount.sub(_insurance);
insurance = insurance.add(_insurance);
}
}
if (totalSupply() == 0) {
_shares = _amount;
} else {
_shares = (_amount.mul(totalSupply())).div(_pool);
}
if (_shares > 0) {
if (token3CRV.balanceOf(address(this)) > earnLowerlimit) {
earn();
}
_mint(_mintTo, _shares);
}
}
function _stakeShares(uint _shares) internal {
UserInfo storage user = userInfo[msg.sender];
updateReward();
_getReward();
user.amount = user.amount.add(_shares);
user.yaxRewardDebt = user.amount.mul(accYaxPerShare).div(1e12);
emit Deposit(msg.sender, _shares);
}
/**
* @notice Returns the pending YAXs for a given account
* @param _account The address to query
*/
function pendingYax(address _account) public view returns (uint _pending) {
UserInfo storage user = userInfo[_account];
uint _accYaxPerShare = accYaxPerShare;
uint lpSupply = balanceOf(address(this));
if (block.number > lastRewardBlock && lpSupply != 0) {
uint256 _multiplier = getMultiplier(lastRewardBlock, block.number);
_accYaxPerShare = accYaxPerShare.add(_multiplier.mul(yaxPerBlock).mul(1e12).div(lpSupply));
}
_pending = user.amount.mul(_accYaxPerShare).div(1e12).sub(user.yaxRewardDebt);
}
/**
* @notice Sets the lastRewardBlock and accYaxPerShare
*/
function updateReward() public {
if (block.number <= lastRewardBlock) {
return;
}
uint lpSupply = balanceOf(address(this));
if (lpSupply == 0) {
lastRewardBlock = block.number;
return;
}
uint256 _multiplier = getMultiplier(lastRewardBlock, block.number);
accYaxPerShare = accYaxPerShare.add(_multiplier.mul(yaxPerBlock).mul(1e12).div(lpSupply));
lastRewardBlock = block.number;
}
function _getReward() internal {
UserInfo storage user = userInfo[msg.sender];
uint _pendingYax = user.amount.mul(accYaxPerShare).div(1e12).sub(user.yaxRewardDebt);
if (_pendingYax > 0) {
user.accEarned = user.accEarned.add(_pendingYax);
safeYaxTransfer(msg.sender, _pendingYax);
emit RewardPaid(msg.sender, _pendingYax);
}
}
/**
* @notice Withdraw the entire balance for an account
* @param _output The address of the desired stablecoin to receive
*/
function withdrawAll(address _output) external {
unstake(userInfo[msg.sender].amount);
withdraw(balanceOf(msg.sender), _output);
}
/**
* @notice Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
* @param reserve The address of the token to swap to 3CRV
* @param amount The amount to swap
*/
function harvest(address reserve, uint amount) external override {
require(msg.sender == controller, "!controller");
require(reserve != address(token3CRV), "token3CRV");
IERC20(reserve).safeTransfer(controller, amount);
}
/**
* @notice Unstakes the given shares from the metavault
* @dev call unstake(0) to only receive the reward
* @param _amount The amount to unstake
*/
function unstake(uint _amount) public {
updateReward();
_getReward();
UserInfo storage user = userInfo[msg.sender];
if (_amount > 0) {
require(user.amount >= _amount, "stakedBal < _amount");
user.amount = user.amount.sub(_amount);
IERC20(address(this)).transfer(msg.sender, _amount);
}
user.yaxRewardDebt = user.amount.mul(accYaxPerShare).div(1e12);
emit Withdraw(msg.sender, _amount);
}
/**
* @notice Withdraws an amount of shares to a given output stablecoin
* @dev No rebalance implementation for lower fees and faster swaps
* @param _shares The amount of shares to withdraw
* @param _output The address of the stablecoin to receive
*/
function withdraw(uint _shares, address _output) public override {
uint _userBal = balanceOf(msg.sender);
if (_shares > _userBal) {
uint _need = _shares.sub(_userBal);
require(_need <= userInfo[msg.sender].amount, "_userBal+staked < _shares");
unstake(_need);
}
uint r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
if (address(vaultManager) != address(0)) {
// expected 0.1% of withdrawal go back to vault (for auto-compounding) to protect withdrawals
// it is updated by governance (community vote)
uint _withdrawalProtectionFee = vaultManager.withdrawalProtectionFee();
if (_withdrawalProtectionFee > 0) {
uint _withdrawalProtection = r.mul(_withdrawalProtectionFee).div(10000);
r = r.sub(_withdrawalProtection);
}
}
// Check balance
uint b = token3CRV.balanceOf(address(this));
if (b < r) {
uint _toWithdraw = r.sub(b);
if (controller != address(0)) {
IController(controller).withdraw(address(token3CRV), _toWithdraw);
}
uint _after = token3CRV.balanceOf(address(this));
uint _diff = _after.sub(b);
if (_diff < _toWithdraw) {
r = b.add(_diff);
}
}
if (_output == address(token3CRV)) {
token3CRV.safeTransfer(msg.sender, r);
} else {
require(converter.convert_rate(address(token3CRV), _output, r) > 0, "rate=0");
token3CRV.safeTransfer(address(converter), r);
uint _outputAmount = converter.convert(address(token3CRV), _output, r);
IERC20(_output).safeTransfer(msg.sender, _outputAmount);
}
}
/**
* @notice Returns the address of the 3CRV token
*/
function want() external override view returns (address) {
return address(token3CRV);
}
/**
* @notice Returns the rate of earnings of a single share
*/
function getPricePerFullShare() external override view returns (uint) {
return balance().mul(1e18).div(totalSupply());
}
/**
* @notice Transfers YAX from the metavault to a given address
* @dev Ensures the metavault has enough balance to transfer
* @param _to The address to transfer to
* @param _amount The amount to transfer
*/
function safeYaxTransfer(address _to, uint _amount) internal {
uint _tokenBal = tokenYAX.balanceOf(address(this));
tokenYAX.safeTransfer(_to, (_tokenBal < _amount) ? _tokenBal : _amount);
}
/**
* @notice Converts non-3CRV stablecoins held in the metavault to 3CRV
* @param _token The address to convert
*/
function earnExtra(address _token) public {
require(msg.sender == governance, "!governance");
require(address(_token) != address(token3CRV), "3crv");
require(address(_token) != address(this), "mlvt");
uint _amount = IERC20(_token).balanceOf(address(this));
require(converter.convert_rate(_token, address(token3CRV), _amount) > 0, "rate=0");
IERC20(_token).safeTransfer(address(converter), _amount);
converter.convert(_token, address(token3CRV), _amount);
}
}
| contract yAxisMetaVault is ERC20, IMetaVault {
using Address for address;
using SafeMath for uint;
using SafeERC20 for IERC20;
IERC20[4] public inputTokens; // DAI, USDC, USDT, 3Crv
IERC20 public token3CRV;
IERC20 public tokenYAX;
uint public min = 9500;
uint public constant max = 10000;
uint public earnLowerlimit = 5 ether; // minimum to invest is 5 3CRV
uint public totalDepositCap = 10000000 ether; // initial cap set at 10 million dollar
address public governance;
address public controller;
uint public insurance;
IVaultManager public vaultManager;
IConverter public converter;
bool public acceptContractDepositor = false; // dont accept contract at beginning
struct UserInfo {
uint amount;
uint yaxRewardDebt;
uint accEarned;
}
uint public lastRewardBlock;
uint public accYaxPerShare;
uint public yaxPerBlock;
mapping(address => UserInfo) public userInfo;
address public treasuryWallet = 0x362Db1c17db4C79B51Fe6aD2d73165b1fe9BaB4a;
uint public constant BLOCKS_PER_WEEK = 46500;
// Block number when each epoch ends.
uint[5] public epochEndBlocks;
// Reward multipler for each of 5 epoches (epochIndex: reward multipler)
uint[6] public epochRewardMultiplers = [86000, 64000, 43000, 21000, 10000, 1];
/**
* @notice Emitted when a user deposits funds
*/
event Deposit(address indexed user, uint amount);
/**
* @notice Emitted when a user withdraws funds
*/
event Withdraw(address indexed user, uint amount);
/**
* @notice Emitted when YAX is paid to a user
*/
event RewardPaid(address indexed user, uint reward);
/**
* @param _tokenDAI The address of the DAI token
* @param _tokenUSDC The address of the USDC token
* @param _tokenUSDT The address of the USDT token
* @param _token3CRV The address of the 3CRV token
* @param _tokenYAX The address of the YAX token
* @param _yaxPerBlock The amount of YAX rewarded per block
* @param _startBlock The starting block for rewards
*/
constructor (IERC20 _tokenDAI, IERC20 _tokenUSDC, IERC20 _tokenUSDT, IERC20 _token3CRV, IERC20 _tokenYAX,
uint _yaxPerBlock, uint _startBlock) public ERC20("yAxis.io:MetaVault:3CRV", "MVLT") {
inputTokens[0] = _tokenDAI;
inputTokens[1] = _tokenUSDC;
inputTokens[2] = _tokenUSDT;
inputTokens[3] = _token3CRV;
token3CRV = _token3CRV;
tokenYAX = _tokenYAX;
yaxPerBlock = _yaxPerBlock; // supposed to be 0.000001 YAX (1000000000000 = 1e12 wei)
lastRewardBlock = (_startBlock > block.number) ? _startBlock : block.number; // supposed to be 11,163,000 (Sat Oct 31 2020 06:30:00 GMT+0)
epochEndBlocks[0] = lastRewardBlock + BLOCKS_PER_WEEK * 2; // weeks 1-2
epochEndBlocks[1] = epochEndBlocks[0] + BLOCKS_PER_WEEK * 2; // weeks 3-4
epochEndBlocks[2] = epochEndBlocks[1] + BLOCKS_PER_WEEK * 4; // month 2
epochEndBlocks[3] = epochEndBlocks[2] + BLOCKS_PER_WEEK * 8; // month 3-4
epochEndBlocks[4] = epochEndBlocks[3] + BLOCKS_PER_WEEK * 8; // month 5-6
governance = msg.sender;
}
/**
* @dev Throws if called by a contract and we are not allowing.
*/
modifier checkContract() {
if (!acceptContractDepositor) {
require(!address(msg.sender).isContract() && msg.sender == tx.origin, "Sorry we do not accept contract!");
}
_;
}
/**
* @notice Returns the current token3CRV balance of the vault and controller, minus insurance
* @dev Ignore insurance fund for balance calculations
*/
function balance() public override view returns (uint) {
uint bal = token3CRV.balanceOf(address(this));
if (controller != address(0)) bal = bal.add(IController(controller).balanceOf(address(token3CRV)));
return bal.sub(insurance);
}
/**
* @notice Called by Governance to set the value for min
* @param _min The new min value
*/
function setMin(uint _min) external {
require(msg.sender == governance, "!governance");
min = _min;
}
/**
* @notice Called by Governance to set the value for the governance address
* @param _governance The new governance value
*/
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
/**
* @notice Called by Governance to set the value for the controller address
* @param _controller The new controller value
*/
function setController(address _controller) public override {
require(msg.sender == governance, "!governance");
controller = _controller;
}
/**
* @notice Called by Governance to set the value for the converter address
* @param _converter The new converter value
* @dev Requires that the return address of token() from the converter is the
* same as token3CRV
*/
function setConverter(IConverter _converter) public {
require(msg.sender == governance, "!governance");
require(_converter.token() == address(token3CRV), "!token3CRV");
converter = _converter;
}
/**
* @notice Called by Governance to set the value for the vaultManager address
* @param _vaultManager The new vaultManager value
*/
function setVaultManager(IVaultManager _vaultManager) public {
require(msg.sender == governance, "!governance");
vaultManager = _vaultManager;
}
/**
* @notice Called by Governance to set the value for the earnLowerlimit
* @dev earnLowerlimit determines the minimum balance of this contract for earn
* to be called
* @param _earnLowerlimit The new earnLowerlimit value
*/
function setEarnLowerlimit(uint _earnLowerlimit) public {
require(msg.sender == governance, "!governance");
earnLowerlimit = _earnLowerlimit;
}
/**
* @notice Called by Governance to set the value for the totalDepositCap
* @dev totalDepositCap is the maximum amount of value that can be deposited
* to the metavault at a time
* @param _totalDepositCap The new totalDepositCap value
*/
function setTotalDepositCap(uint _totalDepositCap) public {
require(msg.sender == governance, "!governance");
totalDepositCap = _totalDepositCap;
}
/**
* @notice Called by Governance to set the value for acceptContractDepositor
* @dev acceptContractDepositor allows the metavault to accept deposits from
* smart contract addresses
* @param _acceptContractDepositor The new acceptContractDepositor value
*/
function setAcceptContractDepositor(bool _acceptContractDepositor) public {
require(msg.sender == governance, "!governance");
acceptContractDepositor = _acceptContractDepositor;
}
/**
* @notice Called by Governance to set the value for yaxPerBlock
* @dev Makes a call to updateReward()
* @param _yaxPerBlock The new yaxPerBlock value
*/
function setYaxPerBlock(uint _yaxPerBlock) public {
require(msg.sender == governance, "!governance");
updateReward();
yaxPerBlock = _yaxPerBlock;
}
/**
* @notice Called by Governance to set the value for epochEndBlocks at the given index
* @dev Throws if _index >= 5
* @dev Throws if _epochEndBlock > the current block.number
* @dev Throws if the stored block.number at the given index is > the current block.number
* @param _index The index to set of epochEndBlocks
* @param _epochEndBlock The new epochEndBlocks value at the index
*/
function setEpochEndBlock(uint8 _index, uint256 _epochEndBlock) public {
require(msg.sender == governance, "!governance");
require(_index < 5, "_index out of range");
require(_epochEndBlock > block.number, "Too late to update");
require(epochEndBlocks[_index] > block.number, "Too late to update");
epochEndBlocks[_index] = _epochEndBlock;
}
/**
* @notice Called by Governance to set the value for epochRewardMultiplers at the given index
* @dev Throws if _index < 1 or > 5
* @dev Throws if the stored block.number at the previous index is > the current block.number
* @param _index The index to set of epochRewardMultiplers
* @param _epochRewardMultipler The new epochRewardMultiplers value at the index
*/
function setEpochRewardMultipler(uint8 _index, uint256 _epochRewardMultipler) public {
require(msg.sender == governance, "!governance");
require(_index > 0 && _index < 6, "Index out of range");
require(epochEndBlocks[_index - 1] > block.number, "Too late to update");
epochRewardMultiplers[_index] = _epochRewardMultipler;
}
/**
* @notice Return reward multiplier over the given _from to _to block.
* @param _from The from block
* @param _to The to block
*/
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
// start at the end of the epochs
for (uint8 epochId = 5; epochId >= 1; --epochId) {
// if _to (the current block number if called within this contract) is after the previous epoch ends
if (_to >= epochEndBlocks[epochId - 1]) {
// if the last reward block is after the previous epoch: return the number of blocks multiplied by this epochs multiplier
if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardMultiplers[epochId]);
// get the multiplier amount for the remaining reward of the current epoch
uint256 multiplier = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]);
// if epoch is 1: return the remaining current epoch reward with the first epoch reward
if (epochId == 1) return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0]));
// for all epochs in between the first and current epoch
for (epochId = epochId - 1; epochId >= 1; --epochId) {
// if the last reward block is after the previous epoch: return the current remaining reward with the previous epoch
if (_from >= epochEndBlocks[epochId - 1]) return multiplier.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardMultiplers[epochId]));
// accumulate the multipler with the reward from the epoch
multiplier = multiplier.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]));
}
// return the accumulated multiplier with the reward from the first epoch
return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0]));
}
}
// return the reward amount between _from and _to in the first epoch
return _to.sub(_from).mul(epochRewardMultiplers[0]);
}
/**
* @notice Called by Governance to set the value for the treasuryWallet
* @param _treasuryWallet The new treasuryWallet value
*/
function setTreasuryWallet(address _treasuryWallet) public {
require(msg.sender == governance, "!governance");
treasuryWallet = _treasuryWallet;
}
/**
* @notice Called by Governance or the controller to claim the amount stored in the insurance fund
* @dev If called by the controller, insurance will auto compound the vault, increasing getPricePerFullShare
*/
function claimInsurance() external override {
// if claim by controller for auto-compounding (current insurance will stay to increase sharePrice)
// otherwise send the fund to treasuryWallet
if (msg.sender != controller) {
// claim by governance for insurance
require(msg.sender == governance, "!governance");
token3CRV.safeTransfer(treasuryWallet, insurance);
}
insurance = 0;
}
/**
* @notice Get the address of the 3CRV token
*/
function token() public override view returns (address) {
return address(token3CRV);
}
/**
* @notice Get the amount that the metavault allows to be borrowed
* @dev min and max are used to keep small withdrawals cheap
*/
function available() public override view returns (uint) {
return token3CRV.balanceOf(address(this)).mul(min).div(max);
}
/**
* @notice If the controller is set, returns the withdrawFee of the 3CRV token for the given _amount
* @param _amount The amount being queried to withdraw
*/
function withdrawFee(uint _amount) public override view returns (uint) {
return (controller == address(0)) ? 0 : IController(controller).withdrawFee(address(token3CRV), _amount);
}
/**
* @notice Sends accrued 3CRV tokens on the metavault to the controller to be deposited to strategies
*/
function earn() public override {
if (controller != address(0)) {
IController _contrl = IController(controller);
if (_contrl.investEnabled()) {
uint _bal = available();
token3CRV.safeTransfer(controller, _bal);
_contrl.earn(address(token3CRV), _bal);
}
}
}
/**
* @notice Returns the amount of 3CRV given for the amounts deposited
* @param amounts The stablecoin amounts being deposited
*/
function calc_token_amount_deposit(uint[3] calldata amounts) external override view returns (uint) {
return converter.calc_token_amount(amounts, true);
}
/**
* @notice Returns the amount given in the desired token for the given shares
* @param _shares The amount of shares to withdraw
* @param _output The desired token to withdraw
*/
function calc_token_amount_withdraw(uint _shares, address _output) external override view returns (uint) {
uint _withdrawFee = withdrawFee(_shares);
if (_withdrawFee > 0) {
_shares = _shares.mul(10000 - _withdrawFee).div(10000);
}
uint r = (balance().mul(_shares)).div(totalSupply());
if (_output == address(token3CRV)) {
return r;
}
return converter.calc_token_amount_withdraw(r, _output);
}
/**
* @notice Returns the amount of 3CRV that would be given for the amount of input tokens
* @param _input The stablecoin to convert to 3CRV
* @param _amount The amount of stablecoin to convert
*/
function convert_rate(address _input, uint _amount) external override view returns (uint) {
return converter.convert_rate(_input, address(token3CRV), _amount);
}
/**
* @notice Deposit a single stablecoin to the metavault
* @dev Users must approve the metavault to spend their stablecoin
* @param _amount The amount of the stablecoin to deposit
* @param _input The address of the stablecoin being deposited
* @param _min_mint_amount The expected amount of shares to receive
* @param _isStake Stakes shares or not
*/
function deposit(uint _amount, address _input, uint _min_mint_amount, bool _isStake) external override checkContract {
require(_amount > 0, "!_amount");
uint _pool = balance();
uint _before = token3CRV.balanceOf(address(this));
if (_input == address(token3CRV)) {
token3CRV.safeTransferFrom(msg.sender, address(this), _amount);
} else if (converter.convert_rate(_input, address(token3CRV), _amount) > 0) {
IERC20(_input).safeTransferFrom(msg.sender, address(converter), _amount);
converter.convert(_input, address(token3CRV), _amount);
}
uint _after = token3CRV.balanceOf(address(this));
require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap");
_amount = _after.sub(_before); // Additional check for deflationary tokens
require(_amount >= _min_mint_amount, "slippage");
if (_amount > 0) {
if (!_isStake) {
_deposit(msg.sender, _pool, _amount);
} else {
uint _shares = _deposit(address(this), _pool, _amount);
_stakeShares(_shares);
}
}
}
/**
* @notice Deposits multiple stablecoins simultaneously to the metavault
* @dev 0: DAI, 1: USDC, 2: USDT, 3: 3CRV
* @dev Users must approve the metavault to spend their stablecoin
* @param _amounts The amounts of each stablecoin being deposited
* @param _min_mint_amount The expected amount of shares to receive
* @param _isStake Stakes shares or not
*/
function depositAll(uint[4] calldata _amounts, uint _min_mint_amount, bool _isStake) external checkContract {
uint _pool = balance();
uint _before = token3CRV.balanceOf(address(this));
bool hasStables = false;
for (uint8 i = 0; i < 4; i++) {
uint _inputAmount = _amounts[i];
if (_inputAmount > 0) {
if (i == 3) {
inputTokens[i].safeTransferFrom(msg.sender, address(this), _inputAmount);
} else if (converter.convert_rate(address(inputTokens[i]), address(token3CRV), _inputAmount) > 0) {
inputTokens[i].safeTransferFrom(msg.sender, address(converter), _inputAmount);
hasStables = true;
}
}
}
if (hasStables) {
uint[3] memory _stablesAmounts;
_stablesAmounts[0] = _amounts[0];
_stablesAmounts[1] = _amounts[1];
_stablesAmounts[2] = _amounts[2];
converter.convert_stables(_stablesAmounts);
}
uint _after = token3CRV.balanceOf(address(this));
require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap");
uint _totalDepositAmount = _after.sub(_before); // Additional check for deflationary tokens
require(_totalDepositAmount >= _min_mint_amount, "slippage");
if (_totalDepositAmount > 0) {
if (!_isStake) {
_deposit(msg.sender, _pool, _totalDepositAmount);
} else {
uint _shares = _deposit(address(this), _pool, _totalDepositAmount);
_stakeShares(_shares);
}
}
}
/**
* @notice Stakes metavault shares
* @param _shares The amount of shares to stake
*/
function stakeShares(uint _shares) external {
uint _before = balanceOf(address(this));
IERC20(address(this)).transferFrom(msg.sender, address(this), _shares);
uint _after = balanceOf(address(this));
_shares = _after.sub(_before);
// Additional check for deflationary tokens
_stakeShares(_shares);
}
function _deposit(address _mintTo, uint _pool, uint _amount) internal returns (uint _shares) {
if (address(vaultManager) != address(0)) {
// expected 0.1% of deposits go into an insurance fund (or auto-compounding if called by controller) in-case of negative profits to protect withdrawals
// it is updated by governance (community vote)
uint _insuranceFee = vaultManager.insuranceFee();
if (_insuranceFee > 0) {
uint _insurance = _amount.mul(_insuranceFee).div(10000);
_amount = _amount.sub(_insurance);
insurance = insurance.add(_insurance);
}
}
if (totalSupply() == 0) {
_shares = _amount;
} else {
_shares = (_amount.mul(totalSupply())).div(_pool);
}
if (_shares > 0) {
if (token3CRV.balanceOf(address(this)) > earnLowerlimit) {
earn();
}
_mint(_mintTo, _shares);
}
}
function _stakeShares(uint _shares) internal {
UserInfo storage user = userInfo[msg.sender];
updateReward();
_getReward();
user.amount = user.amount.add(_shares);
user.yaxRewardDebt = user.amount.mul(accYaxPerShare).div(1e12);
emit Deposit(msg.sender, _shares);
}
/**
* @notice Returns the pending YAXs for a given account
* @param _account The address to query
*/
function pendingYax(address _account) public view returns (uint _pending) {
UserInfo storage user = userInfo[_account];
uint _accYaxPerShare = accYaxPerShare;
uint lpSupply = balanceOf(address(this));
if (block.number > lastRewardBlock && lpSupply != 0) {
uint256 _multiplier = getMultiplier(lastRewardBlock, block.number);
_accYaxPerShare = accYaxPerShare.add(_multiplier.mul(yaxPerBlock).mul(1e12).div(lpSupply));
}
_pending = user.amount.mul(_accYaxPerShare).div(1e12).sub(user.yaxRewardDebt);
}
/**
* @notice Sets the lastRewardBlock and accYaxPerShare
*/
function updateReward() public {
if (block.number <= lastRewardBlock) {
return;
}
uint lpSupply = balanceOf(address(this));
if (lpSupply == 0) {
lastRewardBlock = block.number;
return;
}
uint256 _multiplier = getMultiplier(lastRewardBlock, block.number);
accYaxPerShare = accYaxPerShare.add(_multiplier.mul(yaxPerBlock).mul(1e12).div(lpSupply));
lastRewardBlock = block.number;
}
function _getReward() internal {
UserInfo storage user = userInfo[msg.sender];
uint _pendingYax = user.amount.mul(accYaxPerShare).div(1e12).sub(user.yaxRewardDebt);
if (_pendingYax > 0) {
user.accEarned = user.accEarned.add(_pendingYax);
safeYaxTransfer(msg.sender, _pendingYax);
emit RewardPaid(msg.sender, _pendingYax);
}
}
/**
* @notice Withdraw the entire balance for an account
* @param _output The address of the desired stablecoin to receive
*/
function withdrawAll(address _output) external {
unstake(userInfo[msg.sender].amount);
withdraw(balanceOf(msg.sender), _output);
}
/**
* @notice Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
* @param reserve The address of the token to swap to 3CRV
* @param amount The amount to swap
*/
function harvest(address reserve, uint amount) external override {
require(msg.sender == controller, "!controller");
require(reserve != address(token3CRV), "token3CRV");
IERC20(reserve).safeTransfer(controller, amount);
}
/**
* @notice Unstakes the given shares from the metavault
* @dev call unstake(0) to only receive the reward
* @param _amount The amount to unstake
*/
function unstake(uint _amount) public {
updateReward();
_getReward();
UserInfo storage user = userInfo[msg.sender];
if (_amount > 0) {
require(user.amount >= _amount, "stakedBal < _amount");
user.amount = user.amount.sub(_amount);
IERC20(address(this)).transfer(msg.sender, _amount);
}
user.yaxRewardDebt = user.amount.mul(accYaxPerShare).div(1e12);
emit Withdraw(msg.sender, _amount);
}
/**
* @notice Withdraws an amount of shares to a given output stablecoin
* @dev No rebalance implementation for lower fees and faster swaps
* @param _shares The amount of shares to withdraw
* @param _output The address of the stablecoin to receive
*/
function withdraw(uint _shares, address _output) public override {
uint _userBal = balanceOf(msg.sender);
if (_shares > _userBal) {
uint _need = _shares.sub(_userBal);
require(_need <= userInfo[msg.sender].amount, "_userBal+staked < _shares");
unstake(_need);
}
uint r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
if (address(vaultManager) != address(0)) {
// expected 0.1% of withdrawal go back to vault (for auto-compounding) to protect withdrawals
// it is updated by governance (community vote)
uint _withdrawalProtectionFee = vaultManager.withdrawalProtectionFee();
if (_withdrawalProtectionFee > 0) {
uint _withdrawalProtection = r.mul(_withdrawalProtectionFee).div(10000);
r = r.sub(_withdrawalProtection);
}
}
// Check balance
uint b = token3CRV.balanceOf(address(this));
if (b < r) {
uint _toWithdraw = r.sub(b);
if (controller != address(0)) {
IController(controller).withdraw(address(token3CRV), _toWithdraw);
}
uint _after = token3CRV.balanceOf(address(this));
uint _diff = _after.sub(b);
if (_diff < _toWithdraw) {
r = b.add(_diff);
}
}
if (_output == address(token3CRV)) {
token3CRV.safeTransfer(msg.sender, r);
} else {
require(converter.convert_rate(address(token3CRV), _output, r) > 0, "rate=0");
token3CRV.safeTransfer(address(converter), r);
uint _outputAmount = converter.convert(address(token3CRV), _output, r);
IERC20(_output).safeTransfer(msg.sender, _outputAmount);
}
}
/**
* @notice Returns the address of the 3CRV token
*/
function want() external override view returns (address) {
return address(token3CRV);
}
/**
* @notice Returns the rate of earnings of a single share
*/
function getPricePerFullShare() external override view returns (uint) {
return balance().mul(1e18).div(totalSupply());
}
/**
* @notice Transfers YAX from the metavault to a given address
* @dev Ensures the metavault has enough balance to transfer
* @param _to The address to transfer to
* @param _amount The amount to transfer
*/
function safeYaxTransfer(address _to, uint _amount) internal {
uint _tokenBal = tokenYAX.balanceOf(address(this));
tokenYAX.safeTransfer(_to, (_tokenBal < _amount) ? _tokenBal : _amount);
}
/**
* @notice Converts non-3CRV stablecoins held in the metavault to 3CRV
* @param _token The address to convert
*/
function earnExtra(address _token) public {
require(msg.sender == governance, "!governance");
require(address(_token) != address(token3CRV), "3crv");
require(address(_token) != address(this), "mlvt");
uint _amount = IERC20(_token).balanceOf(address(this));
require(converter.convert_rate(_token, address(token3CRV), _amount) > 0, "rate=0");
IERC20(_token).safeTransfer(address(converter), _amount);
converter.convert(_token, address(token3CRV), _amount);
}
}
| 19,890 |
15 | // swapExactOutputSingle swaps a minimum possible amount of DAI for a fixed amount of WETH./The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable,/ the calling address will need to approve for a slightly higher amount, anticipating some variance./amountOut The exact amount of WETH9 to receive from the swap./amountInMaximum The amount of DAI we are willing to spend to receive the specified amount of WETH9./ return amountIn The amount of DAI actually spent in the swap. | function swapExactOutputSingle(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
// Transfer the specified amount of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);
// Approve the router to spend the specifed `amountInMaximum` of DAI.
// In production, you should choose the maximum amount to spend based on oracles or other data sources to acheive a better swap.
TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);
ISwapRouter.ExactOutputSingleParams memory params =
ISwapRouter.ExactOutputSingleParams({
tokenIn: DAI,
tokenOut: WETH9,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountInMaximum,
sqrtPriceLimitX96: 0
});
// Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
amountIn = swapRouter.exactOutputSingle(params);
// For exact output swaps, the amountInMaximum may not have all been spent.
// If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0.
if (amountIn < amountInMaximum) {
TransferHelper.safeApprove(DAI, address(swapRouter), 0);
TransferHelper.safeTransfer(DAI, msg.sender, amountInMaximum - amountIn);
}
}
| function swapExactOutputSingle(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) {
// Transfer the specified amount of DAI to this contract.
TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum);
// Approve the router to spend the specifed `amountInMaximum` of DAI.
// In production, you should choose the maximum amount to spend based on oracles or other data sources to acheive a better swap.
TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum);
ISwapRouter.ExactOutputSingleParams memory params =
ISwapRouter.ExactOutputSingleParams({
tokenIn: DAI,
tokenOut: WETH9,
fee: poolFee,
recipient: msg.sender,
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountInMaximum,
sqrtPriceLimitX96: 0
});
// Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
amountIn = swapRouter.exactOutputSingle(params);
// For exact output swaps, the amountInMaximum may not have all been spent.
// If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0.
if (amountIn < amountInMaximum) {
TransferHelper.safeApprove(DAI, address(swapRouter), 0);
TransferHelper.safeTransfer(DAI, msg.sender, amountInMaximum - amountIn);
}
}
| 1,460 |
566 | // Update the Stability Pool reward sum S and product P | function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _LUSDLossPerUnitStaked) internal {
uint currentP = P;
uint newP;
assert(_LUSDLossPerUnitStaked <= DECIMAL_PRECISION);
/*
* The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool LUSD in the liquidation.
* We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - LUSDLossPerUnitStaked)
*/
uint newProductFactor = uint(DECIMAL_PRECISION).sub(_LUSDLossPerUnitStaked);
uint128 currentScaleCached = currentScale;
uint128 currentEpochCached = currentEpoch;
uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached];
/*
* Calculate the new S first, before we update P.
* The ETH gain for any given depositor from a liquidation depends on the value of their deposit
* (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation.
*
* Since S corresponds to ETH gain, and P to deposit loss, we update S first.
*/
uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP);
uint newS = currentS.add(marginalETHGain);
epochToScaleToSum[currentEpochCached][currentScaleCached] = newS;
emit S_Updated(newS, currentEpochCached, currentScaleCached);
// If the Stability Pool was emptied, increment the epoch, and reset the scale and product P
if (newProductFactor == 0) {
currentEpoch = currentEpochCached.add(1);
emit EpochUpdated(currentEpoch);
currentScale = 0;
emit ScaleUpdated(currentScale);
newP = DECIMAL_PRECISION;
// If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale
} else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) {
newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION);
currentScale = currentScaleCached.add(1);
emit ScaleUpdated(currentScale);
} else {
newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION);
}
assert(newP > 0);
P = newP;
emit P_Updated(newP);
}
| function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _LUSDLossPerUnitStaked) internal {
uint currentP = P;
uint newP;
assert(_LUSDLossPerUnitStaked <= DECIMAL_PRECISION);
/*
* The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool LUSD in the liquidation.
* We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - LUSDLossPerUnitStaked)
*/
uint newProductFactor = uint(DECIMAL_PRECISION).sub(_LUSDLossPerUnitStaked);
uint128 currentScaleCached = currentScale;
uint128 currentEpochCached = currentEpoch;
uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached];
/*
* Calculate the new S first, before we update P.
* The ETH gain for any given depositor from a liquidation depends on the value of their deposit
* (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation.
*
* Since S corresponds to ETH gain, and P to deposit loss, we update S first.
*/
uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP);
uint newS = currentS.add(marginalETHGain);
epochToScaleToSum[currentEpochCached][currentScaleCached] = newS;
emit S_Updated(newS, currentEpochCached, currentScaleCached);
// If the Stability Pool was emptied, increment the epoch, and reset the scale and product P
if (newProductFactor == 0) {
currentEpoch = currentEpochCached.add(1);
emit EpochUpdated(currentEpoch);
currentScale = 0;
emit ScaleUpdated(currentScale);
newP = DECIMAL_PRECISION;
// If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale
} else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) {
newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION);
currentScale = currentScaleCached.add(1);
emit ScaleUpdated(currentScale);
} else {
newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION);
}
assert(newP > 0);
P = newP;
emit P_Updated(newP);
}
| 68,834 |
273 | // In the current elyfi, the lending company who has a collateral service provider role is allowed to create proposal./account The address of proposer | function _validateProposer(address account) internal view returns (bool) {
return hasRole(LENDING_COMPANY_ROLE, account);
}
| function _validateProposer(address account) internal view returns (bool) {
return hasRole(LENDING_COMPANY_ROLE, account);
}
| 14,816 |
79 | // TODO: implement refund | fallback () payable external {
//refund noobs who send money directly to the contract
require(msg.data.length == 0);
address payable dumbNoob = msg.sender;
dumbNoob.transfer(msg.value);
}
| fallback () payable external {
//refund noobs who send money directly to the contract
require(msg.data.length == 0);
address payable dumbNoob = msg.sender;
dumbNoob.transfer(msg.value);
}
| 22,227 |
192 | // Mapping that stores all Default and External position information for a given component. Position quantities are represented as virtual units; Default positions are on the top-level, while external positions are stored in a module array and accessed through its externalPositions mapping | mapping(address => ISetToken.ComponentPosition) private componentPositions;
| mapping(address => ISetToken.ComponentPosition) private componentPositions;
| 25,884 |
41 | // Check how much tokens already sold | if (preTge) {
| if (preTge) {
| 20,134 |
11 | // Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate reserve The address of the reserve to be updated liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) / | ) internal {
UpdateInterestRatesLocalVars memory vars;
vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress;
(vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress)
.getTotalSupplyAndAvgRate();
//calculates the total variable debt locally using the scaled total supply instead
//of totalSupply(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress)
.scaledTotalSupply()
.rayMul(reserve.variableBorrowIndex);
vars.availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress);
(
vars.newLiquidityRate,
vars.newStableRate,
vars.newVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
reserveAddress,
vars.availableLiquidity.add(liquidityAdded).sub(liquidityTaken),
vars.totalStableDebt,
vars.totalVariableDebt,
vars.avgStableRate,
reserve.configuration.getReserveFactor()
);
require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);
require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW);
require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentStableBorrowRate = uint128(vars.newStableRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newStableRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
| ) internal {
UpdateInterestRatesLocalVars memory vars;
vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress;
(vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress)
.getTotalSupplyAndAvgRate();
//calculates the total variable debt locally using the scaled total supply instead
//of totalSupply(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress)
.scaledTotalSupply()
.rayMul(reserve.variableBorrowIndex);
vars.availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress);
(
vars.newLiquidityRate,
vars.newStableRate,
vars.newVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
reserveAddress,
vars.availableLiquidity.add(liquidityAdded).sub(liquidityTaken),
vars.totalStableDebt,
vars.totalVariableDebt,
vars.avgStableRate,
reserve.configuration.getReserveFactor()
);
require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);
require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW);
require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentStableBorrowRate = uint128(vars.newStableRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newStableRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
| 29,901 |
37 | // Lightweight token modelled after UNI-LP: https:github.com/Uniswap/uniswap-v2-core/blob/v1.0.1/contracts/UniswapV2ERC20.sol Adds: - An exposed `mint()` with minting role - An exposed `burn()` - ERC-3009 (`transferWithAuthorization()`) | contract ANTv2 is IERC20 {
using SafeMath for uint256;
// bytes32 private constant EIP712DOMAIN_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
bytes32 private constant EIP712DOMAIN_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
// bytes32 private constant NAME_HASH = keccak256("Aragon Network Token")
bytes32 private constant NAME_HASH = 0x711a8013284a3c0046af6c0d6ed33e8bbc2c7a11d615cf4fdc8b1ac753bda618;
// bytes32 private constant VERSION_HASH = keccak256("1")
bytes32 private constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH =
// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)");
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
string public constant name = "Aragon Network Token";
string public constant symbol = "ANT";
uint8 public constant decimals = 18;
address public minter;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// ERC-2612, ERC-3009 state
mapping (address => uint256) public nonces;
mapping (address => mapping (bytes32 => bool)) public authorizationState;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
event ChangeMinter(address indexed minter);
modifier onlyMinter {
require(msg.sender == minter, "ANTV2:NOT_MINTER");
_;
}
constructor(address initialMinter) public {
_changeMinter(initialMinter);
}
function _validateSignedData(address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
getDomainSeparator(),
encodeData
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
// Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
require(recoveredAddress != address(0) && recoveredAddress == signer, "ANTV2:INVALID_SIGNATURE");
}
function _changeMinter(address newMinter) internal {
minter = newMinter;
emit ChangeMinter(newMinter);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
require(to != address(this) && to != address(0), "ANTV2:RECEIVER_IS_TOKEN_OR_ZERO");
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function getChainId() public pure returns (uint256 chainId) {
assembly { chainId := chainid() }
}
function getDomainSeparator() public view returns (bytes32) {
return keccak256(
abi.encode(
EIP712DOMAIN_HASH,
NAME_HASH,
VERSION_HASH,
getChainId(),
address(this)
)
);
}
function mint(address to, uint256 value) external onlyMinter returns (bool) {
_mint(to, value);
return true;
}
function changeMinter(address newMinter) external onlyMinter {
_changeMinter(newMinter);
}
function burn(uint256 value) external returns (bool) {
_burn(msg.sender, value);
return true;
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
uint256 fromAllowance = allowance[from][msg.sender];
if (fromAllowance != uint256(-1)) {
// Allowance is implicitly checked with SafeMath's underflow protection
allowance[from][msg.sender] = fromAllowance.sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "ANTV2:AUTH_EXPIRED");
bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
_validateSignedData(owner, encodeData, v, r, s);
_approve(owner, spender, value);
}
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(block.timestamp > validAfter, "ANTV2:AUTH_NOT_YET_VALID");
require(block.timestamp < validBefore, "ANTV2:AUTH_EXPIRED");
require(!authorizationState[from][nonce], "ANTV2:AUTH_ALREADY_USED");
bytes32 encodeData = keccak256(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce));
_validateSignedData(from, encodeData, v, r, s);
authorizationState[from][nonce] = true;
emit AuthorizationUsed(from, nonce);
_transfer(from, to, value);
}
}
| contract ANTv2 is IERC20 {
using SafeMath for uint256;
// bytes32 private constant EIP712DOMAIN_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
bytes32 private constant EIP712DOMAIN_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
// bytes32 private constant NAME_HASH = keccak256("Aragon Network Token")
bytes32 private constant NAME_HASH = 0x711a8013284a3c0046af6c0d6ed33e8bbc2c7a11d615cf4fdc8b1ac753bda618;
// bytes32 private constant VERSION_HASH = keccak256("1")
bytes32 private constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH =
// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)");
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
string public constant name = "Aragon Network Token";
string public constant symbol = "ANT";
uint8 public constant decimals = 18;
address public minter;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// ERC-2612, ERC-3009 state
mapping (address => uint256) public nonces;
mapping (address => mapping (bytes32 => bool)) public authorizationState;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
event ChangeMinter(address indexed minter);
modifier onlyMinter {
require(msg.sender == minter, "ANTV2:NOT_MINTER");
_;
}
constructor(address initialMinter) public {
_changeMinter(initialMinter);
}
function _validateSignedData(address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
getDomainSeparator(),
encodeData
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
// Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
require(recoveredAddress != address(0) && recoveredAddress == signer, "ANTV2:INVALID_SIGNATURE");
}
function _changeMinter(address newMinter) internal {
minter = newMinter;
emit ChangeMinter(newMinter);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
require(to != address(this) && to != address(0), "ANTV2:RECEIVER_IS_TOKEN_OR_ZERO");
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function getChainId() public pure returns (uint256 chainId) {
assembly { chainId := chainid() }
}
function getDomainSeparator() public view returns (bytes32) {
return keccak256(
abi.encode(
EIP712DOMAIN_HASH,
NAME_HASH,
VERSION_HASH,
getChainId(),
address(this)
)
);
}
function mint(address to, uint256 value) external onlyMinter returns (bool) {
_mint(to, value);
return true;
}
function changeMinter(address newMinter) external onlyMinter {
_changeMinter(newMinter);
}
function burn(uint256 value) external returns (bool) {
_burn(msg.sender, value);
return true;
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
uint256 fromAllowance = allowance[from][msg.sender];
if (fromAllowance != uint256(-1)) {
// Allowance is implicitly checked with SafeMath's underflow protection
allowance[from][msg.sender] = fromAllowance.sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "ANTV2:AUTH_EXPIRED");
bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
_validateSignedData(owner, encodeData, v, r, s);
_approve(owner, spender, value);
}
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(block.timestamp > validAfter, "ANTV2:AUTH_NOT_YET_VALID");
require(block.timestamp < validBefore, "ANTV2:AUTH_EXPIRED");
require(!authorizationState[from][nonce], "ANTV2:AUTH_ALREADY_USED");
bytes32 encodeData = keccak256(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce));
_validateSignedData(from, encodeData, v, r, s);
authorizationState[from][nonce] = true;
emit AuthorizationUsed(from, nonce);
_transfer(from, to, value);
}
}
| 38,539 |
87 | // Open a NToken for a token by anyone (contracts aren't allowed)/Create and map the (Token, NToken) pair in NestPool/tokenAddress The address of token contract | function open(address tokenAddress) external;
| function open(address tokenAddress) external;
| 12,535 |
79 | // Use this in case ETH are sent to the contract by mistake | function rescueETH(uint256 weiAmount) external onlyOwner{
require(address(this).balance >= weiAmount, "insufficient ETH balance");
payable(owner()).transfer(weiAmount);
}
| function rescueETH(uint256 weiAmount) external onlyOwner{
require(address(this).balance >= weiAmount, "insufficient ETH balance");
payable(owner()).transfer(weiAmount);
}
| 44,846 |
1 | // IERC20 TLWtoken = IERC20(0x67cdb81b89edd61158c60e8b97a65f3cb115d52e);/ | {
IERC1155 tokenContract = IERC1155(tokenAddress);
require(tokenContract.balanceOf(msg.sender, tokenId) > 0); //check if caller is owner of this token
_;
}
| {
IERC1155 tokenContract = IERC1155(tokenAddress);
require(tokenContract.balanceOf(msg.sender, tokenId) > 0); //check if caller is owner of this token
_;
}
| 31,227 |
24 | // Get balance of the address provided | function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
| function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
| 51,313 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.