Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
Contract Name:
SynthereumVault
Compiler Version
v0.8.9+commit.e5eed63a
Optimization Enabled:
Yes with 200 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {IERC20} from '../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {ISynthereumFinder} from '../core/interfaces/IFinder.sol';
import {IStandardERC20} from '../base/interfaces/IStandardERC20.sol';
import {IPoolVault} from '../synthereum-pool/common/interfaces/IPoolVault.sol';
import {IVault} from './interfaces/IVault.sol';
import {SynthereumInterfaces} from '../core/Constants.sol';
import {PreciseUnitMath} from '../base/utils/PreciseUnitMath.sol';
import {ISynthereumPriceFeed} from '../oracle/interfaces/IPriceFeed.sol';
import {SafeERC20} from '../../@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {SynthereumFactoryAccess} from '../common/libs/FactoryAccess.sol';
import {SynthereumBaseVaultStorage} from './BaseVaultStorage.sol';
contract SynthereumVault is IVault, SynthereumBaseVaultStorage {
using SafeERC20 for IERC20;
using PreciseUnitMath for uint256;
struct DepositCache {
uint256 netCollateralDeposited;
uint256 actualCollateralAmount;
uint256 spreadAdjustedCollateral;
uint256 fee;
uint256 rate;
uint256 discountedRate;
uint256 totalSupply;
uint256 vaultCoverage;
uint256 scalingValue;
uint128 overCollateralFactor;
}
struct WithdrawCache {
uint256 vaultCollateralAmount;
uint256 totSupply;
uint256 scalingValue;
uint256 rate;
uint256 collateralEquivalent;
uint256 removeCollateral;
bool isFullPosition;
}
struct FeeCache {
uint256 positionCollateral;
uint256 amount;
uint256 lpShare;
uint256 totalShares;
uint256 coverage;
bool isDeposit;
}
modifier onlyVaultRegistry() {
address vaultRegistry = synthereumFinder.getImplementationAddress(
SynthereumInterfaces.VaultRegistry
);
require(msg.sender == vaultRegistry, 'Sender must be vault registry');
_;
}
constructor() {
version = 1;
_disableInitializers();
}
function initialize(
string memory _lpTokenName,
string memory _lpTokenSymbol,
address _pool,
uint128 _overCollateralization,
ISynthereumFinder _finder
) external override initializer nonReentrant {
// vault initialisation
pool = IPoolVault(_pool);
priceFeedIdentifier = pool.priceFeedIdentifier();
collateralAsset = pool.collateralToken();
overCollateralization = _overCollateralization;
synthereumFinder = _finder;
collateralDecimals = IStandardERC20(address(collateralAsset)).decimals();
version = 1;
// // reentrancy and erc20 initialisation
__ReentrancyGuard_init();
__ERC20_init(_lpTokenName, _lpTokenSymbol);
__ERC20Permit_init(_lpTokenName);
}
function deposit(uint256 collateralAmount, address recipient)
external
override
nonReentrant
returns (uint256 lpTokensOut)
{
require(collateralAmount > 0, 'Zero amount');
// transfer collateral - checks balance
address sender = _msgSender();
collateralAsset.safeTransferFrom(sender, address(this), collateralAmount);
// approve pool to pull collateral
collateralAsset.safeIncreaseAllowance(address(pool), collateralAmount);
// to retrieve updated vault position on pool
IPoolVault.LPInfo memory vaultPosition;
// to cache intermediate values
DepositCache memory cache;
cache.totalSupply = totalSupply();
cache.overCollateralFactor = overCollateralization;
// deposit collateral (activate if first deposit) into pool and trigger positions update
if (isLpActive) {
vaultPosition = pool.positionLPInfo(address(this));
(cache.netCollateralDeposited, cache.actualCollateralAmount) = pool
.addLiquidity(collateralAmount);
if (cache.totalSupply == 0) {
vaultPosition.coverage = PreciseUnitMath.MAX_UINT_256;
}
} else {
cache.netCollateralDeposited = pool.activateLP(
collateralAmount,
cache.overCollateralFactor
);
cache.actualCollateralAmount = cache.netCollateralDeposited;
vaultPosition.coverage = PreciseUnitMath.MAX_UINT_256;
isLpActive = true;
emit LPActivated(collateralAmount, cache.overCollateralFactor);
}
cache.scalingValue = scalingFactor();
cache.vaultCoverage = vaultPosition.coverage;
uint256 positionCollBefore = cache.actualCollateralAmount -
cache.netCollateralDeposited;
if (
cache.vaultCoverage >=
PreciseUnitMath.PRECISE_UNIT + cache.overCollateralFactor
) {
if (cache.totalSupply != 0) {
(cache.spreadAdjustedCollateral, cache.fee) = applySpread(
FeeCache(
positionCollBefore,
cache.netCollateralDeposited,
cache.netCollateralDeposited,
cache.actualCollateralAmount,
cache.vaultCoverage,
true
)
);
} else {
cache.spreadAdjustedCollateral = cache.netCollateralDeposited;
}
// calculate rate
cache.rate = calculateRate(
positionCollBefore + cache.fee,
cache.totalSupply,
cache.scalingValue
);
lpTokensOut = (cache.spreadAdjustedCollateral * cache.scalingValue).div(
cache.rate
);
} else {
// calculate rate and discounted rate
uint256 maxCollateralAtDiscount;
(
,
cache.discountedRate,
maxCollateralAtDiscount
) = calculateDiscountedRate(
cache.vaultCoverage,
positionCollBefore,
cache.totalSupply,
cache.scalingValue,
cache.overCollateralFactor
);
if (cache.netCollateralDeposited <= maxCollateralAtDiscount) {
lpTokensOut = (cache.netCollateralDeposited * cache.scalingValue).div(
cache.discountedRate
);
} else {
uint256 remainingCollateral = cache.netCollateralDeposited -
maxCollateralAtDiscount;
(cache.spreadAdjustedCollateral, cache.fee) = applySpread(
FeeCache(
cache.actualCollateralAmount - remainingCollateral,
remainingCollateral,
remainingCollateral,
cache.actualCollateralAmount,
PreciseUnitMath.PRECISE_UNIT + cache.overCollateralFactor,
true
)
);
cache.rate = calculateRate(
positionCollBefore + cache.fee,
cache.totalSupply,
cache.scalingValue
);
lpTokensOut =
(maxCollateralAtDiscount * cache.scalingValue).div(
cache.discountedRate
) +
(cache.spreadAdjustedCollateral * cache.scalingValue).div(cache.rate);
}
}
// mint LP tokens to user
_mint(recipient, lpTokensOut);
// log event
emit Deposit(
sender,
recipient,
cache.netCollateralDeposited,
lpTokensOut,
cache.rate,
cache.discountedRate
);
}
function withdraw(uint256 lpTokensAmount, address recipient)
external
override
nonReentrant
returns (uint256 collateralOut)
{
require(lpTokensAmount > 0, 'Zero amount');
// retrieve updated vault position on pool
IPoolVault.LPInfo memory vaultPosition = pool.positionLPInfo(address(this));
WithdrawCache memory cache;
cache.vaultCollateralAmount = vaultPosition.actualCollateralAmount;
// calculate rate and amount of collateral to withdraw
cache.totSupply = totalSupply();
cache.scalingValue = scalingFactor();
cache.rate = calculateRate(
cache.vaultCollateralAmount,
cache.totSupply,
cache.scalingValue
);
cache.isFullPosition = lpTokensAmount == cache.totSupply;
cache.collateralEquivalent = cache.isFullPosition
? cache.vaultCollateralAmount
: lpTokensAmount.mul(cache.rate) / cache.scalingValue;
// Burn LP tokens of user
address sender = _msgSender();
_burn(sender, lpTokensAmount);
// withdraw collateral from pool
if (cache.isFullPosition) {
cache.removeCollateral = cache.collateralEquivalent;
} else {
(cache.removeCollateral, ) = applySpread(
FeeCache(
cache.vaultCollateralAmount,
cache.collateralEquivalent,
lpTokensAmount,
cache.totSupply,
vaultPosition.coverage,
false
)
);
}
(, collateralOut, ) = pool.removeLiquidity(cache.removeCollateral);
// transfer to user the net collateral out
collateralAsset.safeTransfer(recipient, collateralOut);
emit Withdraw(sender, recipient, lpTokensAmount, collateralOut, cache.rate);
}
function donate(uint256 collateralAmount) external {
require(collateralAmount > 0, 'Zero amount');
// transfer collateral - checks balance
address sender = _msgSender();
collateralAsset.safeTransferFrom(sender, address(this), collateralAmount);
// approve pool to pull collateral
collateralAsset.safeIncreaseAllowance(address(pool), collateralAmount);
// add liquidity to vault position in pool
pool.addLiquidity(collateralAmount);
emit Donation(sender, collateralAmount);
}
function setReferencePool(address newPool)
external
override
onlyVaultRegistry
{
pool = IPoolVault(newPool);
}
function getRate() external view override returns (uint256 rate) {
rate = calculateRate(
(pool.positionLPInfo(address(this))).actualCollateralAmount,
totalSupply(),
scalingFactor()
);
}
function getDiscountedRate()
external
view
override
returns (
uint256 rate,
uint256 discountedRate,
uint256 maxCollateralDiscounted
)
{
IPoolVault.LPInfo memory vaultPosition = pool.positionLPInfo(address(this));
uint256 coverage = vaultPosition.coverage;
uint256 collateralAmount = vaultPosition.actualCollateralAmount;
// return zeros if not in discount state
uint128 overCollateralFactor = overCollateralization;
if (coverage >= PreciseUnitMath.PRECISE_UNIT + overCollateralFactor) {
return (
calculateRate(collateralAmount, totalSupply(), scalingFactor()),
0,
0
);
}
// otherwise calculate discount
(rate, discountedRate, maxCollateralDiscounted) = calculateDiscountedRate(
coverage,
collateralAmount,
totalSupply(),
scalingFactor(),
overCollateralFactor
);
}
function getVersion() external view override returns (uint256) {
return version;
}
function getPool() external view override returns (address poolAddress) {
poolAddress = address(pool);
}
function getPoolCollateral()
external
view
override
returns (address collateral)
{
collateral = address(collateralAsset);
}
function getOvercollateralization()
external
view
override
returns (uint128 overcollateral)
{
overcollateral = overCollateralization;
}
function getSpread()
external
view
override
returns (uint256 maxSpreadLong, uint256 maxSpreadShort)
{
ISynthereumPriceFeed priceFeed = ISynthereumPriceFeed(
synthereumFinder.getImplementationAddress(SynthereumInterfaces.PriceFeed)
);
maxSpreadLong = priceFeed.longMaxSpread(priceFeedIdentifier);
maxSpreadShort = priceFeed.shortMaxSpread(priceFeedIdentifier);
}
function scalingFactor() internal view returns (uint256) {
return 10**(18 - collateralDecimals);
}
function calculateRate(
uint256 positionCollateralAmount,
uint256 totalSupply,
uint256 scalingValue
) internal pure returns (uint256 rate) {
// calculate rate
rate = totalSupply == 0
? PreciseUnitMath.PRECISE_UNIT
: (positionCollateralAmount * scalingValue).div(totalSupply);
}
function calculateDiscountedRate(
uint256 coverage,
uint256 actualCollateralAmount,
uint256 totalSupply,
uint256 scalingValue,
uint256 overCollateralFactor
)
internal
pure
returns (
uint256 rate,
uint256 discountedRate,
uint256 collateralDeficit
)
{
// get regular rate
rate = calculateRate(actualCollateralAmount, totalSupply, scalingValue);
// collateralExpected = numTokens * price * overcollateralization
// numTokens * price * overCollateralization = actualCollateral * overColl / coverage - 1;
uint256 collateralExpected = (actualCollateralAmount)
.mul(overCollateralFactor)
.div(coverage - PreciseUnitMath.PRECISE_UNIT);
// collateral deficit = collateralExpected - actualCollateral
collateralDeficit = collateralExpected - actualCollateralAmount;
// discount = collateralDeficit / collateralExpected
// discounted rate = rate - (rate * discount)
discountedRate = rate - rate.mul(collateralDeficit.div(collateralExpected));
}
// apply spread % based on price feed spread
// the spread is applied when the vault is overcollateralized
// and is equal to the maximum gain one can have by
// front-running the price change from the oracle
// spread fee = amountIn * leverage * utilization * maxSpread
function applySpread(FeeCache memory _feeCache)
internal
view
returns (uint256 adjustedAmount, uint256 fee)
{
ISynthereumPriceFeed priceFeed = ISynthereumPriceFeed(
synthereumFinder.getImplementationAddress(SynthereumInterfaces.PriceFeed)
);
uint256 maxSpread = _feeCache.isDeposit
? priceFeed.shortMaxSpread(priceFeedIdentifier)
: priceFeed.longMaxSpread(priceFeedIdentifier);
if (_feeCache.isDeposit) {
uint256 scaleFactor = scalingFactor();
uint256 maxFrontRunScaled = (_feeCache.positionCollateral * scaleFactor)
.mul(maxSpread)
.div(_feeCache.coverage - PreciseUnitMath.PRECISE_UNIT);
fee =
maxFrontRunScaled.mul(_feeCache.lpShare * scaleFactor).div(
_feeCache.totalShares * scaleFactor + maxFrontRunScaled
) /
scaleFactor;
} else {
fee = _feeCache
.lpShare
.div(_feeCache.coverage - PreciseUnitMath.PRECISE_UNIT)
.mul(maxSpread)
.div(_feeCache.totalShares)
.mul(_feeCache.positionCollateral);
}
adjustedAmount = _feeCache.amount - fee;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*
* @custom:storage-size 52
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
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);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../utils/cryptography/EIP712Upgradeable.sol";
import "../../../utils/CountersUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*
* @custom:storage-size 51
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private constant _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
* However, to ensure consistency with the upgradeable transpiler, we will continue
* to reserve a slot.
* @custom:oz-renamed-from _PERMIT_TYPEHASH
*/
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {IERC20} from '../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IMintableBurnableERC20} from '../tokens/interfaces/IMintableBurnableERC20.sol';
import {ISynthereumFinder} from '../core/interfaces/IFinder.sol';
import {IPoolVault} from '../synthereum-pool/common/interfaces/IPoolVault.sol';
import {SynthereumInterfaces} from '../core/Constants.sol';
import {ContextUpgradeable} from '../../@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol';
import {ERC2771Context} from '../common/ERC2771Context.sol';
import {ReentrancyGuardUpgradeable} from '../../@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';
import {ERC20PermitUpgradeable} from '../../@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol';
abstract contract SynthereumBaseVaultStorage is
ERC2771Context,
ReentrancyGuardUpgradeable,
ERC20PermitUpgradeable
{
ISynthereumFinder internal synthereumFinder;
IPoolVault internal pool; // reference pool
IERC20 internal collateralAsset; // reference pool collateral token
uint8 internal collateralDecimals; // decimal unit of the collateral
bool internal isLpActive; // dictates if first deposit on pool or not
uint8 internal version; // version of the vault
uint128 internal overCollateralization; // overcollateralization of the vault position
bytes32 internal priceFeedIdentifier; // price feed id of the pool
function isTrustedForwarder(address forwarder)
public
view
override
returns (bool)
{
try
synthereumFinder.getImplementationAddress(
SynthereumInterfaces.TrustedForwarder
)
returns (address trustedForwarder) {
if (forwarder == trustedForwarder) {
return true;
} else {
return false;
}
} catch {
return false;
}
}
function _msgSender()
internal
view
override(ERC2771Context, ContextUpgradeable)
returns (address sender)
{
return ERC2771Context._msgSender();
}
function _msgData()
internal
view
override(ERC2771Context, ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771Context._msgData();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
/**
* @title ERC20 interface that includes burn mint and roles methods.
*/
interface IMintableBurnableERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev This method should be permissioned to only allow designated parties to burn tokens.
*/
function burn(uint256 value) external;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external returns (bool);
/**
* @notice Returns the number of decimals used to get its user representation.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/**
* @title Provides addresses of the contracts implementing certain interfaces.
*/
interface ISynthereumFinder {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(
bytes32 interfaceName,
address implementationAddress
) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress Address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName)
external
view
returns (address);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {IERC20} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IStandardERC20} from '../../../base/interfaces/IStandardERC20.sol';
import {IMintableBurnableERC20} from '../../../tokens/interfaces/IMintableBurnableERC20.sol';
import {ISynthereumFinder} from '../../../core/interfaces/IFinder.sol';
import {ISynthereumDeployment} from '../../../common/interfaces/IDeployment.sol';
interface IPoolVault is ISynthereumDeployment {
struct LPInfo {
// Actual collateral owned
uint256 actualCollateralAmount;
// Number of tokens collateralized
uint256 tokensCollateralized;
// Overcollateralization percentage
uint256 overCollateralization;
// Actual Lp capacity of the Lp in synth asset (actualCollateralAmount/overCollateralization) * price - numTokens
uint256 capacity;
// Utilization ratio: (numTokens * price_inv * overCollateralization) / actualCollateralAmount
uint256 utilization;
// Collateral coverage: (actualCollateralAmount + numTokens * price_inv) / (numTokens * price_inv)
uint256 coverage;
// Mint shares percentage
uint256 mintShares;
// Redeem shares percentage
uint256 redeemShares;
// Interest shares percentage
uint256 interestShares;
// True if it's overcollateralized, otherwise false
bool isOvercollateralized;
}
/**
* @notice Returns the LP parametrs info
* @notice Mint, redeem and intreest shares are round down (division dust not included)
* @param _lp Address of the LP
* @return info Info of the input LP (see LPInfo struct)
*/
function positionLPInfo(address _lp)
external
view
returns (LPInfo memory info);
/**
* @notice Add collateral to an active LP position
* @notice Only an active LP can call this function to add collateral to his position
* @param _collateralAmount Collateral amount to deposit by the LP
* @return collateralDeposited Net collateral deposited in the LP position
* @return newLpCollateralAmount Amount of collateral of the LP after the increase
*/
function addLiquidity(uint256 _collateralAmount)
external
returns (uint256 collateralDeposited, uint256 newLpCollateralAmount);
/**
* @notice Add the Lp to the active list of the LPs and initialize collateral and overcollateralization
* @notice Only a registered and inactive LP can call this function to add himself
* @param _collateralAmount Collateral amount to deposit by the LP
* @param _overCollateralization Overcollateralization to set by the LP
* @return collateralDeposited Net collateral deposited in the LP position
*/
function activateLP(uint256 _collateralAmount, uint128 _overCollateralization)
external
returns (uint256 collateralDeposited);
/**
* @notice Withdraw collateral from an active LP position
* @notice Only an active LP can call this function to withdraw collateral from his position
* @param _collateralAmount Collateral amount to withdraw by the LP
* @return collateralRemoved Net collateral decreased form the position
* @return collateralReceived Collateral received from the withdrawal
* @return newLpCollateralAmount Amount of collateral of the LP after the decrease
*/
function removeLiquidity(uint256 _collateralAmount)
external
returns (
uint256 collateralRemoved,
uint256 collateralReceived,
uint256 newLpCollateralAmount
);
/**
* @notice Returns price identifier of the pool
* @return Price identifier
*/
function priceFeedIdentifier() external view returns (bytes32);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
/**
* @title Stores common interface names used throughout Synthereum.
*/
library SynthereumInterfaces {
bytes32 public constant Deployer = 'Deployer';
bytes32 public constant PoolRegistry = 'PoolRegistry';
bytes32 public constant SelfMintingRegistry = 'SelfMintingRegistry';
bytes32 public constant FixedRateRegistry = 'FixedRateRegistry';
bytes32 public constant VaultRegistry = 'VaultRegistry';
bytes32 public constant StakingLPVaultRegistry = 'StakingLPVaultRegistry';
bytes32 public constant FactoryVersioning = 'FactoryVersioning';
bytes32 public constant Manager = 'Manager';
bytes32 public constant TokenFactory = 'TokenFactory';
bytes32 public constant CreditLineController = 'CreditLineController';
bytes32 public constant CollateralWhitelist = 'CollateralWhitelist';
bytes32 public constant IdentifierWhitelist = 'IdentifierWhitelist';
bytes32 public constant LendingManager = 'LendingManager';
bytes32 public constant LendingStorageManager = 'LendingStorageManager';
bytes32 public constant CommissionReceiver = 'CommissionReceiver';
bytes32 public constant BuybackProgramReceiver = 'BuybackProgramReceiver';
bytes32 public constant LendingRewardsReceiver = 'LendingRewardsReceiver';
bytes32 public constant StakingRewardsReceiver = 'StakingRewardsReceiver';
bytes32 public constant JarvisToken = 'JarvisToken';
bytes32 public constant DebtTokenFactory = 'DebtTokenFactory';
bytes32 public constant VaultFactory = 'VaultFactory';
bytes32 public constant StakingLPVaultFactory = 'StakingLPVaultFactory';
bytes32 public constant PriceFeed = 'PriceFeed';
bytes32 public constant StakedJarvisToken = 'StakedJarvisToken';
bytes32 public constant StakingLPVaultData = 'StakingLPVaultData';
bytes32 public constant JarvisBrrrrr = 'JarvisBrrrrr';
bytes32 public constant MoneyMarketManager = 'MoneyMarketManager';
bytes32 public constant CrossChainBridge = 'CrossChainBridge';
bytes32 public constant TrustedForwarder = 'TrustedForwarder';
}
library FactoryInterfaces {
bytes32 public constant PoolFactory = 'PoolFactory';
bytes32 public constant SelfMintingFactory = 'SelfMintingFactory';
bytes32 public constant FixedRateFactory = 'FixedRateFactory';
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import {Context} from '../../@openzeppelin/contracts/utils/Context.sol';
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771Context is Context {
function isTrustedForwarder(address forwarder)
public
view
virtual
returns (bool);
function _msgSender()
internal
view
virtual
override
returns (address sender)
{
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[0:msg.data.length - 20];
} else {
return super._msgData();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IStandardERC20 is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {IERC20} from '../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {ISynthereumFinder} from '../../core/interfaces/IFinder.sol';
/**
* @title Interface that a pool MUST have in order to be included in the deployer
*/
interface ISynthereumDeployment {
/**
* @notice Get Synthereum finder of the pool/self-minting derivative
* @return finder Returns finder contract
*/
function synthereumFinder() external view returns (ISynthereumFinder finder);
/**
* @notice Get Synthereum version
* @return contractVersion Returns the version of this pool/self-minting derivative
*/
function version() external view returns (uint8 contractVersion);
/**
* @notice Get the collateral token of this pool/self-minting derivative
* @return collateralCurrency The ERC20 collateral token
*/
function collateralToken() external view returns (IERC20 collateralCurrency);
/**
* @notice Get the synthetic token associated to this pool/self-minting derivative
* @return syntheticCurrency The ERC20 synthetic token
*/
function syntheticToken() external view returns (IERC20 syntheticCurrency);
/**
* @notice Get the synthetic token symbol associated to this pool/self-minting derivative
* @return symbol The ERC20 synthetic token symbol
*/
function syntheticTokenSymbol() external view returns (string memory symbol);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {ISynthereumFinder} from '../../core/interfaces/IFinder.sol';
import {IVaultMigration} from './IVaultMigration.sol';
/**
* @title Provides interface for Public vault
*/
interface IVault is IVaultMigration {
event Deposit(
address indexed sender,
address indexed recipient,
uint256 netCollateralDeposited,
uint256 lpTokensOut,
uint256 rate,
uint256 discountedRate
);
event Withdraw(
address indexed sender,
address indexed recipient,
uint256 lpTokensBurned,
uint256 netCollateralOut,
uint256 rate
);
event LPActivated(uint256 collateralAmount, uint128 overCollateralization);
event Donation(address indexed sender, uint256 collateralAmount);
/**
* @notice Initialize vault as per OZ Clones pattern
* @param _lpTokenName name of the LP token representing a share in the vault
* @param _lpTokenSymbol symbol of the LP token representing a share in the vault
* @param _pool address of MultiLP pool the vault interacts with
* @param _overCollateralization over collateral requirement of the vault position in the pool
* @param _finder The synthereum finder
*/
function initialize(
string memory _lpTokenName,
string memory _lpTokenSymbol,
address _pool,
uint128 _overCollateralization,
ISynthereumFinder _finder
) external;
/**
* @notice Deposits collateral into the vault
* @param collateralAmount amount of collateral units
* @param recipient address receiving the LP token
* @return lpTokensOut amount of LP tokens received as output
*/
function deposit(uint256 collateralAmount, address recipient)
external
returns (uint256 lpTokensOut);
/**
* @notice Withdraw collateral from vault
* @param lpTokensAmount amount of LP token units
* @param recipient address receiving the collateral
* @return collateralOut amount of collateral received
*/
function withdraw(uint256 lpTokensAmount, address recipient)
external
returns (uint256 collateralOut);
/**
* @notice Deposits collateral into the vault as a form of donation (no LP token minted)
* @notice that will be split among existing LPs
*/
function donate(uint256 collateralAmount) external;
/**
* @notice Return current LP vault rate against collateral
* @return rate Vault rate
*/
function getRate() external view returns (uint256 rate);
/**
* @notice Return current LP vault discounted rate against collateral
* @return rate Vault rate
* @return discountedRate Vault discounted rate
* @return maxCollateralDiscounted max amount of collateral units at discount
*/
function getDiscountedRate()
external
view
returns (
uint256 rate,
uint256 discountedRate,
uint256 maxCollateralDiscounted
);
/**
* @notice Return the vault version
* @param version version of the vault
*/
function getVersion() external view returns (uint256 version);
/**
* @notice Return the vault reference pool
* @param poolAddress address of the pool
*/
function getPool() external view returns (address poolAddress);
/**
* @notice Return the vault collateral token
* @param collateral collateral token
*/
function getPoolCollateral() external view returns (address collateral);
/**
* @notice Return the vault overcollateralization factor
* @param overcollateral overcollateralization factor
*/
function getOvercollateralization()
external
view
returns (uint128 overcollateral);
/**
* @notice Return the vault reference pool max spread
* @param maxSpreadLong max spread for buying
* @param maxSpreadShort max spread for selling
*/
function getSpread()
external
view
returns (uint256 maxSpreadLong, uint256 maxSpreadShort);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
/**
* @title PreciseUnitMath
* @author Synthereum Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision.
*
*/
library PreciseUnitMath {
// The number One in precise units.
uint256 internal constant PRECISE_UNIT = 10**18;
// The number One in precise units multiplied for 10^18.
uint256 internal constant DOUBLE_PRECISE_UNIT = 10**36;
// Max unsigned integer value
uint256 internal constant MAX_UINT_256 = type(uint256).max;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * b) / PRECISE_UNIT;
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function mulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return (((a * b) - 1) / PRECISE_UNIT) + 1;
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * PRECISE_UNIT) / b;
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, 'Cant divide by 0');
return a > 0 ? (((a * PRECISE_UNIT) - 1) / b) + 1 : 0;
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(uint256 a, uint256 pow) internal pure returns (uint256) {
require(a > 0, 'Value must be positive');
uint256 result = 1;
for (uint256 i = 0; i < pow; i++) {
uint256 previousResult = result;
result = previousResult * a;
}
return result;
}
/**
* @dev The minimum of `a` and `b`.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev The maximum of `a` and `b`.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
interface ISynthereumPriceFeed {
/**
* @notice Return if a price identifier is supported
* @param _priceId Name of price identifier
* @return True fi supporteed, otherwise false
*/
function isPriceSupported(bytes32 _priceId) external view returns (bool);
/**
* @notice Get last price for a given price identifier
* @notice Only registered pools and registered self-minting derivatives can call this function
* @param _priceId HexName of price identifier
* @return Oracle price
*/
function getLatestPrice(bytes32 _priceId) external view returns (uint256);
/**
* @notice Get the max update spread for a given price identifier when price increases
* @param _priceId HexName of price identifier
* @return Max spread
*/
function longMaxSpread(bytes32 _priceId) external view returns (uint256);
/**
* @notice Get the max update spread for a given price identifier when price decreases
* @param _priceId HexName of price identifier
* @return Max spread
*/
function shortMaxSpread(bytes32 _priceId) external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {ISynthereumFinder} from '../../core/interfaces/IFinder.sol';
import {ISynthereumFactoryVersioning} from '../../core/interfaces/IFactoryVersioning.sol';
import {SynthereumInterfaces, FactoryInterfaces} from '../../core/Constants.sol';
/** @title Library to use for controlling the access of a functions from the factories
*/
library SynthereumFactoryAccess {
/**
*@notice Revert if caller is not a Pool factory
* @param _finder Synthereum finder
*/
function _onlyPoolFactory(ISynthereumFinder _finder) internal view {
ISynthereumFactoryVersioning factoryVersioning
= ISynthereumFactoryVersioning(
_finder.getImplementationAddress(SynthereumInterfaces.FactoryVersioning)
);
uint8 numberOfPoolFactories = factoryVersioning.numberOfFactoryVersions(
FactoryInterfaces.PoolFactory
);
require(
_checkSenderIsFactory(
factoryVersioning,
numberOfPoolFactories,
FactoryInterfaces.PoolFactory
),
'Not allowed'
);
}
/**
* @notice Revert if caller is not a Pool factory or a Fixed rate factory
* @param _finder Synthereum finder
*/
function _onlyPoolFactoryOrFixedRateFactory(ISynthereumFinder _finder)
internal
view
{
ISynthereumFactoryVersioning factoryVersioning
= ISynthereumFactoryVersioning(
_finder.getImplementationAddress(SynthereumInterfaces.FactoryVersioning)
);
uint8 numberOfPoolFactories = factoryVersioning.numberOfFactoryVersions(
FactoryInterfaces.PoolFactory
);
uint8 numberOfFixedRateFactories = factoryVersioning
.numberOfFactoryVersions(FactoryInterfaces.FixedRateFactory);
bool isPoolFactory = _checkSenderIsFactory(
factoryVersioning,
numberOfPoolFactories,
FactoryInterfaces.PoolFactory
);
if (isPoolFactory) {
return;
}
bool isFixedRateFactory = _checkSenderIsFactory(
factoryVersioning,
numberOfFixedRateFactories,
FactoryInterfaces.FixedRateFactory
);
if (isFixedRateFactory) {
return;
}
revert('Sender must be a Pool or FixedRate factory');
}
/**
* @notice Check if sender is a factory
* @param _factoryVersioning SynthereumFactoryVersioning contract
* @param _numberOfFactories Total number of versions of a factory type
* @param _factoryKind Type of the factory
* @return isFactory True if sender is a factory, otherwise false
*/
function _checkSenderIsFactory(
ISynthereumFactoryVersioning _factoryVersioning,
uint8 _numberOfFactories,
bytes32 _factoryKind
) private view returns (bool isFactory) {
uint8 counterFactory;
for (uint8 i = 0; counterFactory < _numberOfFactories; i++) {
try _factoryVersioning.getFactoryVersion(_factoryKind, i) returns (
address factory
) {
if (msg.sender == factory) {
isFactory = true;
break;
} else {
counterFactory++;
if (counterFactory == _numberOfFactories) {
isFactory = false;
}
}
} catch {}
}
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
/**
* @title Provides interface that need to be supported by a public vault during a pool migration
*/
interface IVaultMigration {
/**
* @notice Sets an address to be reference pool the vault is using
* @notice Only vault registry can call this method
* @param newPool address of the pool
*/
function setReferencePool(address newPool) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/**
* @title Provides addresses of different versions of pools factory and derivative factory
*/
interface ISynthereumFactoryVersioning {
/** @notice Sets a Factory
* @param factoryType Type of factory
* @param version Version of the factory to be set
* @param factory The pool factory address to be set
*/
function setFactory(
bytes32 factoryType,
uint8 version,
address factory
) external;
/** @notice Removes a factory
* @param factoryType The type of factory to be removed
* @param version Version of the factory to be removed
*/
function removeFactory(bytes32 factoryType, uint8 version) external;
/** @notice Gets a factory contract address
* @param factoryType The type of factory to be checked
* @param version Version of the factory to be checked
* @return factory Address of the factory contract
*/
function getFactoryVersion(bytes32 factoryType, uint8 version)
external
view
returns (address factory);
/** @notice Gets the number of factory versions for a specific type
* @param factoryType The type of factory to be checked
* @return numberOfVersions Total number of versions for a specific factory
*/
function numberOfFactoryVersions(bytes32 factoryType)
external
view
returns (uint8 numberOfVersions);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {ISynthereumFinder} from '../core/interfaces/IFinder.sol';
import {ISynthereumRegistry} from '../core/registries/interfaces/IRegistry.sol';
import {ISynthereumDeployment} from '../common/interfaces/IDeployment.sol';
import {IVault} from './interfaces/IVault.sol';
import {SynthereumInterfaces} from '../core/Constants.sol';
import {TransparentUpgradeableProxy} from '../../@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol';
contract SynthereumVaultCreator {
address internal immutable vaultImpl;
ISynthereumFinder immutable synthereumFinder;
/**
* @notice Constructs the Vault contract.
* @param _finder Address of the synthereum finder
* @param _vaultImplementation Address of the deployed vault implementation used for proxy
*/
constructor(address _finder, address _vaultImplementation) {
require(_vaultImplementation != address(0), 'Bad vault implementation');
require(_finder != address(0), 'Bad finder');
synthereumFinder = ISynthereumFinder(_finder);
vaultImpl = _vaultImplementation;
}
/**
* @notice Deploy a vault
* @param _lpTokenName name of the LP token representing a share in the vault
* @param _lpTokenSymbol symbol of the LP token representing a share in the vault
* @param _pool address of MultiLP pool the vault interacts with
* @param _overCollateralization over collateral requirement of the vault position in the pool
* @return vault Deployed vault
*/
function createVault(
string memory _lpTokenName,
string memory _lpTokenSymbol,
address _pool,
uint128 _overCollateralization
) public virtual returns (IVault vault) {
require(isPool(_pool), 'Bad pool');
require(bytes(_lpTokenName).length != 0, 'Missing LP token name');
require(bytes(_lpTokenSymbol).length != 0, 'Missing LP token symbol');
require(
_overCollateralization > 0,
'Overcollateral requirement must be bigger than 0%'
);
// deploy a transparent upgradable proxy and initialize implementation
address vaultProxy = address(
new TransparentUpgradeableProxy(
vaultImpl,
synthereumFinder.getImplementationAddress(SynthereumInterfaces.Manager),
abi.encodeWithSelector(
IVault.initialize.selector,
_lpTokenName,
_lpTokenSymbol,
_pool,
_overCollateralization,
synthereumFinder
)
)
);
vault = IVault(vaultProxy);
}
/**
* @notice Returns address of deployed vault implementation the factory is using
* @return implementation Vault implementation
*/
function vaultImplementation() public view virtual returns (address) {
return vaultImpl;
}
/**
* @notice ABI Encodes vault initialise method to construct a vault during deployment
* @param encodedParams ABI encoded parameters for constructor
* @return encodedCall Encoded function call with parameters
*/
function encodeInitialiseCall(bytes memory encodedParams)
public
view
virtual
returns (bytes memory encodedCall)
{
(
string memory name,
string memory symbol,
address pool,
uint128 overColl
) = decodeParams(encodedParams);
encodedCall = abi.encodeWithSelector(
IVault.initialize.selector,
name,
symbol,
pool,
overColl,
synthereumFinder
);
}
/**
* @notice Decodes constructor parameters into proper types
* @param encodedParams ABI encoded parameters for constructor
* @return LPTokenName string of LP token name
* @return LPTokenSymbol string of LP token symbol
* @return pool address of the reference synthereum pool
* @return overcollateralization uint128 Overcollateralization factor of the vault as LP
*/
function decodeParams(bytes memory encodedParams)
internal
pure
returns (
string memory,
string memory,
address,
uint128
)
{
return abi.decode(encodedParams, (string, string, address, uint128));
}
/**
* @notice Checks if address is a deployed and valid synthereum pool
* @param _pool address of the pool to check
* @return bool
*/
function isPool(address _pool) internal view returns (bool) {
ISynthereumRegistry registry = ISynthereumRegistry(
synthereumFinder.getImplementationAddress(
SynthereumInterfaces.PoolRegistry
)
);
ISynthereumDeployment callingContract = ISynthereumDeployment(_pool);
return
registry.isDeployed(
callingContract.syntheticTokenSymbol(),
callingContract.collateralToken(),
callingContract.version(),
_pool
);
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {IERC20} from '../../../../@openzeppelin/contracts/token/ERC20/IERC20.sol';
/**
* @title Provides interface with functions of SynthereumRegistry
*/
interface ISynthereumRegistry {
/**
* @notice Allow the deployer to register an element
* @param syntheticTokenSymbol Symbol of the syntheticToken of the element to register
* @param collateralToken Collateral ERC20 token of the element to register
* @param version Version of the element to register
* @param element Address of the element to register
*/
function register(
string calldata syntheticTokenSymbol,
IERC20 collateralToken,
uint8 version,
address element
) external;
/**
* @notice Allow the deployer to unregister an element
* @param syntheticTokenSymbol Symbol of the syntheticToken of the element to unregister
* @param collateralToken Collateral ERC20 token of the element to unregister
* @param version Version of the element to unregister
* @param element Address of the element to unregister
*/
function unregister(
string calldata syntheticTokenSymbol,
IERC20 collateralToken,
uint8 version,
address element
) external;
/**
* @notice Returns if a particular element exists or not
* @param syntheticTokenSymbol Synthetic token symbol of the element
* @param collateralToken ERC20 contract of collateral currency
* @param version Version of the element
* @param element Contract of the element to check
* @return isElementDeployed Returns true if a particular element exists, otherwise false
*/
function isDeployed(
string calldata syntheticTokenSymbol,
IERC20 collateralToken,
uint8 version,
address element
) external view returns (bool isElementDeployed);
/**
* @notice Returns all the elements with partcular symbol, collateral and version
* @param syntheticTokenSymbol Synthetic token symbol of the element
* @param collateralToken ERC20 contract of collateral currency
* @param version Version of the element
* @return List of all elements
*/
function getElements(
string calldata syntheticTokenSymbol,
IERC20 collateralToken,
uint8 version
) external view returns (address[] memory);
/**
* @notice Returns all the synthetic token symbol used
* @return List of all synthetic token symbol
*/
function getSyntheticTokens() external view returns (string[] memory);
/**
* @notice Returns all the versions used
* @return List of all versions
*/
function getVersions() external view returns (uint8[] memory);
/**
* @notice Returns all the collaterals used
* @return List of all collaterals
*/
function getCollaterals() external view returns (address[] memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967Proxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
*/
constructor(
address _logic,
address admin_,
bytes memory _data
) payable ERC1967Proxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_changeAdmin(admin_);
}
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _getAdmin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
_changeAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../Proxy.sol";
import "./ERC1967Upgrade.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// 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())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {IVault} from './interfaces/IVault.sol';
import {IVaultFactory} from './interfaces/IVaultFactory.sol';
import {IDeploymentSignature} from '../core/interfaces/IDeploymentSignature.sol';
import {ReentrancyGuard} from '../../@openzeppelin/contracts/security/ReentrancyGuard.sol';
import {FactoryConditions} from '../common/FactoryConditions.sol';
import {SynthereumVaultCreator} from './VaultCreator.sol';
contract SynthereumVaultFactory is
IVaultFactory,
IDeploymentSignature,
ReentrancyGuard,
FactoryConditions,
SynthereumVaultCreator
{
bytes4 public immutable override deploymentSignature;
/**
* @param _synthereumFinder Address of the synthereum finder
* @param _vaultImplementation Address of the deployed vault implementation used for EIP1167
*/
constructor(address _synthereumFinder, address _vaultImplementation)
SynthereumVaultCreator(_synthereumFinder, _vaultImplementation)
{
deploymentSignature = this.createVault.selector;
}
/**
* @notice Check if the sender is the deployer and deploy a vault
* @param _lpTokenName name of the LP token representing a share in the vault
* @param _lpTokenSymbol symbol of the LP token representing a share in the vault
* @param _pool address of MultiLP pool the vault interacts with
* @param _overCollateralization over collateral requirement of the vault position in the pool
* @return vault Deployed vault
*/
function createVault(
string memory _lpTokenName,
string memory _lpTokenSymbol,
address _pool,
uint128 _overCollateralization
)
public
override(IVaultFactory, SynthereumVaultCreator)
onlyDeployer(synthereumFinder)
nonReentrant
returns (IVault vault)
{
vault = super.createVault(
_lpTokenName,
_lpTokenSymbol,
_pool,
_overCollateralization
);
}
/**
* @notice ABI Encodes vault initialise method to construct a vault during deployment
* @param encodedParams ABI encoded parameters for constructor
* @return encodedCall Encoded function call with parameters
*/
function encodeInitialiseCall(bytes memory encodedParams)
public
view
override(IVaultFactory, SynthereumVaultCreator)
returns (bytes memory encodedCall)
{
encodedCall = super.encodeInitialiseCall(encodedParams);
}
/**
* @notice Returns address of deployed vault implementation the factory is using
* @return implementation Vault implementation
*/
function vaultImplementation()
public
view
override(IVaultFactory, SynthereumVaultCreator)
returns (address implementation)
{
implementation = super.vaultImplementation();
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {IVault} from './IVault.sol';
/**
* @title Provides interface for Public vault factory
*/
interface IVaultFactory {
/**
* @notice Deploy a public vault
* @param _lpTokenName name of the LP token representing a share in the vault
* @param _lpTokenSymbol symbol of the LP token representing a share in the vault
* @param _pool address of MultiLP pool the vault interacts with
* @param _overCollateralization over collateral requirement of the vault position in the pool
* @return vault Deployed vault
*/
function createVault(
string memory _lpTokenName,
string memory _lpTokenSymbol,
address _pool,
uint128 _overCollateralization
) external returns (IVault vault);
/**
* @notice Encodes the initialise call with its parameters
* @param encodedParams Abi encoded parameters
* @return encodedCall Bytes encoding of initialise call
*/
function encodeInitialiseCall(bytes memory encodedParams)
external
view
returns (bytes memory encodedCall);
/**
* @notice Returns the address of deployed vault implementation
* @return implementation deployed vault implementation
*/
function vaultImplementation() external view returns (address implementation);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/**
* @title Provides signature of function for deployment
*/
interface IDeploymentSignature {
/**
* @notice Returns the bytes4 signature of the function used for the deployment of a contract in a factory
* @return signature returns signature of the deployment function
*/
function deploymentSignature() external view returns (bytes4 signature);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {IStandardERC20} from '../base/interfaces/IStandardERC20.sol';
import {ISynthereumFinder} from '../core/interfaces/IFinder.sol';
import {ISynthereumCollateralWhitelist} from '../core/interfaces/ICollateralWhitelist.sol';
import {ISynthereumIdentifierWhitelist} from '../core/interfaces/IIdentifierWhitelist.sol';
import {SynthereumInterfaces} from '../core/Constants.sol';
/** @title Contract to use iniside factories for checking deployment data
*/
contract FactoryConditions {
/**
* @notice Check if the sender is the deployer
*/
modifier onlyDeployer(ISynthereumFinder _synthereumFinder) {
address deployer = _synthereumFinder.getImplementationAddress(
SynthereumInterfaces.Deployer
);
require(msg.sender == deployer, 'Sender must be Synthereum deployer');
_;
}
/**
* @notice Check if the sender is the deployer and if identifier and collateral are supported
* @param _synthereumFinder Synthereum finder
* @param _collateralToken Collateral token to check if it's in the whithelist
* @param _priceFeedIdentifier Identifier to check if it's in the whithelist
*/
function checkDeploymentConditions(
ISynthereumFinder _synthereumFinder,
IStandardERC20 _collateralToken,
bytes32 _priceFeedIdentifier
) internal view {
address deployer = _synthereumFinder.getImplementationAddress(
SynthereumInterfaces.Deployer
);
require(msg.sender == deployer, 'Sender must be Synthereum deployer');
ISynthereumCollateralWhitelist collateralWhitelist
= ISynthereumCollateralWhitelist(
_synthereumFinder.getImplementationAddress(
SynthereumInterfaces.CollateralWhitelist
)
);
require(
collateralWhitelist.isOnWhitelist(address(_collateralToken)),
'Collateral not supported'
);
ISynthereumIdentifierWhitelist identifierWhitelist
= ISynthereumIdentifierWhitelist(
_synthereumFinder.getImplementationAddress(
SynthereumInterfaces.IdentifierWhitelist
)
);
require(
identifierWhitelist.isOnWhitelist(_priceFeedIdentifier),
'Identifier not supported'
);
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/**
* @title An interface to track a whitelist of addresses.
*/
interface ISynthereumCollateralWhitelist {
/**
* @notice Adds an address to the whitelist.
* @param newCollateral the new address to add.
*/
function addToWhitelist(address newCollateral) external;
/**
* @notice Removes an address from the whitelist.
* @param collateralToRemove The existing address to remove.
*/
function removeFromWhitelist(address collateralToRemove) external;
/**
* @notice Checks whether an address is on the whitelist.
* @param collateralToCheck The address to check.
* @return True if `collateralToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address collateralToCheck)
external
view
returns (bool);
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @return The list of addresses on the whitelist.
*/
function getWhitelist() external view returns (address[] memory);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/**
* @title An interface to track a whitelist of identifiers.
*/
interface ISynthereumIdentifierWhitelist {
/**
* @notice Adds an identifier to the whitelist.
* @param newIdentifier the new identifier to add.
*/
function addToWhitelist(bytes32 newIdentifier) external;
/**
* @notice Removes an identifier from the whitelist.
* @param identifierToRemove The existing identifier to remove.
*/
function removeFromWhitelist(bytes32 identifierToRemove) external;
/**
* @notice Checks whether an address is on the whitelist.
* @param identifierToCheck The address to check.
* @return True if `identifierToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(bytes32 identifierToCheck)
external
view
returns (bool);
/**
* @notice Gets all identifiers that are currently included in the whitelist.
* @return The list of identifiers on the whitelist.
*/
function getWhitelist() external view returns (bytes32[] memory);
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.9;
import {ISynthereumFinder} from './interfaces/IFinder.sol';
import {AccessControlEnumerable} from '../../@openzeppelin/contracts/access/AccessControlEnumerable.sol';
/**
* @title Provides addresses of contracts implementing certain interfaces.
*/
contract SynthereumFinder is ISynthereumFinder, AccessControlEnumerable {
bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer');
//Describe role structure
struct Roles {
address admin;
address maintainer;
}
//----------------------------------------
// Storage
//----------------------------------------
mapping(bytes32 => address) public interfacesImplemented;
//----------------------------------------
// Events
//----------------------------------------
event InterfaceImplementationChanged(
bytes32 indexed interfaceName,
address indexed newImplementationAddress
);
//----------------------------------------
// Modifiers
//----------------------------------------
modifier onlyMaintainer() {
require(
hasRole(MAINTAINER_ROLE, msg.sender),
'Sender must be the maintainer'
);
_;
}
//----------------------------------------
// Constructors
//----------------------------------------
constructor(Roles memory roles) {
_setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE);
_setupRole(DEFAULT_ADMIN_ROLE, roles.admin);
_setupRole(MAINTAINER_ROLE, roles.maintainer);
}
//----------------------------------------
// External view
//----------------------------------------
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(
bytes32 interfaceName,
address implementationAddress
) external override onlyMaintainer {
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress Address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName)
external
view
override
returns (address)
{
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), 'Implementation not found');
return implementationAddress;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}{
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"netCollateralDeposited","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"lpTokensOut","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rate","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"discountedRate","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"collateralAmount","type":"uint256"}],"name":"Donation","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"overCollateralization","type":"uint128"}],"name":"LPActivated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"lpTokensBurned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"netCollateralOut","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rate","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"lpTokensOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"collateralAmount","type":"uint256"}],"name":"donate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getDiscountedRate","outputs":[{"internalType":"uint256","name":"rate","type":"uint256"},{"internalType":"uint256","name":"discountedRate","type":"uint256"},{"internalType":"uint256","name":"maxCollateralDiscounted","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOvercollateralization","outputs":[{"internalType":"uint128","name":"overcollateral","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPool","outputs":[{"internalType":"address","name":"poolAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPoolCollateral","outputs":[{"internalType":"address","name":"collateral","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRate","outputs":[{"internalType":"uint256","name":"rate","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getSpread","outputs":[{"internalType":"uint256","name":"maxSpreadLong","type":"uint256"},{"internalType":"uint256","name":"maxSpreadShort","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getVersion","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_lpTokenName","type":"string"},{"internalType":"string","name":"_lpTokenSymbol","type":"string"},{"internalType":"address","name":"_pool","type":"address"},{"internalType":"uint128","name":"_overCollateralization","type":"uint128"},{"internalType":"contract ISynthereumFinder","name":"_finder","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"isTrustedForwarder","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newPool","type":"address"}],"name":"setReferencePool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"lpTokensAmount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"collateralOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
60806040523480156200001157600080fd5b50610100805460ff60b01b1916600160b01b1790556200003062000036565b620000f8565b600054610100900460ff1615620000a35760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff9081161015620000f6576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b61334380620001086000396000f3fe608060405234801561001057600080fd5b50600436106101a85760003560e01c80636e553f65116100f957806395d89b4111610097578063d505accf11610071578063d505accf146103a4578063dd62ed3e146103b7578063f14faf6f146103ca578063f6449113146103dd57600080fd5b806395d89b4114610376578063a457c2d71461037e578063a9059cbb1461039157600080fd5b80637d0bcd41116100d35780637d0bcd41146103115780637ecebe001461033457806395529b791461034757806395994ef71461036357600080fd5b80636e553f65146102b857806370a08231146102cb5780637b3cee60146102f457600080fd5b80631cec3fc0116101665780633644e515116101405780633644e51514610282578063395093511461028a578063572b6c051461029d578063679aefce146102b057600080fd5b80631cec3fc01461024b57806323b872dd14610260578063313ce5671461027357600080fd5b8062f714ce146101ad578063026b1d5f146101d357806306fdde03146101f8578063095ea7b31461020d5780630d8e6e2c1461023057806318160ddd14610243575b600080fd5b6101c06101bb366004612be9565b6103ef565b6040519081526020015b60405180910390f35b60ff546001600160a01b03165b6040516001600160a01b0390911681526020016101ca565b6102006106eb565b6040516101ca9190612c45565b61022061021b366004612c78565b61077d565b60405190151581526020016101ca565b61010054600160b01b900460ff166101c0565b6067546101c0565b61025e610259366004612d71565b61079f565b005b61022061026e366004612e1b565b610ade565b604051601281526020016101ca565b6101c0610b0e565b610220610298366004612c78565b610b1d565b6102206102ab366004612e5c565b610b49565b6101c0610c0f565b6101c06102c6366004612be9565b610ca4565b6101c06102d9366004612e5c565b6001600160a01b031660009081526065602052604090205490565b6102fc6112f6565b604080519283526020830191909152016101ca565b610319611493565b604080519384526020840192909252908201526060016101ca565b6101c0610342366004612e5c565b61159b565b610101546040516001600160801b0390911681526020016101ca565b61025e610371366004612e5c565b6115b9565b6102006116c2565b61022061038c366004612c78565b6116d1565b61022061039f366004612c78565b611762565b61025e6103b2366004612e88565b61177a565b6101c06103c5366004612ef9565b6118de565b61025e6103d8366004612f27565b611909565b610100546001600160a01b03166101e0565b60006103f9611a33565b600083116104225760405162461bcd60e51b815260040161041990612f40565b60405180910390fd5b60ff546040516359f6849760e01b81523060048201526000916001600160a01b0316906359f68497906024016101406040518083038186803b15801561046757600080fd5b505afa15801561047b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061049f9190612f75565b90506104e36040518060e001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000151581525090565b8151815260675460208201526104f7611a8d565b604082018190528151602083015161050e92611ab4565b60608201526020810151851460c08201819052610549576040810151606082015161053a908790611ae1565b6105449190613015565b61054c565b80515b6080820152600061055b611b00565b90506105678187611b0a565b8160c001511561058057608082015160a08301526105cf565b6105c86040518060c001604052808460000151815260200184608001518152602001888152602001846020015181526020018560a00151815260200160001515815250611c40565b5060a08301525b60ff5460a0830151604051639c8f9f2360e01b81526001600160a01b0390921691639c8f9f23916106069160040190815260200190565b606060405180830381600087803b15801561062057600080fd5b505af1158015610634573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106589190613037565b506101005490955061067591506001600160a01b03168686611ecb565b846001600160a01b0316816001600160a01b03167febff2602b3f468259e1e99f613fed6691f3a6526effe6ef3e768ba7ae7a36c4f888786606001516040516106d1939291909283526020830191909152604082015260600190565b60405180910390a35050506106e560018055565b92915050565b6060606880546106fa90613065565b80601f016020809104026020016040519081016040528092919081815260200182805461072690613065565b80156107735780601f1061074857610100808354040283529160200191610773565b820191906000526020600020905b81548152906001019060200180831161075657829003601f168201915b5050505050905090565b600080610788611b00565b9050610795818585611f34565b5060019392505050565b600054610100900460ff16158080156107bf5750600054600160ff909116105b806107d95750303b1580156107d9575060005460ff166001145b61083c5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610419565b6000805460ff19166001179055801561085f576000805461ff0019166101001790555b610867611a33565b60ff80546001600160a01b0319166001600160a01b038616908117909155604080516350d6dbc360e01b815290516350d6dbc391600480820192602092909190829003018186803b1580156108bb57600080fd5b505afa1580156108cf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f3919061309a565b6101025560ff5460408051632c805af560e21b815290516001600160a01b039092169163b2016bd491600480820192602092909190829003018186803b15801561093c57600080fd5b505afa158015610950573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061097491906130b3565b61010080546001600160a01b03199081166001600160a01b0393841690811790925561010180546fffffffffffffffffffffffffffffffff19166001600160801b03881617905560fe8054909116928516929092179091556040805163313ce56760e01b8152905163313ce56791600480820192602092909190829003018186803b158015610a0257600080fd5b505afa158015610a16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a3a91906130d0565b610100805460ff60b01b1960ff93909316600160a01b029290921662ff00ff60a01b1990921691909117600160b01b179055610a74612050565b610a7e8686612081565b610a87866120b6565b610a9060018055565b8015610ad6576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050565b600080610ae9611b00565b9050610af6858285612103565b610b0185858561217d565b60019150505b9392505050565b6000610b18612328565b905090565b600080610b28611b00565b9050610795818585610b3a85896118de565b610b4491906130ed565b611f34565b60fe546040516302abf57960e61b81526f2a393ab9ba32b22337b93bb0b93232b960811b60048201526000916001600160a01b03169063aafd5e409060240160206040518083038186803b158015610ba057600080fd5b505afa925050508015610bd0575060408051601f3d908101601f19168201909252610bcd918101906130b3565b60015b610bdc57506000919050565b806001600160a01b0316836001600160a01b03161415610bff5750600192915050565b50600092915050565b505b919050565b60ff546040516359f6849760e01b8152306004820152600091610b18916001600160a01b03909116906359f68497906024016101406040518083038186803b158015610c5a57600080fd5b505afa158015610c6e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c929190612f75565b516067545b610c9f611a8d565b611ab4565b6000610cae611a33565b60008311610cce5760405162461bcd60e51b815260040161041990612f40565b6000610cd8611b00565b61010054909150610cf4906001600160a01b03168230876123a3565b60ff5461010054610d12916001600160a01b039182169116866123db565b610d6a6040518061014001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000151581525090565b610dc960405180610140016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160006001600160801b031681525090565b60675460c0820152610101546001600160801b031661012082015261010054600160a81b900460ff1615610f0f5760ff546040516359f6849760e01b81523060048201526001600160a01b03909116906359f68497906024016101406040518083038186803b158015610e3b57600080fd5b505afa158015610e4f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e739190612f75565b60ff546040516328e32c8560e11b8152600481018990529193506001600160a01b0316906351c6590a906024016040805180830381600087803b158015610eb957600080fd5b505af1158015610ecd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef19190613105565b6020830152815260c0810151610f0a5760001960a08301525b611019565b60ff54610120820151604051630a9356ed60e01b8152600481018990526001600160801b0390911660248201526001600160a01b0390911690630a9356ed90604401602060405180830381600087803b158015610f6b57600080fd5b505af1158015610f7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fa3919061309a565b808252602082015260001960a0830152610100805460ff60a81b1916600160a81b1790556101208101516040517f0eb37f069c5cccf2af2c188796e5f4b448e6bfa2c51a09e94973cbbb3ea5a87391611010918991909182526001600160801b0316602082015260400190565b60405180910390a15b611021611a8d565b61010082015260a082015160e08201528051602082015160009161104491613129565b90508161012001516001600160801b0316670de0b6b3a764000061106891906130ed565b8260e001511061112b5760c0820151156110d3576110c46040518060c001604052808381526020018460000151815260200184600001518152602001846020015181526020018460e00151815260200160011515815250611c40565b606084015260408301526110db565b815160408301525b6110fe8260600151826110ee91906130ed565b8360c00151846101000151611ab4565b608083018190526101008301516040840151611124929161111e91613140565b9061249c565b945061127e565b60006111558360e00151838560c001518661010001518761012001516001600160801b03166124b1565b60a086019190915284519092508210905061118c5760a08301516101008401518451611185929161111e91613140565b955061127c565b825160009061119c908390613129565b90506112086040518060c001604052808387602001516111bc9190613129565b8152602001838152602001838152602001866020015181526020018661012001516001600160801b0316670de0b6b3a76400006111f991906130ed565b81526001602090910152611c40565b6060860181905260408601919091526112359061122590856130ed565b8560c00151866101000151611ab4565b608085018190526101008501516040860151611255929161111e91613140565b61126e8560a001518661010001518561111e9190613140565b61127891906130ed565b9650505b505b6112888686612517565b815160808084015160a085015160408051948552602085018a905284019190915260608301526001600160a01b0380891692908716917f5f971bd00bf3ffbca8a6d72cdd4fd92cfd4f62636161921d1e5a64f0b64ccb6d910160405180910390a3505050506106e560018055565b60fe546040516302abf57960e61b815268141c9a58d95199595960ba1b6004820152600091829182916001600160a01b03169063aafd5e409060240160206040518083038186803b15801561134a57600080fd5b505afa15801561135e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061138291906130b3565b61010254604051635414ab0b60e11b81529192506001600160a01b0383169163a8295616916113b79160040190815260200190565b60206040518083038186803b1580156113cf57600080fd5b505afa1580156113e3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611407919061309a565b61010254604051637b1146eb60e11b81529194506001600160a01b0383169163f6228dd69161143c9160040190815260200190565b60206040518083038186803b15801561145457600080fd5b505afa158015611468573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061148c919061309a565b9150509091565b60ff546040516359f6849760e01b81523060048201526000918291829182916001600160a01b03909116906359f68497906024016101406040518083038186803b1580156114e057600080fd5b505afa1580156114f4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115189190612f75565b60a081015181516101015492935090916001600160801b031661154381670de0b6b3a76400006130ed565b83106115665761155682610c9760675490565b9760009750879650945050505050565b61158b838361157460675490565b61157c611a8d565b856001600160801b03166124b1565b9199909850909650945050505050565b6001600160a01b038116600090815260cb60205260408120546106e5565b60fe546040516302abf57960e61b81526c5661756c74526567697374727960981b60048201526000916001600160a01b03169063aafd5e409060240160206040518083038186803b15801561160d57600080fd5b505afa158015611621573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061164591906130b3565b9050336001600160a01b0382161461169f5760405162461bcd60e51b815260206004820152601d60248201527f53656e646572206d757374206265207661756c742072656769737472790000006044820152606401610419565b5060ff80546001600160a01b0319166001600160a01b0392909216919091179055565b6060606980546106fa90613065565b6000806116dc611b00565b905060006116ea82866118de565b90508381101561174a5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610419565b6117578286868403611f34565b506001949350505050565b60008061176d611b00565b905061079581858561217d565b834211156117ca5760405162461bcd60e51b815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606401610419565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886117f98c6125d8565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090506000611854826125fe565b905060006118648287878761264c565b9050896001600160a01b0316816001600160a01b0316146118c75760405162461bcd60e51b815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152606401610419565b6118d28a8a8a611f34565b50505050505050505050565b6001600160a01b03918216600090815260666020908152604080832093909416825291909152205490565b600081116119295760405162461bcd60e51b815260040161041990612f40565b6000611933611b00565b6101005490915061194f906001600160a01b03168230856123a3565b60ff546101005461196d916001600160a01b039182169116846123db565b60ff546040516328e32c8560e11b8152600481018490526001600160a01b03909116906351c6590a906024016040805180830381600087803b1580156119b257600080fd5b505af11580156119c6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119ea9190613105565b5050806001600160a01b03167f5d8bc849764969eb1bcc6d0a2f55999d0167c1ccec240a4f39cf664ca9c4148e83604051611a2791815260200190565b60405180910390a25050565b60026001541415611a865760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610419565b6002600155565b61010054600090611aa990600160a01b900460ff16601261315f565b610b1890600a613266565b60008215611acf57611aca8361111e8487613140565b611ad9565b670de0b6b3a76400005b949350505050565b6000670de0b6b3a7640000611af68385613140565b610b079190613015565b6000610b18612674565b6001600160a01b038216611b6a5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610419565b6001600160a01b03821660009081526065602052604090205481811015611bde5760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610419565b6001600160a01b03831660008181526065602090815260408083208686039055606780548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91015b60405180910390a35b505050565b60fe546040516302abf57960e61b815268141c9a58d95199595960ba1b6004820152600091829182916001600160a01b03169063aafd5e409060240160206040518083038186803b158015611c9457600080fd5b505afa158015611ca8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ccc91906130b3565b905060008460a00151611d5b5761010254604051635414ab0b60e11b815260048101919091526001600160a01b0383169063a82956169060240160206040518083038186803b158015611d1e57600080fd5b505afa158015611d32573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d56919061309a565b611dd8565b61010254604051637b1146eb60e11b815260048101919091526001600160a01b0383169063f6228dd69060240160206040518083038186803b158015611da057600080fd5b505afa158015611db4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dd8919061309a565b90508460a0015115611e75576000611dee611a8d565b90506000611e27670de0b6b3a76400008860800151611e0d9190613129565b61111e85858b60000151611e219190613140565b90611ae1565b905081611e6282848a60600151611e3e9190613140565b611e4891906130ed565b61111e858b60400151611e5b9190613140565b8590611ae1565b611e6c9190613015565b94505050611eb2565b611eaf8560000151611e21876060015161111e85611e21670de0b6b3a76400008c60800151611ea49190613129565b60408d01519061249c565b92505b828560200151611ec29190613129565b93505050915091565b6040516001600160a01b038316602482015260448101829052611c3b90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612696565b60018055565b6001600160a01b038316611f965760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610419565b6001600160a01b038216611ff75760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610419565b6001600160a01b0383811660008181526066602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259101611c32565b600054610100900460ff166120775760405162461bcd60e51b815260040161041990613275565b61207f612768565b565b600054610100900460ff166120a85760405162461bcd60e51b815260040161041990613275565b6120b2828261278f565b5050565b600054610100900460ff166120dd5760405162461bcd60e51b815260040161041990613275565b61210081604051806040016040528060018152602001603160f81b8152506127dd565b50565b600061210f84846118de565b90506000198114612177578181101561216a5760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610419565b6121778484848403611f34565b50505050565b6001600160a01b0383166121e15760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610419565b6001600160a01b0382166122435760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610419565b6001600160a01b038316600090815260656020526040902054818110156122bb5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610419565b6001600160a01b0380851660008181526065602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9061231b9086815260200190565b60405180910390a3612177565b6000610b187f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f61235760975490565b6098546040805160208101859052908101839052606081018290524660808201523060a082015260009060c0016040516020818303038152906040528051906020012090509392505050565b6040516001600160a01b03808516602483015283166044820152606481018290526121779085906323b872dd60e01b90608401611ef7565b604051636eb1769f60e11b81523060048201526001600160a01b038381166024830152600091839186169063dd62ed3e9060440160206040518083038186803b15801561242757600080fd5b505afa15801561243b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061245f919061309a565b61246991906130ed565b6040516001600160a01b03851660248201526044810182905290915061217790859063095ea7b360e01b90606401611ef7565b600081611af6670de0b6b3a764000085613140565b60008060006124c1878787611ab4565b925060006124e46124da670de0b6b3a76400008b613129565b61111e8a88611ae1565b90506124f08882613129565b91506124ff611e5b838361249c565b6125099085613129565b925050955095509592505050565b6001600160a01b03821661256d5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610419565b806067600082825461257f91906130ed565b90915550506001600160a01b0382166000818152606560209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b6001600160a01b038116600090815260cb60205260409020805460018101825590610c08565b60006106e561260b612328565b8360405161190160f01b6020820152602281018390526042810182905260009060620160405160208183030381529060405280519060200120905092915050565b600080600061265d8787878761281e565b9150915061266a816128e2565b5095945050505050565b600061267f33610b49565b15612691575060131936013560601c90565b503390565b60006126eb826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612a309092919063ffffffff16565b805190915015611c3b578080602001905181019061270991906132c0565b611c3b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610419565b600054610100900460ff16611f2e5760405162461bcd60e51b815260040161041990613275565b600054610100900460ff166127b65760405162461bcd60e51b815260040161041990613275565b81516127c9906068906020850190612b3b565b508051611c3b906069906020840190612b3b565b600054610100900460ff166128045760405162461bcd60e51b815260040161041990613275565b815160209283012081519190920120609791909155609855565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a083111561285557506000905060036128d9565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa1580156128a9573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166128d2576000600192509250506128d9565b9150600090505b94509492505050565b60008160048111156128f6576128f66132db565b14156128ff5750565b6001816004811115612913576129136132db565b14156129615760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401610419565b6002816004811115612975576129756132db565b14156129c35760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610419565b60038160048111156129d7576129d76132db565b14156121005760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401610419565b6060611ad9848460008585843b612a895760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610419565b600080866001600160a01b03168587604051612aa591906132f1565b60006040518083038185875af1925050503d8060008114612ae2576040519150601f19603f3d011682016040523d82523d6000602084013e612ae7565b606091505b5091509150612af7828286612b02565b979650505050505050565b60608315612b11575081610b07565b825115612b215782518084602001fd5b8160405162461bcd60e51b81526004016104199190612c45565b828054612b4790613065565b90600052602060002090601f016020900481019282612b695760008555612baf565b82601f10612b8257805160ff1916838001178555612baf565b82800160010185558215612baf579182015b82811115612baf578251825591602001919060010190612b94565b50612bbb929150612bbf565b5090565b5b80821115612bbb5760008155600101612bc0565b6001600160a01b038116811461210057600080fd5b60008060408385031215612bfc57600080fd5b823591506020830135612c0e81612bd4565b809150509250929050565b60005b83811015612c34578181015183820152602001612c1c565b838111156121775750506000910152565b6020815260008251806020840152612c64816040850160208701612c19565b601f01601f19169190910160400192915050565b60008060408385031215612c8b57600080fd5b8235612c9681612bd4565b946020939093013593505050565b634e487b7160e01b600052604160045260246000fd5b604051610140810167ffffffffffffffff81118282101715612cde57612cde612ca4565b60405290565b600082601f830112612cf557600080fd5b813567ffffffffffffffff80821115612d1057612d10612ca4565b604051601f8301601f19908116603f01168101908282118183101715612d3857612d38612ca4565b81604052838152866020858801011115612d5157600080fd5b836020870160208301376000602085830101528094505050505092915050565b600080600080600060a08688031215612d8957600080fd5b853567ffffffffffffffff80821115612da157600080fd5b612dad89838a01612ce4565b96506020880135915080821115612dc357600080fd5b50612dd088828901612ce4565b9450506040860135612de181612bd4565b925060608601356001600160801b0381168114612dfd57600080fd5b91506080860135612e0d81612bd4565b809150509295509295909350565b600080600060608486031215612e3057600080fd5b8335612e3b81612bd4565b92506020840135612e4b81612bd4565b929592945050506040919091013590565b600060208284031215612e6e57600080fd5b8135610b0781612bd4565b60ff8116811461210057600080fd5b600080600080600080600060e0888a031215612ea357600080fd5b8735612eae81612bd4565b96506020880135612ebe81612bd4565b955060408801359450606088013593506080880135612edc81612e79565b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215612f0c57600080fd5b8235612f1781612bd4565b91506020830135612c0e81612bd4565b600060208284031215612f3957600080fd5b5035919050565b6020808252600b908201526a16995c9bc8185b5bdd5b9d60aa1b604082015260600190565b80518015158114610c0a57600080fd5b60006101408284031215612f8857600080fd5b612f90612cba565b825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a082015260c083015160c082015260e083015160e0820152610100808401518183015250610120612ff4818501612f65565b908201529392505050565b634e487b7160e01b600052601160045260246000fd5b60008261303257634e487b7160e01b600052601260045260246000fd5b500490565b60008060006060848603121561304c57600080fd5b8351925060208401519150604084015190509250925092565b600181811c9082168061307957607f821691505b60208210811415610c0857634e487b7160e01b600052602260045260246000fd5b6000602082840312156130ac57600080fd5b5051919050565b6000602082840312156130c557600080fd5b8151610b0781612bd4565b6000602082840312156130e257600080fd5b8151610b0781612e79565b6000821982111561310057613100612fff565b500190565b6000806040838503121561311857600080fd5b505080516020909101519092909150565b60008282101561313b5761313b612fff565b500390565b600081600019048311821515161561315a5761315a612fff565b500290565b600060ff821660ff84168082101561317957613179612fff565b90039392505050565b600181815b808511156131bd5781600019048211156131a3576131a3612fff565b808516156131b057918102915b93841c9390800290613187565b509250929050565b6000826131d4575060016106e5565b816131e1575060006106e5565b81600181146131f757600281146132015761321d565b60019150506106e5565b60ff84111561321257613212612fff565b50506001821b6106e5565b5060208310610133831016604e8410600b8410161715613240575081810a6106e5565b61324a8383613182565b806000190482111561325e5761325e612fff565b029392505050565b6000610b0760ff8416836131c5565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b6000602082840312156132d257600080fd5b610b0782612f65565b634e487b7160e01b600052602160045260246000fd5b60008251613303818460208701612c19565b919091019291505056fea2646970667358221220f182585791bc5828a38fe9d989effd6abaf526499408e02d5798a285d6fafd8964736f6c63430008090033
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106101a85760003560e01c80636e553f65116100f957806395d89b4111610097578063d505accf11610071578063d505accf146103a4578063dd62ed3e146103b7578063f14faf6f146103ca578063f6449113146103dd57600080fd5b806395d89b4114610376578063a457c2d71461037e578063a9059cbb1461039157600080fd5b80637d0bcd41116100d35780637d0bcd41146103115780637ecebe001461033457806395529b791461034757806395994ef71461036357600080fd5b80636e553f65146102b857806370a08231146102cb5780637b3cee60146102f457600080fd5b80631cec3fc0116101665780633644e515116101405780633644e51514610282578063395093511461028a578063572b6c051461029d578063679aefce146102b057600080fd5b80631cec3fc01461024b57806323b872dd14610260578063313ce5671461027357600080fd5b8062f714ce146101ad578063026b1d5f146101d357806306fdde03146101f8578063095ea7b31461020d5780630d8e6e2c1461023057806318160ddd14610243575b600080fd5b6101c06101bb366004612be9565b6103ef565b6040519081526020015b60405180910390f35b60ff546001600160a01b03165b6040516001600160a01b0390911681526020016101ca565b6102006106eb565b6040516101ca9190612c45565b61022061021b366004612c78565b61077d565b60405190151581526020016101ca565b61010054600160b01b900460ff166101c0565b6067546101c0565b61025e610259366004612d71565b61079f565b005b61022061026e366004612e1b565b610ade565b604051601281526020016101ca565b6101c0610b0e565b610220610298366004612c78565b610b1d565b6102206102ab366004612e5c565b610b49565b6101c0610c0f565b6101c06102c6366004612be9565b610ca4565b6101c06102d9366004612e5c565b6001600160a01b031660009081526065602052604090205490565b6102fc6112f6565b604080519283526020830191909152016101ca565b610319611493565b604080519384526020840192909252908201526060016101ca565b6101c0610342366004612e5c565b61159b565b610101546040516001600160801b0390911681526020016101ca565b61025e610371366004612e5c565b6115b9565b6102006116c2565b61022061038c366004612c78565b6116d1565b61022061039f366004612c78565b611762565b61025e6103b2366004612e88565b61177a565b6101c06103c5366004612ef9565b6118de565b61025e6103d8366004612f27565b611909565b610100546001600160a01b03166101e0565b60006103f9611a33565b600083116104225760405162461bcd60e51b815260040161041990612f40565b60405180910390fd5b60ff546040516359f6849760e01b81523060048201526000916001600160a01b0316906359f68497906024016101406040518083038186803b15801561046757600080fd5b505afa15801561047b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061049f9190612f75565b90506104e36040518060e001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000151581525090565b8151815260675460208201526104f7611a8d565b604082018190528151602083015161050e92611ab4565b60608201526020810151851460c08201819052610549576040810151606082015161053a908790611ae1565b6105449190613015565b61054c565b80515b6080820152600061055b611b00565b90506105678187611b0a565b8160c001511561058057608082015160a08301526105cf565b6105c86040518060c001604052808460000151815260200184608001518152602001888152602001846020015181526020018560a00151815260200160001515815250611c40565b5060a08301525b60ff5460a0830151604051639c8f9f2360e01b81526001600160a01b0390921691639c8f9f23916106069160040190815260200190565b606060405180830381600087803b15801561062057600080fd5b505af1158015610634573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106589190613037565b506101005490955061067591506001600160a01b03168686611ecb565b846001600160a01b0316816001600160a01b03167febff2602b3f468259e1e99f613fed6691f3a6526effe6ef3e768ba7ae7a36c4f888786606001516040516106d1939291909283526020830191909152604082015260600190565b60405180910390a35050506106e560018055565b92915050565b6060606880546106fa90613065565b80601f016020809104026020016040519081016040528092919081815260200182805461072690613065565b80156107735780601f1061074857610100808354040283529160200191610773565b820191906000526020600020905b81548152906001019060200180831161075657829003601f168201915b5050505050905090565b600080610788611b00565b9050610795818585611f34565b5060019392505050565b600054610100900460ff16158080156107bf5750600054600160ff909116105b806107d95750303b1580156107d9575060005460ff166001145b61083c5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610419565b6000805460ff19166001179055801561085f576000805461ff0019166101001790555b610867611a33565b60ff80546001600160a01b0319166001600160a01b038616908117909155604080516350d6dbc360e01b815290516350d6dbc391600480820192602092909190829003018186803b1580156108bb57600080fd5b505afa1580156108cf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f3919061309a565b6101025560ff5460408051632c805af560e21b815290516001600160a01b039092169163b2016bd491600480820192602092909190829003018186803b15801561093c57600080fd5b505afa158015610950573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061097491906130b3565b61010080546001600160a01b03199081166001600160a01b0393841690811790925561010180546fffffffffffffffffffffffffffffffff19166001600160801b03881617905560fe8054909116928516929092179091556040805163313ce56760e01b8152905163313ce56791600480820192602092909190829003018186803b158015610a0257600080fd5b505afa158015610a16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a3a91906130d0565b610100805460ff60b01b1960ff93909316600160a01b029290921662ff00ff60a01b1990921691909117600160b01b179055610a74612050565b610a7e8686612081565b610a87866120b6565b610a9060018055565b8015610ad6576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050565b600080610ae9611b00565b9050610af6858285612103565b610b0185858561217d565b60019150505b9392505050565b6000610b18612328565b905090565b600080610b28611b00565b9050610795818585610b3a85896118de565b610b4491906130ed565b611f34565b60fe546040516302abf57960e61b81526f2a393ab9ba32b22337b93bb0b93232b960811b60048201526000916001600160a01b03169063aafd5e409060240160206040518083038186803b158015610ba057600080fd5b505afa925050508015610bd0575060408051601f3d908101601f19168201909252610bcd918101906130b3565b60015b610bdc57506000919050565b806001600160a01b0316836001600160a01b03161415610bff5750600192915050565b50600092915050565b505b919050565b60ff546040516359f6849760e01b8152306004820152600091610b18916001600160a01b03909116906359f68497906024016101406040518083038186803b158015610c5a57600080fd5b505afa158015610c6e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c929190612f75565b516067545b610c9f611a8d565b611ab4565b6000610cae611a33565b60008311610cce5760405162461bcd60e51b815260040161041990612f40565b6000610cd8611b00565b61010054909150610cf4906001600160a01b03168230876123a3565b60ff5461010054610d12916001600160a01b039182169116866123db565b610d6a6040518061014001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000151581525090565b610dc960405180610140016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160006001600160801b031681525090565b60675460c0820152610101546001600160801b031661012082015261010054600160a81b900460ff1615610f0f5760ff546040516359f6849760e01b81523060048201526001600160a01b03909116906359f68497906024016101406040518083038186803b158015610e3b57600080fd5b505afa158015610e4f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e739190612f75565b60ff546040516328e32c8560e11b8152600481018990529193506001600160a01b0316906351c6590a906024016040805180830381600087803b158015610eb957600080fd5b505af1158015610ecd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ef19190613105565b6020830152815260c0810151610f0a5760001960a08301525b611019565b60ff54610120820151604051630a9356ed60e01b8152600481018990526001600160801b0390911660248201526001600160a01b0390911690630a9356ed90604401602060405180830381600087803b158015610f6b57600080fd5b505af1158015610f7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fa3919061309a565b808252602082015260001960a0830152610100805460ff60a81b1916600160a81b1790556101208101516040517f0eb37f069c5cccf2af2c188796e5f4b448e6bfa2c51a09e94973cbbb3ea5a87391611010918991909182526001600160801b0316602082015260400190565b60405180910390a15b611021611a8d565b61010082015260a082015160e08201528051602082015160009161104491613129565b90508161012001516001600160801b0316670de0b6b3a764000061106891906130ed565b8260e001511061112b5760c0820151156110d3576110c46040518060c001604052808381526020018460000151815260200184600001518152602001846020015181526020018460e00151815260200160011515815250611c40565b606084015260408301526110db565b815160408301525b6110fe8260600151826110ee91906130ed565b8360c00151846101000151611ab4565b608083018190526101008301516040840151611124929161111e91613140565b9061249c565b945061127e565b60006111558360e00151838560c001518661010001518761012001516001600160801b03166124b1565b60a086019190915284519092508210905061118c5760a08301516101008401518451611185929161111e91613140565b955061127c565b825160009061119c908390613129565b90506112086040518060c001604052808387602001516111bc9190613129565b8152602001838152602001838152602001866020015181526020018661012001516001600160801b0316670de0b6b3a76400006111f991906130ed565b81526001602090910152611c40565b6060860181905260408601919091526112359061122590856130ed565b8560c00151866101000151611ab4565b608085018190526101008501516040860151611255929161111e91613140565b61126e8560a001518661010001518561111e9190613140565b61127891906130ed565b9650505b505b6112888686612517565b815160808084015160a085015160408051948552602085018a905284019190915260608301526001600160a01b0380891692908716917f5f971bd00bf3ffbca8a6d72cdd4fd92cfd4f62636161921d1e5a64f0b64ccb6d910160405180910390a3505050506106e560018055565b60fe546040516302abf57960e61b815268141c9a58d95199595960ba1b6004820152600091829182916001600160a01b03169063aafd5e409060240160206040518083038186803b15801561134a57600080fd5b505afa15801561135e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061138291906130b3565b61010254604051635414ab0b60e11b81529192506001600160a01b0383169163a8295616916113b79160040190815260200190565b60206040518083038186803b1580156113cf57600080fd5b505afa1580156113e3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611407919061309a565b61010254604051637b1146eb60e11b81529194506001600160a01b0383169163f6228dd69161143c9160040190815260200190565b60206040518083038186803b15801561145457600080fd5b505afa158015611468573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061148c919061309a565b9150509091565b60ff546040516359f6849760e01b81523060048201526000918291829182916001600160a01b03909116906359f68497906024016101406040518083038186803b1580156114e057600080fd5b505afa1580156114f4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115189190612f75565b60a081015181516101015492935090916001600160801b031661154381670de0b6b3a76400006130ed565b83106115665761155682610c9760675490565b9760009750879650945050505050565b61158b838361157460675490565b61157c611a8d565b856001600160801b03166124b1565b9199909850909650945050505050565b6001600160a01b038116600090815260cb60205260408120546106e5565b60fe546040516302abf57960e61b81526c5661756c74526567697374727960981b60048201526000916001600160a01b03169063aafd5e409060240160206040518083038186803b15801561160d57600080fd5b505afa158015611621573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061164591906130b3565b9050336001600160a01b0382161461169f5760405162461bcd60e51b815260206004820152601d60248201527f53656e646572206d757374206265207661756c742072656769737472790000006044820152606401610419565b5060ff80546001600160a01b0319166001600160a01b0392909216919091179055565b6060606980546106fa90613065565b6000806116dc611b00565b905060006116ea82866118de565b90508381101561174a5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610419565b6117578286868403611f34565b506001949350505050565b60008061176d611b00565b905061079581858561217d565b834211156117ca5760405162461bcd60e51b815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606401610419565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886117f98c6125d8565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090506000611854826125fe565b905060006118648287878761264c565b9050896001600160a01b0316816001600160a01b0316146118c75760405162461bcd60e51b815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152606401610419565b6118d28a8a8a611f34565b50505050505050505050565b6001600160a01b03918216600090815260666020908152604080832093909416825291909152205490565b600081116119295760405162461bcd60e51b815260040161041990612f40565b6000611933611b00565b6101005490915061194f906001600160a01b03168230856123a3565b60ff546101005461196d916001600160a01b039182169116846123db565b60ff546040516328e32c8560e11b8152600481018490526001600160a01b03909116906351c6590a906024016040805180830381600087803b1580156119b257600080fd5b505af11580156119c6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119ea9190613105565b5050806001600160a01b03167f5d8bc849764969eb1bcc6d0a2f55999d0167c1ccec240a4f39cf664ca9c4148e83604051611a2791815260200190565b60405180910390a25050565b60026001541415611a865760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610419565b6002600155565b61010054600090611aa990600160a01b900460ff16601261315f565b610b1890600a613266565b60008215611acf57611aca8361111e8487613140565b611ad9565b670de0b6b3a76400005b949350505050565b6000670de0b6b3a7640000611af68385613140565b610b079190613015565b6000610b18612674565b6001600160a01b038216611b6a5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610419565b6001600160a01b03821660009081526065602052604090205481811015611bde5760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610419565b6001600160a01b03831660008181526065602090815260408083208686039055606780548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91015b60405180910390a35b505050565b60fe546040516302abf57960e61b815268141c9a58d95199595960ba1b6004820152600091829182916001600160a01b03169063aafd5e409060240160206040518083038186803b158015611c9457600080fd5b505afa158015611ca8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ccc91906130b3565b905060008460a00151611d5b5761010254604051635414ab0b60e11b815260048101919091526001600160a01b0383169063a82956169060240160206040518083038186803b158015611d1e57600080fd5b505afa158015611d32573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d56919061309a565b611dd8565b61010254604051637b1146eb60e11b815260048101919091526001600160a01b0383169063f6228dd69060240160206040518083038186803b158015611da057600080fd5b505afa158015611db4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dd8919061309a565b90508460a0015115611e75576000611dee611a8d565b90506000611e27670de0b6b3a76400008860800151611e0d9190613129565b61111e85858b60000151611e219190613140565b90611ae1565b905081611e6282848a60600151611e3e9190613140565b611e4891906130ed565b61111e858b60400151611e5b9190613140565b8590611ae1565b611e6c9190613015565b94505050611eb2565b611eaf8560000151611e21876060015161111e85611e21670de0b6b3a76400008c60800151611ea49190613129565b60408d01519061249c565b92505b828560200151611ec29190613129565b93505050915091565b6040516001600160a01b038316602482015260448101829052611c3b90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612696565b60018055565b6001600160a01b038316611f965760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610419565b6001600160a01b038216611ff75760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610419565b6001600160a01b0383811660008181526066602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259101611c32565b600054610100900460ff166120775760405162461bcd60e51b815260040161041990613275565b61207f612768565b565b600054610100900460ff166120a85760405162461bcd60e51b815260040161041990613275565b6120b2828261278f565b5050565b600054610100900460ff166120dd5760405162461bcd60e51b815260040161041990613275565b61210081604051806040016040528060018152602001603160f81b8152506127dd565b50565b600061210f84846118de565b90506000198114612177578181101561216a5760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610419565b6121778484848403611f34565b50505050565b6001600160a01b0383166121e15760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610419565b6001600160a01b0382166122435760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610419565b6001600160a01b038316600090815260656020526040902054818110156122bb5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610419565b6001600160a01b0380851660008181526065602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9061231b9086815260200190565b60405180910390a3612177565b6000610b187f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f61235760975490565b6098546040805160208101859052908101839052606081018290524660808201523060a082015260009060c0016040516020818303038152906040528051906020012090509392505050565b6040516001600160a01b03808516602483015283166044820152606481018290526121779085906323b872dd60e01b90608401611ef7565b604051636eb1769f60e11b81523060048201526001600160a01b038381166024830152600091839186169063dd62ed3e9060440160206040518083038186803b15801561242757600080fd5b505afa15801561243b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061245f919061309a565b61246991906130ed565b6040516001600160a01b03851660248201526044810182905290915061217790859063095ea7b360e01b90606401611ef7565b600081611af6670de0b6b3a764000085613140565b60008060006124c1878787611ab4565b925060006124e46124da670de0b6b3a76400008b613129565b61111e8a88611ae1565b90506124f08882613129565b91506124ff611e5b838361249c565b6125099085613129565b925050955095509592505050565b6001600160a01b03821661256d5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610419565b806067600082825461257f91906130ed565b90915550506001600160a01b0382166000818152606560209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b6001600160a01b038116600090815260cb60205260409020805460018101825590610c08565b60006106e561260b612328565b8360405161190160f01b6020820152602281018390526042810182905260009060620160405160208183030381529060405280519060200120905092915050565b600080600061265d8787878761281e565b9150915061266a816128e2565b5095945050505050565b600061267f33610b49565b15612691575060131936013560601c90565b503390565b60006126eb826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612a309092919063ffffffff16565b805190915015611c3b578080602001905181019061270991906132c0565b611c3b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610419565b600054610100900460ff16611f2e5760405162461bcd60e51b815260040161041990613275565b600054610100900460ff166127b65760405162461bcd60e51b815260040161041990613275565b81516127c9906068906020850190612b3b565b508051611c3b906069906020840190612b3b565b600054610100900460ff166128045760405162461bcd60e51b815260040161041990613275565b815160209283012081519190920120609791909155609855565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a083111561285557506000905060036128d9565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa1580156128a9573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166128d2576000600192509250506128d9565b9150600090505b94509492505050565b60008160048111156128f6576128f66132db565b14156128ff5750565b6001816004811115612913576129136132db565b14156129615760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401610419565b6002816004811115612975576129756132db565b14156129c35760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610419565b60038160048111156129d7576129d76132db565b14156121005760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401610419565b6060611ad9848460008585843b612a895760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610419565b600080866001600160a01b03168587604051612aa591906132f1565b60006040518083038185875af1925050503d8060008114612ae2576040519150601f19603f3d011682016040523d82523d6000602084013e612ae7565b606091505b5091509150612af7828286612b02565b979650505050505050565b60608315612b11575081610b07565b825115612b215782518084602001fd5b8160405162461bcd60e51b81526004016104199190612c45565b828054612b4790613065565b90600052602060002090601f016020900481019282612b695760008555612baf565b82601f10612b8257805160ff1916838001178555612baf565b82800160010185558215612baf579182015b82811115612baf578251825591602001919060010190612b94565b50612bbb929150612bbf565b5090565b5b80821115612bbb5760008155600101612bc0565b6001600160a01b038116811461210057600080fd5b60008060408385031215612bfc57600080fd5b823591506020830135612c0e81612bd4565b809150509250929050565b60005b83811015612c34578181015183820152602001612c1c565b838111156121775750506000910152565b6020815260008251806020840152612c64816040850160208701612c19565b601f01601f19169190910160400192915050565b60008060408385031215612c8b57600080fd5b8235612c9681612bd4565b946020939093013593505050565b634e487b7160e01b600052604160045260246000fd5b604051610140810167ffffffffffffffff81118282101715612cde57612cde612ca4565b60405290565b600082601f830112612cf557600080fd5b813567ffffffffffffffff80821115612d1057612d10612ca4565b604051601f8301601f19908116603f01168101908282118183101715612d3857612d38612ca4565b81604052838152866020858801011115612d5157600080fd5b836020870160208301376000602085830101528094505050505092915050565b600080600080600060a08688031215612d8957600080fd5b853567ffffffffffffffff80821115612da157600080fd5b612dad89838a01612ce4565b96506020880135915080821115612dc357600080fd5b50612dd088828901612ce4565b9450506040860135612de181612bd4565b925060608601356001600160801b0381168114612dfd57600080fd5b91506080860135612e0d81612bd4565b809150509295509295909350565b600080600060608486031215612e3057600080fd5b8335612e3b81612bd4565b92506020840135612e4b81612bd4565b929592945050506040919091013590565b600060208284031215612e6e57600080fd5b8135610b0781612bd4565b60ff8116811461210057600080fd5b600080600080600080600060e0888a031215612ea357600080fd5b8735612eae81612bd4565b96506020880135612ebe81612bd4565b955060408801359450606088013593506080880135612edc81612e79565b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215612f0c57600080fd5b8235612f1781612bd4565b91506020830135612c0e81612bd4565b600060208284031215612f3957600080fd5b5035919050565b6020808252600b908201526a16995c9bc8185b5bdd5b9d60aa1b604082015260600190565b80518015158114610c0a57600080fd5b60006101408284031215612f8857600080fd5b612f90612cba565b825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a082015260c083015160c082015260e083015160e0820152610100808401518183015250610120612ff4818501612f65565b908201529392505050565b634e487b7160e01b600052601160045260246000fd5b60008261303257634e487b7160e01b600052601260045260246000fd5b500490565b60008060006060848603121561304c57600080fd5b8351925060208401519150604084015190509250925092565b600181811c9082168061307957607f821691505b60208210811415610c0857634e487b7160e01b600052602260045260246000fd5b6000602082840312156130ac57600080fd5b5051919050565b6000602082840312156130c557600080fd5b8151610b0781612bd4565b6000602082840312156130e257600080fd5b8151610b0781612e79565b6000821982111561310057613100612fff565b500190565b6000806040838503121561311857600080fd5b505080516020909101519092909150565b60008282101561313b5761313b612fff565b500390565b600081600019048311821515161561315a5761315a612fff565b500290565b600060ff821660ff84168082101561317957613179612fff565b90039392505050565b600181815b808511156131bd5781600019048211156131a3576131a3612fff565b808516156131b057918102915b93841c9390800290613187565b509250929050565b6000826131d4575060016106e5565b816131e1575060006106e5565b81600181146131f757600281146132015761321d565b60019150506106e5565b60ff84111561321257613212612fff565b50506001821b6106e5565b5060208310610133831016604e8410600b8410161715613240575081810a6106e5565b61324a8383613182565b806000190482111561325e5761325e612fff565b029392505050565b6000610b0760ff8416836131c5565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b6000602082840312156132d257600080fd5b610b0782612f65565b634e487b7160e01b600052602160045260246000fd5b60008251613303818460208701612c19565b919091019291505056fea2646970667358221220f182585791bc5828a38fe9d989effd6abaf526499408e02d5798a285d6fafd8964736f6c63430008090033
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 34 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.