// 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 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
* ====
*
* [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 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) {
(bool success, bytes memory returndata) = target.delegatecall(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 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
pragma solidity 0.8.19;
/**
* @author DIVA protocol team.
* @title A protocol to create and settle derivative assets.
* @dev DIVA protocol is implemented using the Diamond Standard
* (EIP-2535: https://eips.ethereum.org/EIPS/eip-2535).
* Contract issues directionally reversed long and short positions
* (represented as ERC20 tokens) upon collateral deposit. Combined those
* assets represent a claim on the collateral held in the contract. If held
* in isolation, they expose the user to the up- or downside of the reference
* asset. Contract holds all the collateral backing all position tokens in
* existence.
* Users can withdraw collateral by i) submitting both short and long tokens
* in equal proportions or by redeeming them separately after the final
* reference asset value and hence the payout for long and short position
* tokens has been determined.
* Contract is the owner of all position tokens and hence the only account
* authorized to execute the `mint` and `burn` functions inside
* `PositionToken` contract.
*/
import {LibDiamond} from "./libraries/LibDiamond.sol";
import {LibDiamondStorage} from "./libraries/LibDiamondStorage.sol";
import {LibDIVAStorage} from "./libraries/LibDIVAStorage.sol";
import {LibEIP712} from "./libraries/LibEIP712.sol";
import {LibEIP712Storage} from "./libraries/LibEIP712Storage.sol";
import {IDiamondCut} from "./interfaces/IDiamondCut.sol";
import {IDiamondLoupe} from "./interfaces/IDiamondLoupe.sol";
import {IERC165} from "./interfaces/IERC165.sol";
// Thrown if no function exists for function called
error FunctionNotFound(bytes4 _functionSelector);
// Thrown if zero address is provided as ownershipContract
error ZeroOwnershipContractAddress();
// Thrown if zero address is provided as fallback data provider
error ZeroFallbackDataProviderAddress();
// Thrown if zero address is provided as the DiamondCutFacet
error ZeroDiamondCutFacetAddress();
// Thrown if zero address is provided as treasury
error ZeroTreasuryAddress();
// Thrown if zero address is provided as position token factory contract
error ZeroPositionTokenFactoryAddress();
contract Diamond {
/**
* @dev Deploy DiamondCutFacet before deploying the diamond
*/
constructor(
address _ownershipContract,
address _fallbackDataProvider,
address _diamondCutFacet,
address _treasury,
address _positionTokenFactory
) payable {
if (_ownershipContract == address(0)) revert ZeroOwnershipContractAddress();
if (_fallbackDataProvider == address(0)) revert ZeroFallbackDataProviderAddress();
if (_diamondCutFacet == address(0)) revert ZeroDiamondCutFacetAddress();
if (_treasury == address(0)) revert ZeroTreasuryAddress();
if (_positionTokenFactory == address(0)) revert ZeroPositionTokenFactoryAddress();
// Add the diamondCut external function from the diamondCutFacet
IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1);
bytes4[] memory functionSelectors = new bytes4[](1);
functionSelectors[0] = IDiamondCut.diamondCut.selector;
cut[0] = IDiamondCut.FacetCut({
facetAddress: _diamondCutFacet,
action: IDiamondCut.FacetCutAction.Add,
functionSelectors: functionSelectors
});
LibDiamond._diamondCut(cut, address(0), "");
// ************************************************************************
// Initialization of DIVA protocol variables (updateable by contract owner)
// ************************************************************************
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage
._diamondStorage();
LibDIVAStorage.GovernanceStorage storage gs = LibDIVAStorage
._governanceStorage();
LibDIVAStorage.PoolStorage storage ps = LibDIVAStorage
._poolStorage();
LibEIP712Storage.EIP712Storage storage es = LibEIP712Storage
._eip712Storage();
// Initialize fee parameters. Ensure that values are 0 or within the
// bandwidths specified in `_isValidFee`.
gs.fees.push(LibDIVAStorage.Fees({
startTime: block.timestamp,
protocolFee: 2500000000000000, // 0.25%
settlementFee: 500000000000000 // 0.05%
}));
// Initialize settlement period parameters. Ensure that values are between
// 3 and 15 days (as specified in `_isValidPeriod`).
gs.settlementPeriods.push(LibDIVAStorage.SettlementPeriods({
startTime: block.timestamp,
submissionPeriod: 7 days,
challengePeriod: 3 days,
reviewPeriod: 5 days,
fallbackSubmissionPeriod: 10 days
}));
// Initialize treasury and fallback data provider address.
// `previousFallbackDataProvider` and `previousTreasury` are initialized to
// zero address at contract deployment.
gs.startTimeTreasury = block.timestamp;
gs.treasury = _treasury;
gs.startTimeFallbackDataProvider = block.timestamp;
gs.fallbackDataProvider = _fallbackDataProvider;
// Store positionTokenFactory address
ps.positionTokenFactory = _positionTokenFactory;
// Initialize EIP712 domain separator and store chain id to protect against replay attacks
// in case of a fork. This approach is inspired by openzeppelin's EIP712 implementation:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/EIP712.sol
// Note that the address(this) check was consciously removed as not deemed relevant for our case.
es.EIP712_DOMAIN_SEPARATOR = LibEIP712._getDomainHash();
es.CACHED_CHAIN_ID = LibEIP712._chainId();
// Set owner contract address
ds.ownershipContract = _ownershipContract;
// Adding ERC165 data
ds.supportedInterfaces[type(IDiamondLoupe).interfaceId] = true;
ds.supportedInterfaces[type(IERC165).interfaceId] = true;
}
// Find facet for function that is called and execute the
// function if a facet is found and return any value.
fallback() external payable {
address facet = LibDiamondStorage._diamondStorage()
.selectorToFacetAndPosition[msg.sig].facetAddress;
if (facet == address(0)) revert FunctionNotFound(msg.sig);
assembly {
// copy incoming call data
calldatacopy(0, 0, calldatasize())
// forward call to logic contract (facet)
let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
// retrieve return data
returndatacopy(0, 0, returndatasize())
// forward return data back to caller
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.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 ECDSA {
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", Strings.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: agpl-3.0
pragma solidity 0.8.19;
interface IDiamondCut {
enum FacetCutAction {
Add,
Replace,
Remove
}
// Add=0, Replace=1, Remove=2
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
// Duplication of event defined in `LibDiamond.sol` as events emitted out of
// library functions are not reflected in the contract ABI. Read more about it here:
// https://web.archive.org/web/20180922101404/https://blog.aragon.org/library-driven-development-in-solidity-2bebcaf88736/
event DiamondCut(FacetCut[] _facetCut, address _init, bytes _calldata);
/// @notice Add/replace/remove any number of functions and optionally
/// execute a function with delegatecall
/// @param _facetCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _facetCut,
address _init,
bytes calldata _calldata
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;
interface IERC165 {
/**
* @notice Query if a contract implements an interface.
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
* @param interfaceId The interface identifier, as specified in ERC-165.
* @return `true` if the contract implements `interfaceID` and
* `interfaceID` is not 0xffffffff, `false` otherwise.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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: agpl-3.0
pragma solidity 0.8.19;
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/**
* @notice Position token contract
* @dev The `PositionToken` contract inherits from ERC20 contract and stores
* the Id of the pool that the position token is linked to. It implements a
* `mint` and a `burn` function which can only be called by the `PositionToken`
* contract owner.
*
* Two `PositionToken` contracts are deployed during pool creation process
* (`createContingentPool`) with Diamond contract being set as the owner.
* The `mint` function is used during pool creation (`createContingentPool`)
* and addition of liquidity (`addLiquidity`). Position tokens are burnt
* during token redemption (`redeemPositionToken`) and removal of liquidity
* (`removeLiquidity`). The address of the position tokens is stored in the
* pool parameters within Diamond contract and used to verify the tokens that
* a user sends back to withdraw collateral.
*
* Position tokens have the same number of decimals as the underlying
* collateral token.
*/
interface IPositionToken is IERC20Upgradeable {
/**
* @notice Function to initialize the position token instance
*/
function initialize(
string memory symbol_, // name is set equal to symbol
bytes32 poolId_,
uint8 decimals_,
address owner_
) external;
/**
* @notice Function to mint ERC20 position tokens.
* @dev Called during `createContingentPool` and `addLiquidity`.
* Can only be called by the owner of the position token which
* is the Diamond contract in the context of DIVA.
* @param _recipient The account receiving the position tokens.
* @param _amount The number of position tokens to mint.
*/
function mint(address _recipient, uint256 _amount) external;
/**
* @notice Function to burn position tokens.
* @dev Called within `redeemPositionToken` and `removeLiquidity`.
* Can only be called by the owner of the position token which
* is the Diamond contract in the context of DIVA.
* @param _redeemer Address redeeming positions tokens in return for
* collateral.
* @param _amount The number of position tokens to burn.
*/
function burn(address _redeemer, uint256 _amount) external;
/**
* @notice Returns the Id of the contingent pool that the position token is
* linked to in the context of DIVA.
* @return The poolId.
*/
function poolId() external view returns (bytes32);
/**
* @notice Returns the owner of the position token (Diamond contract in the
* context of DIVA).
* @return The address of the position token owner.
*/
function owner() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;
interface IPositionTokenFactory {
/**
* @notice Creates a clone of the permissionless position token contract.
* @param _symbol Symbol string of the position token. Name is set equal to symbol.
* @param _poolId The Id of the contingent pool that the position token belongs to.
* @param _decimals Decimals of position token (same as collateral token).
* @param _owner Owner of the position token. Should always be DIVA Protocol address.
* @param _permissionedERC721Token Address of permissioned ERC721 token.
* @return clone Returns the address of the clone contract.
*/
function createPositionToken(
string memory _symbol,
bytes32 _poolId,
uint8 _decimals,
address _owner,
address _permissionedERC721Token
) external returns (address clone);
/**
* @notice Address where the position token implementation contract is stored.
* @dev This is needed since we are using a clone proxy.
* @return The implementation address.
*/
function positionTokenImplementation() external view returns (address);
/**
* @notice Address where the permissioned position token implementation contract
* is stored.
* @dev This is needed since we are using a clone proxy.
* @return The implementation address.
*/
function permissionedPositionTokenImplementation() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {PositionToken} from "../PositionToken.sol";
import {IPositionToken} from "../interfaces/IPositionToken.sol";
import {IPositionTokenFactory} from "../interfaces/IPositionTokenFactory.sol";
import {SafeDecimalMath} from "./SafeDecimalMath.sol";
import {LibDIVAStorage} from "./LibDIVAStorage.sol";
// Thrown in `addLiquidity`, `fillOfferAddLiquidity`, `removeLiquidity`,
// and `fillOfferRemoveLiquidity` if pool doesn't exist
error NonExistentPool();
// Thrown in `removeLiquidity` or `redeemPositionToken` if collateral amount
// to be returned to user during exceeds the pool's collateral balance
error AmountExceedsPoolCollateralBalance();
// Thrown in `removeLiquidity` if the fee amount to be allocated exceeds the
// pool's current collateral balance
error FeeAmountExceedsPoolCollateralBalance();
// Thrown in `addLiquidity` if the pool is already expired
error PoolExpired();
// Thrown in `createContingentPool` if the input parameters are invalid
error InvalidInputParamsCreateContingentPool();
// Thrown in `createContingentPool` and `addLiquidity` if the collateral token
// implements a fee
error FeeTokensNotSupported();
// Thrown in `addLiquidity` if adding additional collateral would
// result in the pool capacity being exceeded
error PoolCapacityExceeded();
// Thrown in `removeLiquidity` if return collateral is paused
error ReturnCollateralPaused();
// Thrown in `removeLiquidity` if status of `finalReferenceValue`
// is already "Confirmed"
error FinalValueAlreadyConfirmed();
// Thrown in `removeLiquidity` if a user's short or long position
// token balance is smaller than the indicated amount
error InsufficientShortOrLongBalance();
// Thrown in `removeLiquidity` if `_amount` provided by user results
// in a zero protocol fee amount; user should increase their `_amount`
error ZeroProtocolFee();
// Thrown in `removeLiquidity` if `_amount` provided by user results
// in zero settlement fee amount; user should increase `_amount`
error ZeroSettlementFee();
library LibDIVA {
using SafeDecimalMath for uint256;
using SafeERC20 for IERC20Metadata;
// Argument for `createContingentPool` function
struct PoolParams {
string referenceAsset;
uint96 expiryTime;
uint256 floor;
uint256 inflection;
uint256 cap;
uint256 gradient;
uint256 collateralAmount;
address collateralToken;
address dataProvider;
uint256 capacity;
address longRecipient;
address shortRecipient;
address permissionedERC721Token;
}
// Argument for `_createContingentPoolLib` function
struct CreatePoolParams {
PoolParams poolParams;
uint256 collateralAmountMsgSender;
uint256 collateralAmountMaker;
address maker;
}
// Argument for `_addLiquidityLib` to avoid stack-too-deep error
struct AddLiquidityParams {
bytes32 poolId;
uint256 collateralAmountMsgSender;
uint256 collateralAmountMaker;
address maker;
address longRecipient;
address shortRecipient;
}
// Argument for `_removeLiquidityLib` to avoid stack-too-deep error
struct RemoveLiquidityParams {
bytes32 poolId;
uint256 amount;
address longTokenHolder;
address shortTokenHolder;
}
/**
* @notice Emitted when fees are allocated.
* @dev Collateral token can be looked up via the `getPoolParameters`
* function using the emitted `poolId`.
* @param poolId The Id of the pool that the fee applies to.
* @param recipient Address that is allocated the fees.
* @param amount Fee amount allocated.
*/
event FeeClaimAllocated(
bytes32 indexed poolId,
address indexed recipient,
uint256 amount
);
/**
* @notice Emitted when fees are reserved for data provider in
* `removeLiquidity`.
* @dev Collateral token can be looked up via the `getPoolParameters`
* function using the emitted `poolId`.
* @param poolId The Id of the pool that the fee applies to.
* @param amount Fee amount reserved.
*/
event FeeClaimReserved(
bytes32 indexed poolId,
uint256 amount
);
/**
* @notice Emitted when a new pool is created.
* @param poolId The Id of the newly created contingent pool.
* @param longRecipient The address that received the long position tokens.
* @param shortRecipient The address that received the short position tokens.
* @param collateralAmount The collateral amount deposited into the pool.
* @param permissionedERC721Token Address of ERC721 token that the transfer
* restrictions apply to.
*/
event PoolIssued(
bytes32 indexed poolId,
address indexed longRecipient,
address indexed shortRecipient,
uint256 collateralAmount,
address permissionedERC721Token
);
/**
* @notice Emitted when new collateral is added to an existing pool.
* @param poolId The Id of the pool that collateral was added to.
* @param longRecipient The address that received the long position token.
* @param shortRecipient The address that received the short position token.
* @param collateralAmount The collateral amount added.
*/
event LiquidityAdded(
bytes32 indexed poolId,
address indexed longRecipient,
address indexed shortRecipient,
uint256 collateralAmount
);
/**
* @notice Emitted when collateral is removed from an existing pool.
* @param poolId The Id of the pool that collateral was removed from.
* @param longTokenHolder The address of the user that contributed the long token.
* @param shortTokenHolder The address of the user that contributed the short token.
* @param collateralAmount The collateral amount removed from the pool.
*/
event LiquidityRemoved(
bytes32 indexed poolId,
address indexed longTokenHolder,
address indexed shortTokenHolder,
uint256 collateralAmount
);
/**
* @notice Emitted when tips and reserved fees (the "reserve") have been allocated to the
* data provider after the final value has been confirmed.
* @param poolId Id of the pool for which the reserve has been allocated
* @param recipient Address of the reserve recipient, typically the data provider
* @param amount Reserve amount allocated (in collateral token)
*/
event ReservedClaimAllocated(
bytes32 indexed poolId,
address indexed recipient,
uint256 amount
);
uint256 private constant ADDRESS_MASK = (1 << 160) - 1;
uint256 private constant UINT_96_MASK = (1 << 96) - 1;
function _poolParameters(bytes32 _poolId)
internal
view
returns (LibDIVAStorage.Pool memory)
{
return LibDIVAStorage._poolStorage().pools[_poolId];
}
function _getPoolCount() internal view returns (uint256) {
return LibDIVAStorage._poolStorage().nonce;
}
function _getClaim(address _collateralToken, address _recipient)
internal
view
returns (uint256)
{
return
LibDIVAStorage._feeClaimStorage().claimableFeeAmount[
_collateralToken
][_recipient];
}
function _getReservedClaim(bytes32 _poolId) internal view returns (uint256) {
return LibDIVAStorage._feeClaimStorage().poolIdToReservedClaim[_poolId];
}
/**
* @dev Internal function to transfer the collateral to the user.
* Openzeppelin's `safeTransfer` method is used to handle different
* implementations of the ERC20 standard.
* @param _pool Pool struct.
* @param _receiver Recipient address.
* @param _amount Collateral amount to return.
*/
function _returnCollateral(
LibDIVAStorage.Pool storage _pool,
address _receiver,
uint256 _amount
) internal {
IERC20Metadata collateralToken = IERC20Metadata(_pool.collateralToken);
// That case shouldn't happen, but if it happens unexpectedly, then
// it will throw here.
if (_amount > _pool.collateralBalance)
revert AmountExceedsPoolCollateralBalance();
_pool.collateralBalance -= _amount;
collateralToken.safeTransfer(_receiver, _amount);
}
/**
* @notice Internal function to calculate the payoff per long and short token,
* net of fees, and store it in `payoutLong` and `payoutShort` inside pool
* parameters.
* @dev Called inside `redeemPositionToken` and `setFinalReferenceValue`
* functions after status of final reference value has been confirmed.
* @param _pool Pool struct.
* @param _fees Fees struct.
* @param _collateralTokenDecimals Collateral token decimals. Passed as
* argument to avoid reading from storage again.
*/
function _setPayoutAmount(
LibDIVAStorage.Pool storage _pool,
LibDIVAStorage.Fees memory _fees,
uint8 _collateralTokenDecimals
) internal {
// Calculate payoff per short and long token. Output is in collateral
// token decimals.
(_pool.payoutShort, _pool.payoutLong) = _calcPayoffs(
_pool.floor,
_pool.inflection,
_pool.cap,
_pool.gradient,
_pool.finalReferenceValue,
_collateralTokenDecimals,
_fees.protocolFee + _fees.settlementFee
);
}
/**
* @notice Internal function used within `setFinalReferenceValue` and
* `redeemPositionToken` to calculate and allocate fee claims to recipient
* (DIVA Treasury or data provider). Fee is applied to the overall
* collateral remaining in the pool and allocated in full the first time
* the respective function is triggered.
* @dev Fees can be claimed via the `claimFee` function.
* @param _poolId Pool Id.
* @param _pool Pool struct.
* @param _fee Percentage fee expressed as an integer with 18 decimals
* @param _recipient Fee recipient address.
* @param _collateralBalance Current pool collateral balance expressed as
* an integer with collateral token decimals.
* @param _collateralTokenDecimals Collateral token decimals.
*/
function _calcAndAllocateFeeClaim(
bytes32 _poolId,
LibDIVAStorage.Pool storage _pool,
uint96 _fee,
address _recipient,
uint256 _collateralBalance,
uint8 _collateralTokenDecimals
) internal {
uint256 _feeAmount = _calcFee(
_fee,
_collateralBalance,
_collateralTokenDecimals
);
_allocateFeeClaim(_poolId, _pool, _recipient, _feeAmount);
}
/**
* @notice Internal function to allocate fees to `recipient`.
* @dev The balance of the recipient is tracked inside the contract and
* can be claimed via `claimFee` function.
* @param _poolId Pool Id that the fee applies to.
* @param _pool Pool struct.
* @param _recipient Address of the fee recipient.
* @param _feeAmount Total fee amount expressed as an integer with
* collateral token decimals.
*/
function _allocateFeeClaim(
bytes32 _poolId,
LibDIVAStorage.Pool storage _pool,
address _recipient,
uint256 _feeAmount
) internal {
// Check that fee amount to be allocated doesn't exceed the pool's
// current `collateralBalance`. This check should never trigger, but
// kept for safety.
if (_feeAmount > _pool.collateralBalance)
revert FeeAmountExceedsPoolCollateralBalance();
// Reduce `collateralBalance` in pool parameters and increase fee claim
_pool.collateralBalance -= _feeAmount;
LibDIVAStorage._feeClaimStorage()
.claimableFeeAmount[_pool.collateralToken][_recipient] += _feeAmount;
// Log poolId, recipient and fee amount
emit FeeClaimAllocated(_poolId, _recipient, _feeAmount);
}
/**
* @notice Internal function to reserve settlement fees accrued during `removeLiquidity`
* for data provider. The function is very similar to `_allocateFeeClaim`.
* @dev The fee will be allocated to the actual data provider, which may be
* either the assigned data provider or the fallback data provider, once the final value
* has been confirmed. If neither of them reports a value, the reserved fee will be
* allocated to the treasury.
* @param _poolId Pool Id that the fee applies to.
* @param _pool Pool struct.
* @param _feeAmount Total fee amount expressed as an integer with
* collateral token decimals.
*/
function _reserveFeeClaim(
bytes32 _poolId,
LibDIVAStorage.Pool storage _pool,
uint256 _feeAmount
) internal {
// Check that fee amount to be reserved doesn't exceed the pool's
// current `collateralBalance`. This check should never trigger, but
// kept for safety.
if (_feeAmount > _pool.collateralBalance)
revert FeeAmountExceedsPoolCollateralBalance();
// Reduce `collateralBalance` in pool parameters and increase
// fee claim reserve
_pool.collateralBalance -= _feeAmount;
LibDIVAStorage._feeClaimStorage()
.poolIdToReservedClaim[_poolId] += _feeAmount;
// Log poolId and fee amount
emit FeeClaimReserved(_poolId, _feeAmount);
}
/**
* @notice Internal function to transfer the reserved fee and tip to the data provider when the
* final reference value is confirmed.
* @dev `poolIdToReservedClaim` is set to zero and credited to the claimable fee amount.
* @param _poolId Id of pool.
* @param _recipient Reserve recipient.
*/
function _allocateReservedClaim(bytes32 _poolId, address _recipient) internal {
// Get reference to relevant storage slot
LibDIVAStorage.FeeClaimStorage storage fs = LibDIVAStorage._feeClaimStorage();
// Initialize Pool struct
LibDIVAStorage.Pool storage _pool = LibDIVAStorage._poolStorage().pools[_poolId];
// Get reserve for pool
uint256 _reserve = fs.poolIdToReservedClaim[_poolId];
// Credit reserve to the claimable fee amount
fs.poolIdToReservedClaim[_poolId] = 0;
fs.claimableFeeAmount[_pool.collateralToken][_recipient] += _reserve;
// Log event
emit ReservedClaimAllocated(_poolId, _recipient, _reserve);
}
/**
* @notice Function to calculate the fee amount for a given collateral amount.
* @dev Output is an integer expressed with collateral token decimals.
* As fee parameter has 18 decimals but collateral tokens may have
* less, scaling needs to be applied when using `SafeDecimalMath` library.
* @param _fee Percentage fee expressed as an integer with 18 decimals
* (e.g., 0.25% is 2500000000000000).
* @param _collateralAmount Collateral amount that is used as the basis for
* the fee calculation expressed as an integer with collateral token decimals.
* @param _collateralTokenDecimals Collateral token decimals.
* @return The fee amount expressed as an integer with collateral token decimals.
*/
function _calcFee(
uint96 _fee,
uint256 _collateralAmount,
uint8 _collateralTokenDecimals
) internal pure returns (uint256) {
uint256 _SCALINGFACTOR;
unchecked {
// Cannot over-/underflow as collateral token decimals are restricted to
// a minimum of 6 and a maximum of 18.
_SCALINGFACTOR = uint256(10**(18 - _collateralTokenDecimals));
}
uint256 _feeAmount = uint256(_fee).multiplyDecimal(
_collateralAmount * _SCALINGFACTOR
) / _SCALINGFACTOR;
return _feeAmount;
}
/**
* @notice Function to calculate the payoffs per long and short token,
* net of fees.
* @dev Scaling applied during calculations to handle different decimals.
* @param _floor Value of underlying at or below which the short token
* will pay out the max amount and the long token zero. Expressed as an
* integer with 18 decimals.
* @param _inflection Value of underlying at which the long token will
* payout out `_gradient` and the short token `1-_gradient`. Expressed
* as an integer with 18 decimals.
* @param _cap Value of underlying at or above which the long token will
* pay out the max amount and short token zero. Expressed as an integer
* with 18 decimals.
* @param _gradient Long token payout at inflection (0 <= _gradient <= 1).
* Expressed as an integer with collateral token decimals.
* @param _finalReferenceValue Final value submitted by data provider
* expressed as an integer with 18 decimals.
* @param _collateralTokenDecimals Collateral token decimals.
* @param _fee Fee in percent expressed as an integer with 18 decimals.
* @return payoffShortNet Payoff per short token (net of fees) expressed
* as an integer with collateral token decimals.
* @return payoffLongNet Payoff per long token (net of fees) expressed
* as an integer with collateral token decimals.
*/
function _calcPayoffs(
uint256 _floor,
uint256 _inflection,
uint256 _cap,
uint256 _gradient,
uint256 _finalReferenceValue,
uint256 _collateralTokenDecimals,
uint96 _fee // max value: 1.5% <= 2^96
) internal pure returns (uint96 payoffShortNet, uint96 payoffLongNet) {
uint256 _SCALINGFACTOR;
unchecked {
// Cannot over-/underflow as collateral token decimals are restricted to
// a minimum of 6 and a maximum of 18.
_SCALINGFACTOR = uint256(10**(18 - _collateralTokenDecimals));
}
uint256 _UNIT = SafeDecimalMath.UNIT;
uint256 _payoffLong;
uint256 _payoffShort;
// Note: _gradient * _SCALINGFACTOR not cached for calculations
// as it would result in a stack-too-deep error
if (_finalReferenceValue == _inflection) {
_payoffLong = _gradient * _SCALINGFACTOR;
} else if (_finalReferenceValue <= _floor) {
_payoffLong = 0;
} else if (_finalReferenceValue >= _cap) {
_payoffLong = _UNIT;
} else if (_finalReferenceValue < _inflection) {
_payoffLong = (
(_gradient * _SCALINGFACTOR).multiplyDecimal(
_finalReferenceValue - _floor
)
).divideDecimal(_inflection - _floor);
} else {
// Case: cap > _finalReferenceValue > _inflection
_payoffLong =
_gradient *
_SCALINGFACTOR +
(
(_UNIT - _gradient * _SCALINGFACTOR).multiplyDecimal(
_finalReferenceValue - _inflection
)
).divideDecimal(_cap - _inflection);
}
unchecked {
// Underflow not possible: as 0 <= _payoffLong <= _UNIT
_payoffShort = _UNIT - _payoffLong;
payoffShortNet = uint96(
_payoffShort.multiplyDecimal(_UNIT - _fee) / _SCALINGFACTOR
);
payoffLongNet = uint96(
_payoffLong.multiplyDecimal(_UNIT - _fee) / _SCALINGFACTOR
);
}
return (payoffShortNet, payoffLongNet); // collateral token decimals
}
function _createContingentPoolLib(CreatePoolParams memory _createPoolParams)
internal
returns (bytes32)
{
// Get reference to relevant storage slots
LibDIVAStorage.PoolStorage storage ps = LibDIVAStorage._poolStorage();
LibDIVAStorage.GovernanceStorage storage gs = LibDIVAStorage
._governanceStorage();
// Create reference to collateral token corresponding to the provided pool Id
IERC20Metadata collateralToken = IERC20Metadata(
_createPoolParams.poolParams.collateralToken
);
uint8 _collateralTokenDecimals = collateralToken.decimals();
// Check validity of input parameters
if (
!_validateInputParamsCreateContingentPool(
_createPoolParams.poolParams,
_collateralTokenDecimals
)
) revert InvalidInputParamsCreateContingentPool();
// Increment internal `nonce` every time a new pool is created. Index
// starts at 1. No overflow risk when using compiler version >= 0.8.0.
++ps.nonce;
// Calculate `poolId` as the hash of pool params, msg.sender and nonce.
// This is to protect users from malicious pools in the event of chain reorgs.
bytes32 _poolId = _getPoolId(_createPoolParams, ps);
// Transfer approved collateral tokens from `msg.sender` to `this`. Note that
// the transfer will revert for fee tokens.
// Block scoping applied to avoid stack-too-deep error.
{
uint256 _before = collateralToken.balanceOf(address(this));
collateralToken.safeTransferFrom(
msg.sender,
address(this),
_createPoolParams.collateralAmountMsgSender
);
// Transfer approved collateral tokens from maker. Applies only for `fillOfferCreateContingentPool`
// when makerFillAmount > 0. Requires prior approval from `maker` to execute this transaction.
if (_createPoolParams.collateralAmountMaker != 0) {
collateralToken.safeTransferFrom(
_createPoolParams.maker,
address(this),
_createPoolParams.collateralAmountMaker
);
}
uint256 _after = collateralToken.balanceOf(address(this));
// Revert if a fee was applied during transfer. Throws if `_before > _after`.
if (_after - _before != _createPoolParams.collateralAmountMsgSender + _createPoolParams.collateralAmountMaker) {
revert FeeTokensNotSupported();
}
}
// Deploy two `PositionToken` contract clones, one that represents shares in the short
// and one that represents shares in the long position.
// Naming convention for short/long token: S13/L13 where 13 is the nonce.
// Diamond contract (address(this) due to delegatecall) is set as the
// owner of the position tokens and is the only account that is
// authorized to call the `mint` and `burn` function therein.
// Note that position tokens have same number of decimals as collateral token.
address _shortToken = IPositionTokenFactory(ps.positionTokenFactory)
.createPositionToken(
string(abi.encodePacked("S", Strings.toString(ps.nonce))), // name is equal to symbol
_poolId,
_collateralTokenDecimals,
address(this),
_createPoolParams.poolParams.permissionedERC721Token
);
address _longToken = IPositionTokenFactory(ps.positionTokenFactory)
.createPositionToken(
string(abi.encodePacked("L", Strings.toString(ps.nonce))), // name is equal to symbol
_poolId,
_collateralTokenDecimals,
address(this),
_createPoolParams.poolParams.permissionedERC721Token
);
(uint48 _indexFees, ) = _getCurrentFees(gs);
(uint48 _indexSettlementPeriods, ) = _getCurrentSettlementPeriods(gs);
// Store `Pool` struct in `pools` mapping for the newly generated `poolId`
ps.pools[_poolId] = LibDIVAStorage.Pool(
_createPoolParams.poolParams.floor,
_createPoolParams.poolParams.inflection,
_createPoolParams.poolParams.cap,
_createPoolParams.poolParams.gradient,
_createPoolParams.poolParams.collateralAmount,
0, // finalReferenceValue
_createPoolParams.poolParams.capacity,
block.timestamp,
_shortToken,
0, // payoutShort
_longToken,
0, // payoutLong
_createPoolParams.poolParams.collateralToken,
_createPoolParams.poolParams.expiryTime,
address(_createPoolParams.poolParams.dataProvider),
_indexFees,
_indexSettlementPeriods,
LibDIVAStorage.Status.Open,
_createPoolParams.poolParams.referenceAsset
);
// Number of position tokens is set equal to the total collateral to
// standardize the max payout at 1.0. Position tokens are sent to the recipients
// provided as part of the input parameters.
IPositionToken(_shortToken).mint(
_createPoolParams.poolParams.shortRecipient,
_createPoolParams.poolParams.collateralAmount
);
IPositionToken(_longToken).mint(
_createPoolParams.poolParams.longRecipient,
_createPoolParams.poolParams.collateralAmount
);
// Log pool creation
emit PoolIssued(
_poolId,
_createPoolParams.poolParams.longRecipient,
_createPoolParams.poolParams.shortRecipient,
_createPoolParams.poolParams.collateralAmount,
_createPoolParams.poolParams.permissionedERC721Token
);
return _poolId;
}
// Return `poolId` which is the hash of create pool parameters, msg.sender and nonce.
// This is to protect users from depositing into malicious pools in case of chain reorgs.
function _getPoolId(
CreatePoolParams memory _createPoolParams,
LibDIVAStorage.PoolStorage storage _ps
) private view returns (bytes32 poolId) {
// Assembly for more efficient computing:
// bytes32 _poolId = keccak256(
// abi.encode(
// keccak256(bytes(_createPoolParams.poolParams.referenceAsset)),
// _createPoolParams.poolParams.expiryTime,
// _createPoolParams.poolParams.floor,
// _createPoolParams.poolParams.inflection,
// _createPoolParams.poolParams.cap,
// _createPoolParams.poolParams.gradient,
// _createPoolParams.poolParams.collateralAmount,
// _createPoolParams.poolParams.collateralToken,
// _createPoolParams.poolParams.dataProvider,
// _createPoolParams.poolParams.capacity,
// _createPoolParams.poolParams.longRecipient,
// _createPoolParams.poolParams.shortRecipient,
// _createPoolParams.poolParams.permissionedERC721Token,
// _createPoolParams.collateralAmountMsgSender,
// _createPoolParams.collateralAmountMaker,
// _createPoolParams.maker,
// msg.sender,
// ps.nonce
// )
// );
assembly {
let mem := mload(0x40)
// _createPoolParams.poolParams.referenceAsset;
// Get memory pointer where the `poolParams` struct information is stored.
let poolParams := mload(_createPoolParams)
// At the `poolParams` location, get the memory pointer where the length
// of the `referenceAsset` string is stored.
let referenceAsset := mload(poolParams)
// Store the hash of the string at position `mem`. `mload(referenceAsset)` is
// the string length, `add(referenceAsset, 0x20)` is the location where the
// actual string starts.
mstore(
mem,
keccak256(add(referenceAsset, 0x20), mload(referenceAsset))
)
// _createPoolParams.poolParams.expiryTime;
mstore(
add(mem, 0x20),
and(UINT_96_MASK, mload(add(poolParams, 0x20)))
)
// _createPoolParams.poolParams.floor;
mstore(add(mem, 0x40), mload(add(poolParams, 0x40)))
// _createPoolParams.poolParams.inflection;
mstore(add(mem, 0x60), mload(add(poolParams, 0x60)))
// _createPoolParams.poolParams.cap;
mstore(add(mem, 0x80), mload(add(poolParams, 0x80)))
// _createPoolParams.poolParams.gradient;
mstore(add(mem, 0xA0), mload(add(poolParams, 0xA0)))
// _createPoolParams.poolParams.collateralAmount;
mstore(add(mem, 0xC0), mload(add(poolParams, 0xC0)))
// _createPoolParams.poolParams.collateralToken;
mstore(add(mem, 0xE0),
and(ADDRESS_MASK, mload(add(poolParams, 0xE0)))
)
// _createPoolParams.poolParams.dataProvider;
mstore(add(mem, 0x100),
and(ADDRESS_MASK, mload(add(poolParams, 0x100)))
)
// _createPoolParams.poolParams.capacity;
mstore(add(mem, 0x120), mload(add(poolParams, 0x120)))
// _createPoolParams.poolParams.longRecipient;
mstore(add(mem, 0x140),
and(ADDRESS_MASK, mload(add(poolParams, 0x140)))
)
// _createPoolParams.poolParams.shortRecipient;
mstore(add(mem, 0x160),
and(ADDRESS_MASK, mload(add(poolParams, 0x160)))
)
// _createPoolParams.poolParams.permissionedERC721Token;
mstore(add(mem, 0x180),
and(ADDRESS_MASK, mload(add(poolParams, 0x180)))
)
// _createPoolParams.collateralAmountMsgSender;
mstore(add(mem, 0x1A0), mload(add(_createPoolParams, 0x20))) // First slot after poolParams struct reference
// _createPoolParams.collateralAmountMaker;
mstore(add(mem, 0x1C0), mload(add(_createPoolParams, 0x40)))
// _createPoolParams.maker;
mstore(add(mem, 0x1E0),
and(ADDRESS_MASK, mload(add(_createPoolParams, 0x60)))
)
// msg.sender;
mstore(add(mem, 0x200), and(ADDRESS_MASK, caller()))
// ps.nonce
// IMPORTANT: Assumes `nonce` to be at position zero inside `PoolStorage` struct
mstore(add(mem, 0x220), sload(_ps.slot))
poolId := keccak256(mem, 0x240)
}
}
function _validateInputParamsCreateContingentPool(
PoolParams memory _poolParams,
uint8 _collateralTokenDecimals
) internal view returns (bool) {
// Expiry time should not be equal to or smaller than `block.timestamp`
if (_poolParams.expiryTime <= block.timestamp) {
return false;
}
// Reference asset should not be empty string
if (bytes(_poolParams.referenceAsset).length == 0) {
return false;
}
// Floor should not be greater than inflection
if (_poolParams.floor > _poolParams.inflection) {
return false;
}
// Cap should not be smaller than inflection
if (_poolParams.cap < _poolParams.inflection) {
return false;
}
// Cap should not exceed 1e59 to prevent overflow in
// `LibDIVA._calcPayoffs` in the scenario
// `cap > finalReferenceValue > inflection`
if (_poolParams.cap > 1e59) {
return false;
}
// Data provider should not be zero address
if (_poolParams.dataProvider == address(0)) {
return false;
}
// Gradient should not be greater than 1 (integer in collateral token decimals)
if (_poolParams.gradient > uint256(10**_collateralTokenDecimals)) {
return false;
}
// Collateral amount should not be greater than pool capacity
if (_poolParams.collateralAmount > _poolParams.capacity) {
return false;
}
// Collateral token should not have decimals larger than 18 or smaller than 6
if ((_collateralTokenDecimals > 18) || (_collateralTokenDecimals < 6)) {
return false;
}
return true;
}
// Function to transfer collateral from msg.sender/maker to `this` and mint position token
function _addLiquidityLib(AddLiquidityParams memory addLiquidityParams)
internal
{
// Initialize Pool struct
LibDIVAStorage.Pool storage _pool =
LibDIVAStorage._poolStorage().pools[addLiquidityParams.poolId];
// Check if pool exists
if (!_poolExists(_pool)) revert NonExistentPool();
// Check that pool has not expired yet
if (block.timestamp >= _pool.expiryTime) revert PoolExpired();
// Check that new total pool collateral does not exceed the maximum
// capacity of the pool
if ((_pool.collateralBalance + addLiquidityParams.collateralAmountMsgSender + addLiquidityParams.collateralAmountMaker) > _pool.capacity)
revert PoolCapacityExceeded();
// Connect to collateral token contract of the given pool Id
IERC20Metadata collateralToken = IERC20Metadata(_pool.collateralToken);
uint256 _collateralAmountIncr = addLiquidityParams
.collateralAmountMsgSender +
addLiquidityParams.collateralAmountMaker;
// Transfer approved collateral tokens from `msg.sender` (taker in `fillOfferAddLiquidity`) to `this`.
// Requires prior approval from `msg.sender` to execute this transaction. Note that
// the transfer will revert for fee tokens.
// Block scoping applied to avoid stack-too-deep error.
{
uint256 _before = collateralToken.balanceOf(address(this));
collateralToken.safeTransferFrom(
msg.sender,
address(this),
addLiquidityParams.collateralAmountMsgSender
);
// Transfer approved collateral tokens from maker. Applies only for `fillOfferAddLiquidity`
// when makerFillAmount > 0. Requires prior approval from `maker` to execute this transaction.
if (addLiquidityParams.collateralAmountMaker != 0) {
collateralToken.safeTransferFrom(
addLiquidityParams.maker,
address(this),
addLiquidityParams.collateralAmountMaker
);
}
uint256 _after = collateralToken.balanceOf(address(this));
// Revert if a fee was applied during transfer. Throws if `_before > _after`.
if (_after - _before != _collateralAmountIncr) {
revert FeeTokensNotSupported();
}
}
// Increase `collateralBalance`
_pool.collateralBalance += _collateralAmountIncr;
// Mint long and short position tokens and send to `shortRecipient` and
// `_longRecipient`, respectively (additional supply equals `_collateralAmountIncr`)
IPositionToken(_pool.shortToken).mint(
addLiquidityParams.shortRecipient,
_collateralAmountIncr
);
IPositionToken(_pool.longToken).mint(
addLiquidityParams.longRecipient,
_collateralAmountIncr
);
// Log addition of collateral
emit LiquidityAdded(
addLiquidityParams.poolId,
addLiquidityParams.longRecipient,
addLiquidityParams.shortRecipient,
_collateralAmountIncr
);
}
function _removeLiquidityLib(
RemoveLiquidityParams memory _removeLiquidityParams,
LibDIVAStorage.Pool storage _pool
) internal returns (uint256 collateralAmountRemovedNet) {
// Get reference to relevant storage slot
LibDIVAStorage.GovernanceStorage storage gs = LibDIVAStorage
._governanceStorage();
// Confirm that functionality is not paused
if (block.timestamp < gs.pauseReturnCollateralUntil)
revert ReturnCollateralPaused();
// Check if pool exists
if (!_poolExists(_pool)) revert NonExistentPool();
// If status is Confirmed, users should use `redeemPositionToken` function
// to withdraw collateral
if (_pool.statusFinalReferenceValue == LibDIVAStorage.Status.Confirmed)
revert FinalValueAlreadyConfirmed();
// Create reference to short and long position tokens for the given pool
IPositionToken shortToken = IPositionToken(_pool.shortToken);
IPositionToken longToken = IPositionToken(_pool.longToken);
// Check that `shortTokenHolder` and `longTokenHolder` own the corresponding
// `_amount` of short and long position tokens. In particular, this check will
// revert when a user tries to remove an amount that exceeds the overall position token
// supply which is the maximum amount that a user can own.
if (
shortToken.balanceOf(_removeLiquidityParams.shortTokenHolder) <
_removeLiquidityParams.amount ||
longToken.balanceOf(_removeLiquidityParams.longTokenHolder) <
_removeLiquidityParams.amount
) revert InsufficientShortOrLongBalance();
// Get fee parameters applicable for given `_poolId`
LibDIVAStorage.Fees memory _fees = gs.fees[_pool.indexFees];
uint256 _protocolFee;
uint256 _settlementFee;
if (_fees.protocolFee > 0) {
// Calculate protocol fees to charge (note that collateral amount
// to return is equal to `_amount`)
_protocolFee = _calcFee(
_fees.protocolFee,
_removeLiquidityParams.amount,
IERC20Metadata(_pool.collateralToken).decimals()
);
// User has to increase `_amount` if fee is 0
if (_protocolFee == 0) revert ZeroProtocolFee();
} // else _protocolFee = 0 (default value for uint256)
if (_fees.settlementFee > 0) {
// Calculate settlement fees to charge
_settlementFee = _calcFee(
_fees.settlementFee,
_removeLiquidityParams.amount,
IERC20Metadata(_pool.collateralToken).decimals()
);
// User has to increase `_amount` if fee is 0
if (_settlementFee == 0) revert ZeroSettlementFee();
} // else _settlementFee = 0 (default value for uint256)
// Burn short and long position tokens
shortToken.burn(
_removeLiquidityParams.shortTokenHolder,
_removeLiquidityParams.amount
);
longToken.burn(
_removeLiquidityParams.longTokenHolder,
_removeLiquidityParams.amount
);
// Allocate protocol fee to DIVA treasury. Fee is held within this
// contract and can be claimed via `claimFee` function.
// `collateralBalance` is reduced inside `_allocateFeeClaim`.
_allocateFeeClaim(
_removeLiquidityParams.poolId,
_pool,
_getCurrentTreasury(gs),
_protocolFee
);
// Reserve settlement fee for data provider which is not known at this stage.
// Fee will be allocated to actual data provider following final value
// confirmation and afterwards can be claimed via the `claimFee` function.
_reserveFeeClaim(
_removeLiquidityParams.poolId,
_pool,
_settlementFee
);
// Collateral amount to return net of fees
collateralAmountRemovedNet =
_removeLiquidityParams.amount -
_protocolFee -
_settlementFee;
// Log removal of liquidity
emit LiquidityRemoved(
_removeLiquidityParams.poolId,
_removeLiquidityParams.longTokenHolder,
_removeLiquidityParams.shortTokenHolder,
_removeLiquidityParams.amount
);
}
// Returns whether pool exists or not. Uses `collateralToken != address(0)` check
// to determine the existence of a pool as it's the cheapest among the available
// options.
function _poolExists(LibDIVAStorage.Pool storage _pool) internal view returns (bool) {
return _pool.collateralToken != address(0);
}
function _getFeesHistory(
uint256 _nbrLastUpdates,
LibDIVAStorage.GovernanceStorage storage _gs
) internal view returns (LibDIVAStorage.Fees[] memory) {
if (_nbrLastUpdates > 0) {
// Cache length to avoid reading from storage on every loop
uint256 _len = _gs.fees.length;
// Cap `_nbrLastUpdates` at max history rather than throwing an error
_nbrLastUpdates = _nbrLastUpdates > _len ? _len : _nbrLastUpdates;
// Define the size of the array to be returned
LibDIVAStorage.Fees[] memory _fees = new LibDIVAStorage.Fees[](
_nbrLastUpdates
);
// Iterate through the fees array starting from the latest item
for (uint256 i = _len; i > _len - _nbrLastUpdates; ) {
_fees[_len - i] = _gs.fees[i - 1]; // first element of _fees represents latest fees
unchecked {
--i;
}
}
return _fees;
} else {
return new LibDIVAStorage.Fees[](0);
}
}
function _getSettlementPeriodsHistory(
uint256 _nbrLastUpdates,
LibDIVAStorage.GovernanceStorage storage _gs
) internal view returns (LibDIVAStorage.SettlementPeriods[] memory) {
if (_nbrLastUpdates > 0) {
// Cache length to avoid reading from storage on every loop
uint256 _len = _gs.settlementPeriods.length;
// Cap `_nbrLastUpdates` at max history rather than throwing an error
_nbrLastUpdates = _nbrLastUpdates > _len ? _len : _nbrLastUpdates;
// Define the size of the array to be returned
LibDIVAStorage.SettlementPeriods[]
memory _settlementPeriods = new LibDIVAStorage.SettlementPeriods[](
_nbrLastUpdates
);
// Iterate through the settlement periods array starting from the latest item
for (uint256 i = _len; i > _len - _nbrLastUpdates; ) {
_settlementPeriods[_len - i] = _gs.settlementPeriods[i - 1]; // first element of _fees represents latest fees
unchecked {
--i;
}
}
return _settlementPeriods;
} else {
return new LibDIVAStorage.SettlementPeriods[](0);
}
}
function _getCurrentFees(LibDIVAStorage.GovernanceStorage storage _gs)
internal
view
returns (uint48 index, LibDIVAStorage.Fees memory fees)
{
// Get length of `fees` array
uint256 _len = _gs.fees.length;
// Load latest fee regime
LibDIVAStorage.Fees memory _fees = _gs.fees[_len - 1];
// Return the latest array entry & index if already past activation time,
// otherwise return the second last entry
if (_fees.startTime > block.timestamp) {
index = uint48(_len - 2);
} else {
index = uint48(_len - 1);
}
fees = _gs.fees[index];
}
function _getCurrentSettlementPeriods(
LibDIVAStorage.GovernanceStorage storage _gs
)
internal
view
returns (
uint48 index,
LibDIVAStorage.SettlementPeriods memory settlementPeriods
)
{
// Get length of `settlementPeriods` array
uint256 _len = _gs.settlementPeriods.length;
// Load latest settlement periods regime
LibDIVAStorage.SettlementPeriods memory _settlementPeriods = _gs
.settlementPeriods[_len - 1];
// Return the latest array entry & index if already past activation time,
// otherwise return the second last entry
if (_settlementPeriods.startTime > block.timestamp) {
index = uint48(_len - 2);
} else {
index = uint48(_len - 1);
}
settlementPeriods = _gs.settlementPeriods[index];
}
function _getCurrentFallbackDataProvider(
LibDIVAStorage.GovernanceStorage storage _gs
) internal view returns (address) {
// Return the new fallback data provider if `block.timestamp` is at or past
// the activation time, else return the current fallback data provider
return
block.timestamp < _gs.startTimeFallbackDataProvider
? _gs.previousFallbackDataProvider
: _gs.fallbackDataProvider;
}
function _getCurrentTreasury(LibDIVAStorage.GovernanceStorage storage _gs)
internal
view
returns (address)
{
// Return the new treasury address if `block.timestamp` is at or past
// the activation time, else return the current treasury address
return
block.timestamp < _gs.startTimeTreasury
? _gs.previousTreasury
: _gs.treasury;
}
function _getFallbackDataProviderInfo(
LibDIVAStorage.GovernanceStorage storage _gs
)
internal
view
returns (
address previousFallbackDataProvider,
address fallbackDataProvider,
uint256 startTimeFallbackDataProvider
)
{
// Return values
previousFallbackDataProvider = _gs.previousFallbackDataProvider;
fallbackDataProvider = _gs.fallbackDataProvider;
startTimeFallbackDataProvider = _gs.startTimeFallbackDataProvider;
}
function _getTreasuryInfo(LibDIVAStorage.GovernanceStorage storage _gs)
internal
view
returns (
address previousTreasury,
address treasury,
uint256 startTimeTreasury
)
{
// Return values
previousTreasury = _gs.previousTreasury;
treasury = _gs.treasury;
startTimeTreasury = _gs.startTimeTreasury;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;
library LibDiamondStorage {
// The hash for diamond storage position, which is:
// keccak256("diamond.standard.diamond.storage")
bytes32 constant DIAMOND_STORAGE_POSITION =
0xc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131c;
struct FacetAddressAndPosition {
address facetAddress;
uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint256 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
// Maps function selector to the facet address and
// the position of the selector in the facetFunctionSelectors.selectors array
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
// Maps facet addresses to function selectors
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
// Facet addresses
address[] facetAddresses;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// Address of contract that stores the owner and implements the ownership
// transfer mechanism
address ownershipContract;
}
function _diamondStorage()
internal
pure
returns (DiamondStorage storage ds)
{
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;
library LibEIP712Storage {
// The hash for eip712 storage position, which is:
// keccak256("diamond.standard.eip712.storage")
bytes32 constant EIP712_STORAGE_POSITION =
0x8605704e9bc6b9116b88d76d80e5d463ac2b851042de18aae713a2e1c43f2fe5;
struct EIP712Storage {
// EIP712 domain separator (set in constructor in Diamond.sol)
bytes32 EIP712_DOMAIN_SEPARATOR;
// Chain id (set in constructor in Diamond.sol)
uint256 CACHED_CHAIN_ID;
// Mapping to store created poolId with typedOfferHash
mapping(bytes32 => bytes32) typedOfferHashToPoolId;
// Mapping to store takerFilled amount with typedOfferHash
mapping(bytes32 => uint256) typedOfferHashToTakerFilledAmount;
}
function _eip712Storage() internal pure returns (EIP712Storage storage es) {
bytes32 position = EIP712_STORAGE_POSITION;
assembly {
es.slot := position
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IPositionToken} from "./interfaces/IPositionToken.sol";
/**
* @dev Implementation contract for position token clones
*/
contract PositionToken is IPositionToken, ERC20Upgradeable {
bytes32 private _poolId;
address private _owner;
uint8 private _decimals;
constructor() {
/* @dev To prevent the implementation contract from being used, invoke the {_disableInitializers}
* function in the constructor to automatically lock it when it is deployed.
* For more information, refer to @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
*/
_disableInitializers();
}
modifier onlyOwner() {
require(
_owner == msg.sender,
"PositionToken: caller is not owner"
);
_;
}
function mint(
address _recipient,
uint256 _amount
) external override onlyOwner {
_mint(_recipient, _amount);
}
function burn(
address _redeemer,
uint256 _amount
) external override onlyOwner {
_burn(_redeemer, _amount);
}
function poolId() external view override returns (bytes32) {
return _poolId;
}
function owner() external view override returns (address) {
return _owner;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function initialize(
string memory symbol_,
bytes32 poolId_,
uint8 decimals_,
address owner_
) external override initializer {
__ERC20_init(symbol_, symbol_);
_owner = owner_;
_poolId = poolId_;
_decimals = decimals_;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;
/**
* @notice Reduced version of Synthetix' SafeDecimalMath library for decimal
* calculations:
* https://github.com/Synthetixio/synthetix/blob/master/contracts/SafeDecimalMath.sol
* Note that the code was adjusted for solidity 0.8.19 where SafeMath is no
* longer required to handle overflows
*/
library SafeDecimalMath {
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
/* The number representing 1.0. */
uint256 public constant UNIT = 10**uint256(decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint256) {
return UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands
* as fixed-point decimals.
*
* @dev A unit factor is divided out after the product of x and y is
* evaluated, so that product must be less than 2**256. As this is an
* integer division, the internal division always rounds down. This helps
* save on gas. Rounding is more expensive on gas.
*/
function multiplyDecimal(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// Divide by UNIT to remove the extra factor introduced by the product
return (x * y) / UNIT;
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// Reintroduce the UNIT factor that will be divided out by y
return (x * UNIT) / y;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.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));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev String operations.
*/
library Strings {
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 = Math.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, Math.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 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 IERC20Permit {
/**
* @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);
}
{
"compilationTarget": {
"contracts/Diamond.sol": "Diamond"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"_ownershipContract","type":"address"},{"internalType":"address","name":"_fallbackDataProvider","type":"address"},{"internalType":"address","name":"_diamondCutFacet","type":"address"},{"internalType":"address","name":"_treasury","type":"address"},{"internalType":"address","name":"_positionTokenFactory","type":"address"}],"stateMutability":"payable","type":"constructor"},{"inputs":[{"internalType":"bytes4","name":"_selector","type":"bytes4"}],"name":"CannotAddFunctionToDiamondThatAlreadyExists","type":"error"},{"inputs":[{"internalType":"bytes4[]","name":"_selectors","type":"bytes4[]"}],"name":"CannotAddSelectorsToZeroAddress","type":"error"},{"inputs":[{"internalType":"bytes4","name":"_selector","type":"bytes4"}],"name":"CannotRemoveFunctionThatDoesNotExist","type":"error"},{"inputs":[{"internalType":"bytes4","name":"_selector","type":"bytes4"}],"name":"CannotRemoveImmutableFunction","type":"error"},{"inputs":[{"internalType":"bytes4","name":"_selector","type":"bytes4"}],"name":"CannotReplaceFunctionWithTheSameFunctionFromTheSameFacet","type":"error"},{"inputs":[{"internalType":"bytes4[]","name":"_selectors","type":"bytes4[]"}],"name":"CannotReplaceFunctionsFromFacetWithZeroAddress","type":"error"},{"inputs":[{"internalType":"bytes4","name":"_functionSelector","type":"bytes4"}],"name":"FunctionNotFound","type":"error"},{"inputs":[{"internalType":"uint8","name":"_action","type":"uint8"}],"name":"IncorrectFacetCutAction","type":"error"},{"inputs":[{"internalType":"address","name":"_initializationContractAddress","type":"address"},{"internalType":"bytes","name":"_calldata","type":"bytes"}],"name":"InitializationFunctionReverted","type":"error"},{"inputs":[{"internalType":"address","name":"_contractAddress","type":"address"},{"internalType":"string","name":"_message","type":"string"}],"name":"NoBytecodeAtAddress","type":"error"},{"inputs":[{"internalType":"address","name":"_facetAddress","type":"address"}],"name":"NoSelectorsProvidedForFacetForCut","type":"error"},{"inputs":[{"internalType":"address","name":"_facetAddress","type":"address"}],"name":"RemoveFacetAddressMustBeZeroAddress","type":"error"},{"inputs":[],"name":"ZeroDiamondCutFacetAddress","type":"error"},{"inputs":[],"name":"ZeroFallbackDataProviderAddress","type":"error"},{"inputs":[],"name":"ZeroOwnershipContractAddress","type":"error"},{"inputs":[],"name":"ZeroPositionTokenFactoryAddress","type":"error"},{"inputs":[],"name":"ZeroTreasuryAddress","type":"error"},{"stateMutability":"payable","type":"fallback"}]