{ "language": "Solidity", "sources": { "@synthetixio/core-contracts/contracts/errors/AccessError.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Library for access related errors.\n */\nlibrary AccessError {\n /**\n * @dev Thrown when an address tries to perform an unauthorized action.\n * @param addr The address that attempts the action.\n */\n error Unauthorized(address addr);\n}\n" }, "@synthetixio/core-contracts/contracts/errors/AddressError.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Library for address related errors.\n */\nlibrary AddressError {\n /**\n * @dev Thrown when a zero address was passed as a function parameter (0x0000000000000000000000000000000000000000).\n */\n error ZeroAddress();\n\n /**\n * @dev Thrown when an address representing a contract is expected, but no code is found at the address.\n * @param contr The address that was expected to be a contract.\n */\n error NotAContract(address contr);\n}\n" }, "@synthetixio/core-contracts/contracts/errors/ArrayError.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Library for array related errors.\n */\nlibrary ArrayError {\n /**\n * @dev Thrown when an unexpected empty array is detected.\n */\n error EmptyArray();\n\n /**\n * @dev Thrown when attempting to access an array beyond its current number of items.\n */\n error OutOfBounds();\n}\n" }, "@synthetixio/core-contracts/contracts/errors/ChangeError.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Library for change related errors.\n */\nlibrary ChangeError {\n /**\n * @dev Thrown when a change is expected but none is detected.\n */\n error NoChange();\n}\n" }, "@synthetixio/core-contracts/contracts/errors/InitError.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Library for initialization related errors.\n */\nlibrary InitError {\n /**\n * @dev Thrown when attempting to initialize a contract that is already initialized.\n */\n error AlreadyInitialized();\n\n /**\n * @dev Thrown when attempting to interact with a contract that has not been initialized yet.\n */\n error NotInitialized();\n}\n" }, "@synthetixio/core-contracts/contracts/errors/ParameterError.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Library for errors related with expected function parameters.\n */\nlibrary ParameterError {\n /**\n * @dev Thrown when an invalid parameter is used in a function.\n * @param parameter The name of the parameter.\n * @param reason The reason why the received parameter is invalid.\n */\n error InvalidParameter(string parameter, string reason);\n}\n" }, "@synthetixio/core-contracts/contracts/initializable/InitializableMixin.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../errors/InitError.sol\";\n\n/**\n * @title Mixin for contracts that require initialization.\n */\nabstract contract InitializableMixin {\n /**\n * @dev Reverts if contract is not initialized.\n */\n modifier onlyIfInitialized() {\n if (!_isInitialized()) {\n revert InitError.NotInitialized();\n }\n\n _;\n }\n\n /**\n * @dev Reverts if contract is already initialized.\n */\n modifier onlyIfNotInitialized() {\n if (_isInitialized()) {\n revert InitError.AlreadyInitialized();\n }\n\n _;\n }\n\n /**\n * @dev Override this function to determine if the contract is initialized.\n * @return True if initialized, false otherwise.\n */\n function _isInitialized() internal view virtual returns (bool);\n}\n" }, "@synthetixio/core-contracts/contracts/interfaces/IERC165.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title ERC165 interface for determining if a contract supports a given interface.\n */\ninterface IERC165 {\n /**\n * @notice Determines if the contract in question supports the specified interface.\n * @param interfaceID XOR of all selectors in the contract.\n * @return True if the contract supports the specified interface.\n */\n function supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n" }, "@synthetixio/core-contracts/contracts/interfaces/IERC20.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title ERC20 token implementation.\n */\ninterface IERC20 {\n /**\n * @notice Emitted when tokens have been transferred.\n * @param from The address that originally owned the tokens.\n * @param to The address that received the tokens.\n * @param amount The number of tokens that were transferred.\n */\n event Transfer(address indexed from, address indexed to, uint amount);\n\n /**\n * @notice Emitted when a user has provided allowance to another user for transferring tokens on its behalf.\n * @param owner The address that is providing the allowance.\n * @param spender The address that received the allowance.\n * @param amount The number of tokens that were added to `spender`'s allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint amount);\n\n /**\n * @notice Thrown when the address interacting with the contract does not have sufficient allowance to transfer tokens from another contract.\n * @param required The necessary allowance.\n * @param existing The current allowance.\n */\n error InsufficientAllowance(uint required, uint existing);\n\n /**\n * @notice Thrown when the address interacting with the contract does not have sufficient tokens.\n * @param required The necessary balance.\n * @param existing The current balance.\n */\n error InsufficientBalance(uint required, uint existing);\n\n /**\n * @notice Retrieves the name of the token, e.g. \"Synthetix Network Token\".\n * @return A string with the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @notice Retrieves the symbol of the token, e.g. \"SNX\".\n * @return A string with the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @notice Retrieves the number of decimals used by the token. The default is 18.\n * @return The number of decimals.\n */\n function decimals() external view returns (uint8);\n\n /**\n * @notice Returns the total number of tokens in circulation (minted - burnt).\n * @return The total number of tokens.\n */\n function totalSupply() external view returns (uint);\n\n /**\n * @notice Returns the balance of a user.\n * @param owner The address whose balance is being retrieved.\n * @return The number of tokens owned by the user.\n */\n function balanceOf(address owner) external view returns (uint);\n\n /**\n * @notice Returns how many tokens a user has allowed another user to transfer on its behalf.\n * @param owner The user who has given the allowance.\n * @param spender The user who was given the allowance.\n * @return The amount of tokens `spender` can transfer on `owner`'s behalf.\n */\n function allowance(address owner, address spender) external view returns (uint);\n\n /**\n * @notice Transfer tokens from one address to another.\n * @param to The address that will receive the tokens.\n * @param amount The amount of tokens to be transferred.\n * @return A boolean which is true if the operation succeeded.\n */\n function transfer(address to, uint amount) external returns (bool);\n\n /**\n * @notice Allows users to provide allowance to other users so that they can transfer tokens on their behalf.\n * @param spender The address that is receiving the allowance.\n * @param amount The amount of tokens that are being added to the allowance.\n * @return A boolean which is true if the operation succeeded.\n */\n function approve(address spender, uint amount) external returns (bool);\n\n /**\n * @notice Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) external returns (bool);\n\n /**\n * @notice Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);\n\n /**\n * @notice Allows a user who has been given allowance to transfer tokens on another user's behalf.\n * @param from The address that owns the tokens that are being transferred.\n * @param to The address that will receive the tokens.\n * @param amount The number of tokens to transfer.\n * @return A boolean which is true if the operation succeeded.\n */\n function transferFrom(address from, address to, uint amount) external returns (bool);\n}\n" }, "@synthetixio/core-contracts/contracts/interfaces/IERC721.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title ERC721 non-fungible token (NFT) contract.\n */\ninterface IERC721 {\n /**\n * @notice Thrown when an address attempts to provide allowance to itself.\n * @param addr The address attempting to provide allowance.\n */\n error CannotSelfApprove(address addr);\n\n /**\n * @notice Thrown when attempting to transfer a token to an address that does not satisfy IERC721Receiver requirements.\n * @param addr The address that cannot receive the tokens.\n */\n error InvalidTransferRecipient(address addr);\n\n /**\n * @notice Thrown when attempting to specify an owner which is not valid (ex. the 0x00000... address)\n */\n error InvalidOwner(address addr);\n\n /**\n * @notice Thrown when attempting to operate on a token id that does not exist.\n * @param id The token id that does not exist.\n */\n error TokenDoesNotExist(uint256 id);\n\n /**\n * @notice Thrown when attempting to mint a token that already exists.\n * @param id The token id that already exists.\n */\n error TokenAlreadyMinted(uint256 id);\n\n /**\n * @notice Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @notice Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @notice Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @notice Returns the number of tokens in ``owner``'s account.\n *\n * Requirements:\n *\n * - `owner` must be a valid address\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @notice Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @notice Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @notice Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @notice Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @notice Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @notice Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @notice Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @notice Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n" }, "@synthetixio/core-contracts/contracts/interfaces/IERC721Enumerable.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC721 extension with helper functions that allow the enumeration of NFT tokens.\n */\ninterface IERC721Enumerable is IERC721 {\n /**\n * @notice Thrown calling *ByIndex function with an index greater than the number of tokens existing\n * @param requestedIndex The index requested by the caller\n * @param length The length of the list that is being iterated, making the max index queryable length - 1\n */\n error IndexOverrun(uint requestedIndex, uint length);\n\n /**\n * @dev Returns the total amount of tokens stored by the contract.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\n *\n * Requirements:\n * - `owner` must be a valid address\n * - `index` must be less than the balance of the tokens for the owner\n */\n function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);\n\n /**\n * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n * Use along with {totalSupply} to enumerate all tokens.\n *\n * Requirements:\n * - `index` must be less than the total supply of the tokens\n */\n function tokenByIndex(uint256 index) external view returns (uint256);\n}\n" }, "@synthetixio/core-contracts/contracts/interfaces/IERC721Metadata.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @title Additional metadata for IERC721 tokens.\n */\ninterface IERC721Metadata is IERC165 {\n /**\n * @notice Retrieves the name of the token, e.g. \"Synthetix Account Token\".\n * @return A string with the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @notice Retrieves the symbol of the token, e.g. \"SNX-ACC\".\n * @return A string with the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @notice Retrieves the off-chain URI where the specified token id may contain associated data, such as images, audio, etc.\n * @param tokenId The numeric id of the token in question.\n * @return The URI of the token in question.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" }, "@synthetixio/core-contracts/contracts/interfaces/IERC721Receiver.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title ERC721 extension that allows contracts to receive tokens with `safeTransferFrom`.\n */\ninterface IERC721Receiver {\n /**\n * @notice Function that will be called by ERC721 tokens implementing the `safeTransferFrom` function.\n * @dev The contract transferring the token will revert if the receiving contract does not implement this function.\n * @param operator The address that is executing the transfer.\n * @param from The address whose token is being transferred.\n * @param tokenId The numeric id of the token being transferred.\n * @param data Optional additional data that may be passed by the operator, and could be used by the implementing contract.\n * @return The selector of this function (IERC721Receiver.onERC721Received.selector). Caller will revert if not returned.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes memory data\n ) external returns (bytes4);\n}\n" }, "@synthetixio/core-contracts/contracts/interfaces/IOwnable.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Contract for facilitating ownership by a single address.\n */\ninterface IOwnable {\n /**\n * @notice Thrown when an address tries to accept ownership but has not been nominated.\n * @param addr The address that is trying to accept ownership.\n */\n error NotNominated(address addr);\n\n /**\n * @notice Emitted when an address has been nominated.\n * @param newOwner The address that has been nominated.\n */\n event OwnerNominated(address newOwner);\n\n /**\n * @notice Emitted when the owner of the contract has changed.\n * @param oldOwner The previous owner of the contract.\n * @param newOwner The new owner of the contract.\n */\n event OwnerChanged(address oldOwner, address newOwner);\n\n /**\n * @notice Allows a nominated address to accept ownership of the contract.\n * @dev Reverts if the caller is not nominated.\n */\n function acceptOwnership() external;\n\n /**\n * @notice Allows the current owner to nominate a new owner.\n * @dev The nominated owner will have to call `acceptOwnership` in a separate transaction in order to finalize the action and become the new contract owner.\n * @param newNominatedOwner The address that is to become nominated.\n */\n function nominateNewOwner(address newNominatedOwner) external;\n\n /**\n * @notice Allows a nominated owner to reject the nomination.\n */\n function renounceNomination() external;\n\n /**\n * @notice Returns the current owner of the contract.\n */\n function owner() external view returns (address);\n\n /**\n * @notice Returns the current nominated owner of the contract.\n * @dev Only one address can be nominated at a time.\n */\n function nominatedOwner() external view returns (address);\n}\n" }, "@synthetixio/core-contracts/contracts/interfaces/IUUPSImplementation.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Contract to be used as the implementation of a Universal Upgradeable Proxy Standard (UUPS) proxy.\n *\n * Important: A UUPS proxy requires its upgradeability functions to be in the implementation as opposed to the proxy. This means that if the proxy is upgraded to an implementation that does not support this interface, it will no longer be upgradeable.\n */\ninterface IUUPSImplementation {\n /**\n * @notice Thrown when an incoming implementation will not be able to receive future upgrades.\n */\n error ImplementationIsSterile(address implementation);\n\n /**\n * @notice Thrown intentionally when testing future upgradeability of an implementation.\n */\n error UpgradeSimulationFailed();\n\n /**\n * @notice Emitted when the implementation of the proxy has been upgraded.\n * @param self The address of the proxy whose implementation was upgraded.\n * @param implementation The address of the proxy's new implementation.\n */\n event Upgraded(address indexed self, address implementation);\n\n /**\n * @notice Allows the proxy to be upgraded to a new implementation.\n * @param newImplementation The address of the proxy's new implementation.\n * @dev Will revert if `newImplementation` is not upgradeable.\n * @dev The implementation of this function needs to be protected by some sort of access control such as `onlyOwner`.\n */\n function upgradeTo(address newImplementation) external;\n\n /**\n * @notice Function used to determine if a new implementation will be able to receive future upgrades in `upgradeTo`.\n * @param newImplementation The address of the new implementation being tested for future upgradeability.\n * @dev This function will always revert, but will revert with different error messages. The function `upgradeTo` uses this error to determine the future upgradeability of the implementation in question.\n */\n function simulateUpgradeTo(address newImplementation) external;\n\n /**\n * @notice Retrieves the current implementation of the proxy.\n * @return The address of the current implementation.\n */\n function getImplementation() external view returns (address);\n}\n" }, "@synthetixio/core-contracts/contracts/ownership/Ownable.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./OwnableStorage.sol\";\nimport \"../interfaces/IOwnable.sol\";\nimport \"../errors/AddressError.sol\";\nimport \"../errors/ChangeError.sol\";\n\n/**\n * @title Contract for facilitating ownership by a single address.\n * See IOwnable.\n */\ncontract Ownable is IOwnable {\n constructor(address initialOwner) {\n OwnableStorage.load().owner = initialOwner;\n }\n\n /**\n * @inheritdoc IOwnable\n */\n function acceptOwnership() public override {\n OwnableStorage.Data storage store = OwnableStorage.load();\n\n address currentNominatedOwner = store.nominatedOwner;\n if (msg.sender != currentNominatedOwner) {\n revert NotNominated(msg.sender);\n }\n\n emit OwnerChanged(store.owner, currentNominatedOwner);\n store.owner = currentNominatedOwner;\n\n store.nominatedOwner = address(0);\n }\n\n /**\n * @inheritdoc IOwnable\n */\n function nominateNewOwner(address newNominatedOwner) public override onlyOwner {\n OwnableStorage.Data storage store = OwnableStorage.load();\n\n if (newNominatedOwner == address(0)) {\n revert AddressError.ZeroAddress();\n }\n\n if (newNominatedOwner == store.nominatedOwner) {\n revert ChangeError.NoChange();\n }\n\n store.nominatedOwner = newNominatedOwner;\n emit OwnerNominated(newNominatedOwner);\n }\n\n /**\n * @inheritdoc IOwnable\n */\n function renounceNomination() external override {\n OwnableStorage.Data storage store = OwnableStorage.load();\n\n if (store.nominatedOwner != msg.sender) {\n revert NotNominated(msg.sender);\n }\n\n store.nominatedOwner = address(0);\n }\n\n /**\n * @inheritdoc IOwnable\n */\n function owner() external view override returns (address) {\n return OwnableStorage.load().owner;\n }\n\n /**\n * @inheritdoc IOwnable\n */\n function nominatedOwner() external view override returns (address) {\n return OwnableStorage.load().nominatedOwner;\n }\n\n /**\n * @dev Reverts if the caller is not the owner.\n */\n modifier onlyOwner() {\n OwnableStorage.onlyOwner();\n\n _;\n }\n}\n" }, "@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../errors/AccessError.sol\";\n\nlibrary OwnableStorage {\n bytes32 private constant _SLOT_OWNABLE_STORAGE =\n keccak256(abi.encode(\"io.synthetix.core-contracts.Ownable\"));\n\n struct Data {\n address owner;\n address nominatedOwner;\n }\n\n function load() internal pure returns (Data storage store) {\n bytes32 s = _SLOT_OWNABLE_STORAGE;\n assembly {\n store.slot := s\n }\n }\n\n function onlyOwner() internal view {\n if (msg.sender != getOwner()) {\n revert AccessError.Unauthorized(msg.sender);\n }\n }\n\n function getOwner() internal view returns (address) {\n return OwnableStorage.load().owner;\n }\n}\n" }, "@synthetixio/core-contracts/contracts/proxy/AbstractProxy.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nabstract contract AbstractProxy {\n fallback() external payable {\n _forward();\n }\n\n receive() external payable {\n _forward();\n }\n\n function _forward() internal {\n address implementation = _getImplementation();\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n calldatacopy(0, 0, calldatasize())\n\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n returndatacopy(0, 0, returndatasize())\n\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n function _getImplementation() internal view virtual returns (address);\n}\n" }, "@synthetixio/core-contracts/contracts/proxy/ProxyStorage.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\ncontract ProxyStorage {\n bytes32 private constant _SLOT_PROXY_STORAGE =\n keccak256(abi.encode(\"io.synthetix.core-contracts.Proxy\"));\n\n struct ProxyStore {\n address implementation;\n bool simulatingUpgrade;\n }\n\n function _proxyStore() internal pure returns (ProxyStore storage store) {\n bytes32 s = _SLOT_PROXY_STORAGE;\n assembly {\n store.slot := s\n }\n }\n}\n" }, "@synthetixio/core-contracts/contracts/proxy/UUPSImplementation.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../interfaces/IUUPSImplementation.sol\";\nimport \"../errors/AddressError.sol\";\nimport \"../errors/ChangeError.sol\";\nimport \"../utils/AddressUtil.sol\";\nimport \"./ProxyStorage.sol\";\n\nabstract contract UUPSImplementation is IUUPSImplementation, ProxyStorage {\n /**\n * @inheritdoc IUUPSImplementation\n */\n function simulateUpgradeTo(address newImplementation) public override {\n ProxyStore storage store = _proxyStore();\n\n store.simulatingUpgrade = true;\n\n address currentImplementation = store.implementation;\n store.implementation = newImplementation;\n\n (bool rollbackSuccessful, ) = newImplementation.delegatecall(\n abi.encodeCall(this.upgradeTo, (currentImplementation))\n );\n\n if (!rollbackSuccessful || _proxyStore().implementation != currentImplementation) {\n revert UpgradeSimulationFailed();\n }\n\n store.simulatingUpgrade = false;\n\n // solhint-disable-next-line reason-string\n revert();\n }\n\n /**\n * @inheritdoc IUUPSImplementation\n */\n function getImplementation() external view override returns (address) {\n return _proxyStore().implementation;\n }\n\n function _upgradeTo(address newImplementation) internal virtual {\n if (newImplementation == address(0)) {\n revert AddressError.ZeroAddress();\n }\n\n if (!AddressUtil.isContract(newImplementation)) {\n revert AddressError.NotAContract(newImplementation);\n }\n\n ProxyStore storage store = _proxyStore();\n\n if (newImplementation == store.implementation) {\n revert ChangeError.NoChange();\n }\n\n if (!store.simulatingUpgrade && _implementationIsSterile(newImplementation)) {\n revert ImplementationIsSterile(newImplementation);\n }\n\n store.implementation = newImplementation;\n\n emit Upgraded(address(this), newImplementation);\n }\n\n function _implementationIsSterile(\n address candidateImplementation\n ) internal virtual returns (bool) {\n (bool simulationReverted, bytes memory simulationResponse) = address(this).delegatecall(\n abi.encodeCall(this.simulateUpgradeTo, (candidateImplementation))\n );\n\n return\n !simulationReverted &&\n keccak256(abi.encodePacked(simulationResponse)) ==\n keccak256(abi.encodePacked(UpgradeSimulationFailed.selector));\n }\n}\n" }, "@synthetixio/core-contracts/contracts/proxy/UUPSProxy.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./AbstractProxy.sol\";\nimport \"./ProxyStorage.sol\";\nimport \"../errors/AddressError.sol\";\nimport \"../utils/AddressUtil.sol\";\n\ncontract UUPSProxy is AbstractProxy, ProxyStorage {\n constructor(address firstImplementation) {\n if (firstImplementation == address(0)) {\n revert AddressError.ZeroAddress();\n }\n\n if (!AddressUtil.isContract(firstImplementation)) {\n revert AddressError.NotAContract(firstImplementation);\n }\n\n _proxyStore().implementation = firstImplementation;\n }\n\n function _getImplementation() internal view virtual override returns (address) {\n return _proxyStore().implementation;\n }\n}\n" }, "@synthetixio/core-contracts/contracts/proxy/UUPSProxyWithOwner.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport {UUPSProxy} from \"./UUPSProxy.sol\";\nimport {OwnableStorage} from \"../ownership/OwnableStorage.sol\";\n\ncontract UUPSProxyWithOwner is UUPSProxy {\n // solhint-disable-next-line no-empty-blocks\n constructor(address firstImplementation, address initialOwner) UUPSProxy(firstImplementation) {\n OwnableStorage.load().owner = initialOwner;\n }\n}\n" }, "@synthetixio/core-contracts/contracts/token/ERC20.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../interfaces/IERC20.sol\";\nimport \"../errors/InitError.sol\";\nimport \"./ERC20Storage.sol\";\n\n/*\n * @title ERC20 token implementation.\n * See IERC20.\n *\n * Reference implementations:\n * - OpenZeppelin - https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol\n * - Rari-Capital - https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol\n */\ncontract ERC20 is IERC20 {\n /**\n * @inheritdoc IERC20\n */\n function name() external view override returns (string memory) {\n return ERC20Storage.load().name;\n }\n\n /**\n * @inheritdoc IERC20\n */\n function symbol() external view override returns (string memory) {\n return ERC20Storage.load().symbol;\n }\n\n /**\n * @inheritdoc IERC20\n */\n function decimals() external view override returns (uint8) {\n return ERC20Storage.load().decimals;\n }\n\n /**\n * @inheritdoc IERC20\n */\n function totalSupply() external view virtual override returns (uint256) {\n return ERC20Storage.load().totalSupply;\n }\n\n /**\n * @inheritdoc IERC20\n */\n function allowance(\n address owner,\n address spender\n ) public view virtual override returns (uint256) {\n return ERC20Storage.load().allowance[owner][spender];\n }\n\n /**\n * @inheritdoc IERC20\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n return ERC20Storage.load().balanceOf[owner];\n }\n\n /**\n * @inheritdoc IERC20\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n _approve(msg.sender, spender, amount);\n return true;\n }\n\n /**\n * @inheritdoc IERC20\n */\n function increaseAllowance(\n address spender,\n uint256 addedValue\n ) public virtual override returns (bool) {\n uint256 currentAllowance = ERC20Storage.load().allowance[msg.sender][spender];\n _approve(msg.sender, spender, currentAllowance + addedValue);\n\n return true;\n }\n\n /**\n * @inheritdoc IERC20\n */\n function decreaseAllowance(\n address spender,\n uint256 subtractedValue\n ) public virtual override returns (bool) {\n uint256 currentAllowance = ERC20Storage.load().allowance[msg.sender][spender];\n _approve(msg.sender, spender, currentAllowance - subtractedValue);\n\n return true;\n }\n\n /**\n * @inheritdoc IERC20\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n _transfer(msg.sender, to, amount);\n\n return true;\n }\n\n /**\n * @inheritdoc IERC20\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external virtual override returns (bool) {\n return _transferFrom(from, to, amount);\n }\n\n function _transferFrom(\n address from,\n address to,\n uint256 amount\n ) internal virtual returns (bool) {\n ERC20Storage.Data storage store = ERC20Storage.load();\n\n uint256 currentAllowance = store.allowance[from][msg.sender];\n if (currentAllowance < amount) {\n revert InsufficientAllowance(amount, currentAllowance);\n }\n\n unchecked {\n store.allowance[from][msg.sender] -= amount;\n }\n\n _transfer(from, to, amount);\n\n return true;\n }\n\n function _transfer(address from, address to, uint256 amount) internal virtual {\n ERC20Storage.Data storage store = ERC20Storage.load();\n\n uint256 accountBalance = store.balanceOf[from];\n if (accountBalance < amount) {\n revert InsufficientBalance(amount, accountBalance);\n }\n\n // We are now sure that we can perform this operation safely\n // since it didn't revert in the previous step.\n // The total supply cannot exceed the maximum value of uint256,\n // thus we can now perform accounting operations in unchecked mode.\n unchecked {\n store.balanceOf[from] -= amount;\n store.balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n }\n\n function _approve(address owner, address spender, uint256 amount) internal virtual {\n ERC20Storage.load().allowance[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n function _mint(address to, uint256 amount) internal virtual {\n ERC20Storage.Data storage store = ERC20Storage.load();\n\n store.totalSupply += amount;\n\n // No need for overflow check since it is done in the previous step\n unchecked {\n store.balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n ERC20Storage.Data storage store = ERC20Storage.load();\n\n uint256 accountBalance = store.balanceOf[from];\n if (accountBalance < amount) {\n revert InsufficientBalance(amount, accountBalance);\n }\n\n // No need for underflow check since it would have occured in the previous step\n unchecked {\n store.balanceOf[from] -= amount;\n store.totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n\n function _initialize(\n string memory tokenName,\n string memory tokenSymbol,\n uint8 tokenDecimals\n ) internal virtual {\n ERC20Storage.Data storage store = ERC20Storage.load();\n\n if (bytes(store.name).length > 0 || bytes(store.symbol).length > 0 || store.decimals > 0) {\n revert InitError.AlreadyInitialized();\n }\n\n store.name = tokenName;\n store.symbol = tokenSymbol;\n store.decimals = tokenDecimals;\n }\n}\n" }, "@synthetixio/core-contracts/contracts/token/ERC20Helper.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../interfaces/IERC20.sol\";\n\nlibrary ERC20Helper {\n error FailedTransfer(address from, address to, uint value);\n\n function safeTransfer(address token, address to, uint value) internal {\n (bool success, bytes memory data) = token.call(\n abi.encodeWithSelector(IERC20.transfer.selector, to, value)\n );\n if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {\n revert FailedTransfer(address(this), to, value);\n }\n }\n\n function safeTransferFrom(address token, address from, address to, uint value) internal {\n (bool success, bytes memory data) = token.call(\n abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)\n );\n if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {\n revert FailedTransfer(from, to, value);\n }\n }\n}\n" }, "@synthetixio/core-contracts/contracts/token/ERC20Storage.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nlibrary ERC20Storage {\n bytes32 private constant _SLOT_ERC20_STORAGE =\n keccak256(abi.encode(\"io.synthetix.core-contracts.ERC20\"));\n\n struct Data {\n string name;\n string symbol;\n uint8 decimals;\n mapping(address => uint256) balanceOf;\n mapping(address => mapping(address => uint256)) allowance;\n uint256 totalSupply;\n }\n\n function load() internal pure returns (Data storage store) {\n bytes32 s = _SLOT_ERC20_STORAGE;\n assembly {\n store.slot := s\n }\n }\n}\n" }, "@synthetixio/core-contracts/contracts/token/ERC721.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../interfaces/IERC721.sol\";\nimport \"../interfaces/IERC721Metadata.sol\";\nimport \"../interfaces/IERC721Receiver.sol\";\nimport \"../errors/AddressError.sol\";\nimport \"../errors/AccessError.sol\";\nimport \"../errors/InitError.sol\";\nimport \"../errors/ParameterError.sol\";\nimport \"./ERC721Storage.sol\";\nimport \"../utils/AddressUtil.sol\";\nimport \"../utils/StringUtil.sol\";\n\n/*\n * @title ERC721 non-fungible token (NFT) contract.\n * See IERC721.\n *\n * Reference implementations:\n * - OpenZeppelin - https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol\n */\ncontract ERC721 is IERC721, IERC721Metadata {\n /**\n * @inheritdoc IERC165\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return\n interfaceId == this.supportsInterface.selector || // ERC165\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId;\n }\n\n /**\n * @inheritdoc IERC721\n */\n function balanceOf(address holder) public view virtual override returns (uint) {\n if (holder == address(0)) {\n revert InvalidOwner(holder);\n }\n\n return ERC721Storage.load().balanceOf[holder];\n }\n\n /**\n * @inheritdoc IERC721\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n if (!_exists(tokenId)) {\n revert TokenDoesNotExist(tokenId);\n }\n\n return ERC721Storage.load().ownerOf[tokenId];\n }\n\n /**\n * @inheritdoc IERC721Metadata\n */\n function name() external view virtual override returns (string memory) {\n return ERC721Storage.load().name;\n }\n\n /**\n * @inheritdoc IERC721Metadata\n */\n function symbol() external view virtual override returns (string memory) {\n return ERC721Storage.load().symbol;\n }\n\n /**\n * @inheritdoc IERC721Metadata\n */\n function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {\n if (!_exists(tokenId)) {\n revert TokenDoesNotExist(tokenId);\n }\n\n string memory baseURI = ERC721Storage.load().baseTokenURI;\n\n return\n bytes(baseURI).length > 0\n ? string(abi.encodePacked(baseURI, StringUtil.uintToString(tokenId)))\n : \"\";\n }\n\n /**\n * @inheritdoc IERC721\n */\n function approve(address to, uint256 tokenId) public virtual override {\n ERC721Storage.Data storage store = ERC721Storage.load();\n address holder = store.ownerOf[tokenId];\n\n if (to == holder) {\n revert CannotSelfApprove(to);\n }\n\n if (msg.sender != holder && !isApprovedForAll(holder, msg.sender)) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n _approve(to, tokenId);\n }\n\n /**\n * @inheritdoc IERC721\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n if (!_exists(tokenId)) {\n revert TokenDoesNotExist(tokenId);\n }\n\n return ERC721Storage.load().tokenApprovals[tokenId];\n }\n\n /**\n * @inheritdoc IERC721\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n if (msg.sender == operator) {\n revert CannotSelfApprove(operator);\n }\n\n ERC721Storage.load().operatorApprovals[msg.sender][operator] = approved;\n\n emit ApprovalForAll(msg.sender, operator, approved);\n }\n\n /**\n * @inheritdoc IERC721\n */\n function isApprovedForAll(\n address holder,\n address operator\n ) public view virtual override returns (bool) {\n return ERC721Storage.load().operatorApprovals[holder][operator];\n }\n\n /**\n * @inheritdoc IERC721\n */\n function transferFrom(address from, address to, uint256 tokenId) public virtual override {\n if (!_isApprovedOrOwner(msg.sender, tokenId)) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @inheritdoc IERC721\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @inheritdoc IERC721\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n if (!_isApprovedOrOwner(msg.sender, tokenId)) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n _transfer(from, to, tokenId);\n if (!_checkOnERC721Received(from, to, tokenId, data)) {\n revert InvalidTransferRecipient(to);\n }\n }\n\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return ERC721Storage.load().ownerOf[tokenId] != address(0);\n }\n\n function _isApprovedOrOwner(\n address spender,\n uint256 tokenId\n ) internal view virtual returns (bool) {\n address holder = ownerOf(tokenId);\n\n // Not checking tokenId existence since it is checked in ownerOf() and getApproved()\n\n return (spender == holder ||\n getApproved(tokenId) == spender ||\n isApprovedForAll(holder, spender));\n }\n\n function _mint(address to, uint256 tokenId) internal virtual {\n ERC721Storage.Data storage store = ERC721Storage.load();\n if (to == address(0)) {\n revert AddressError.ZeroAddress();\n }\n\n if (tokenId == 0) {\n revert ParameterError.InvalidParameter(\"tokenId\", \"cannot be zero\");\n }\n\n if (_exists(tokenId)) {\n revert TokenAlreadyMinted(tokenId);\n }\n\n _beforeTransfer(address(0), to, tokenId);\n\n store.balanceOf[to] += 1;\n store.ownerOf[tokenId] = to;\n\n _postTransfer(address(0), to, tokenId);\n\n emit Transfer(address(0), to, tokenId);\n }\n\n function _burn(uint256 tokenId) internal virtual {\n ERC721Storage.Data storage store = ERC721Storage.load();\n address holder = store.ownerOf[tokenId];\n\n _approve(address(0), tokenId);\n\n _beforeTransfer(holder, address(0), tokenId);\n\n store.balanceOf[holder] -= 1;\n delete store.ownerOf[tokenId];\n\n _postTransfer(holder, address(0), tokenId);\n\n emit Transfer(holder, address(0), tokenId);\n }\n\n function _transfer(address from, address to, uint256 tokenId) internal virtual {\n ERC721Storage.Data storage store = ERC721Storage.load();\n\n if (ownerOf(tokenId) != from) {\n revert AccessError.Unauthorized(from);\n }\n\n if (to == address(0)) {\n revert AddressError.ZeroAddress();\n }\n\n _beforeTransfer(from, to, tokenId);\n\n // Clear approvals from the previous holder\n _approve(address(0), tokenId);\n\n store.balanceOf[from] -= 1;\n store.balanceOf[to] += 1;\n store.ownerOf[tokenId] = to;\n\n _postTransfer(from, to, tokenId);\n\n emit Transfer(from, to, tokenId);\n }\n\n function _approve(address to, uint256 tokenId) internal virtual {\n ERC721Storage.load().tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal returns (bool) {\n if (AddressUtil.isContract(to)) {\n try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) returns (\n bytes4 retval\n ) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch {\n return false;\n }\n } else {\n return true;\n }\n }\n\n function _beforeTransfer(\n address from,\n address to,\n uint256 tokenId // solhint-disable-next-line no-empty-blocks\n ) internal virtual {}\n\n function _postTransfer(\n address from,\n address to,\n uint256 tokenId // solhint-disable-next-line no-empty-blocks\n ) internal virtual {}\n\n function _initialize(\n string memory tokenName,\n string memory tokenSymbol,\n string memory baseTokenURI\n ) internal virtual {\n ERC721Storage.Data storage store = ERC721Storage.load();\n if (\n bytes(store.name).length > 0 ||\n bytes(store.symbol).length > 0 ||\n bytes(store.baseTokenURI).length > 0\n ) {\n revert InitError.AlreadyInitialized();\n }\n\n if (bytes(tokenName).length == 0 || bytes(tokenSymbol).length == 0) {\n revert ParameterError.InvalidParameter(\"name/symbol\", \"must not be empty\");\n }\n\n store.name = tokenName;\n store.symbol = tokenSymbol;\n store.baseTokenURI = baseTokenURI;\n }\n}\n" }, "@synthetixio/core-contracts/contracts/token/ERC721Enumerable.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./ERC721.sol\";\nimport \"./ERC721EnumerableStorage.sol\";\nimport \"../interfaces/IERC721Enumerable.sol\";\n\n/*\n * @title ERC721 extension with helper functions that allow the enumeration of NFT tokens.\n * See IERC721Enumerable\n *\n * Reference implementations:\n * - OpenZeppelin - https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/extensions/ERC721EnumerableStorage.sol\n */\nabstract contract ERC721Enumerable is ERC721, IERC721Enumerable {\n /**\n * @inheritdoc IERC165\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return\n super.supportsInterface(interfaceId) ||\n interfaceId == type(IERC721Enumerable).interfaceId;\n }\n\n /**\n * @inheritdoc IERC721Enumerable\n */\n function tokenOfOwnerByIndex(\n address owner,\n uint256 index\n ) public view virtual override returns (uint256) {\n if (ERC721.balanceOf(owner) <= index) {\n revert IndexOverrun(index, ERC721.balanceOf(owner));\n }\n return ERC721EnumerableStorage.load().ownedTokens[owner][index];\n }\n\n /**\n * @inheritdoc IERC721Enumerable\n */\n function totalSupply() public view virtual override returns (uint256) {\n return ERC721EnumerableStorage.load().allTokens.length;\n }\n\n /**\n * @dev Returns the total amount of tokens stored by the contract.\n */\n function tokenByIndex(uint256 index) public view virtual override returns (uint256) {\n if (index >= ERC721Enumerable.totalSupply()) {\n revert IndexOverrun(index, ERC721Enumerable.totalSupply());\n }\n return ERC721EnumerableStorage.load().allTokens[index];\n }\n\n function _beforeTransfer(address from, address to, uint256 tokenId) internal virtual override {\n if (from == address(0)) {\n _addTokenToAllTokensEnumeration(tokenId);\n } else if (from != to) {\n _removeTokenFromOwnerEnumeration(from, tokenId);\n }\n if (to == address(0)) {\n _removeTokenFromAllTokensEnumeration(tokenId);\n } else if (to != from) {\n _addTokenToOwnerEnumeration(to, tokenId);\n }\n }\n\n function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\n uint256 length = ERC721.balanceOf(to);\n ERC721EnumerableStorage.load().ownedTokens[to][length] = tokenId;\n ERC721EnumerableStorage.load().ownedTokensIndex[tokenId] = length;\n }\n\n /**\n * @dev Private function to add a token to this extension's token tracking data structures.\n * @param tokenId uint256 ID of the token to be added to the tokens list\n */\n function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\n ERC721EnumerableStorage.load().allTokensIndex[tokenId] = ERC721EnumerableStorage\n .load()\n .allTokens\n .length;\n ERC721EnumerableStorage.load().allTokens.push(tokenId);\n }\n\n /**\n * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\n * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\n * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\n * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n * @param from address representing the previous owner of the given token ID\n * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n */\n function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {\n // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;\n uint256 tokenIndex = ERC721EnumerableStorage.load().ownedTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary\n if (tokenIndex != lastTokenIndex) {\n uint256 lastTokenId = ERC721EnumerableStorage.load().ownedTokens[from][lastTokenIndex];\n\n ERC721EnumerableStorage.load().ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n ERC721EnumerableStorage.load().ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n }\n\n // This also deletes the contents at the last position of the array\n delete ERC721EnumerableStorage.load().ownedTokensIndex[tokenId];\n delete ERC721EnumerableStorage.load().ownedTokens[from][lastTokenIndex];\n }\n\n /**\n * @dev Private function to remove a token from this extension's token tracking data structures.\n * This has O(1) time complexity, but alters the order of the _allTokens array.\n * @param tokenId uint256 ID of the token to be removed from the tokens list\n */\n function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\n // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = ERC721EnumerableStorage.load().allTokens.length - 1;\n uint256 tokenIndex = ERC721EnumerableStorage.load().allTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\n // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\n // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\n uint256 lastTokenId = ERC721EnumerableStorage.load().allTokens[lastTokenIndex];\n\n ERC721EnumerableStorage.load().allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n ERC721EnumerableStorage.load().allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n\n // This also deletes the contents at the last position of the array\n delete ERC721EnumerableStorage.load().allTokensIndex[tokenId];\n ERC721EnumerableStorage.load().allTokens.pop();\n }\n\n function _initialize(\n string memory tokenName,\n string memory tokenSymbol,\n string memory baseTokenURI\n ) internal virtual override {\n super._initialize(tokenName, tokenSymbol, baseTokenURI);\n if (ERC721EnumerableStorage.load().allTokens.length > 0) {\n revert InitError.AlreadyInitialized();\n }\n }\n}\n" }, "@synthetixio/core-contracts/contracts/token/ERC721EnumerableStorage.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nlibrary ERC721EnumerableStorage {\n bytes32 private constant _SLOT_ERC721_ENUMERABLE_STORAGE =\n keccak256(abi.encode(\"io.synthetix.core-contracts.ERC721Enumerable\"));\n\n struct Data {\n mapping(uint256 => uint256) ownedTokensIndex;\n mapping(uint256 => uint256) allTokensIndex;\n mapping(address => mapping(uint256 => uint256)) ownedTokens;\n uint256[] allTokens;\n }\n\n function load() internal pure returns (Data storage store) {\n bytes32 s = _SLOT_ERC721_ENUMERABLE_STORAGE;\n assembly {\n store.slot := s\n }\n }\n}\n" }, "@synthetixio/core-contracts/contracts/token/ERC721Storage.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nlibrary ERC721Storage {\n bytes32 private constant _SLOT_ERC721_STORAGE =\n keccak256(abi.encode(\"io.synthetix.core-contracts.ERC721\"));\n\n struct Data {\n string name;\n string symbol;\n string baseTokenURI;\n mapping(uint256 => address) ownerOf;\n mapping(address => uint256) balanceOf;\n mapping(uint256 => address) tokenApprovals;\n mapping(address => mapping(address => bool)) operatorApprovals;\n }\n\n function load() internal pure returns (Data storage store) {\n bytes32 s = _SLOT_ERC721_STORAGE;\n assembly {\n store.slot := s\n }\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/AddressUtil.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nlibrary AddressUtil {\n function isContract(address account) internal view returns (bool) {\n uint256 size;\n\n assembly {\n size := extcodesize(account)\n }\n\n return size > 0;\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/DecimalMath.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./SafeCast.sol\";\n\n/**\n * @title Utility library used to represent \"decimals\" (fixed point numbers) with integers, with two different levels of precision.\n *\n * They are represented by N * UNIT, where UNIT is the number of decimals of precision in the representation.\n *\n * Examples:\n * 1) Given UNIT = 100\n * then if A = 50, A represents the decimal 0.50\n * 2) Given UNIT = 1000000000000000000\n * then if A = 500000000000000000, A represents the decimal 0.500000000000000000\n *\n * Note: An accompanying naming convention of the postfix \"D\" is helpful with this utility. I.e. if a variable \"myValue\" represents a low resolution decimal, it should be named \"myValueD18\", and if it was a high resolution decimal \"myValueD27\". While scaling, intermediate precision decimals like \"myValue45\" could arise. Non-decimals should have no postfix, i.e. just \"myValue\".\n *\n * Important: Multiplication and division operations are currently not supported for high precision decimals. Using these operations on them will yield incorrect results and fail silently.\n */\nlibrary DecimalMath {\n using SafeCastU256 for uint256;\n using SafeCastI256 for int256;\n\n // solhint-disable numcast/safe-cast\n\n // Numbers representing 1.0 (low precision).\n uint256 public constant UNIT = 1e18;\n int256 public constant UNIT_INT = int256(UNIT);\n uint128 public constant UNIT_UINT128 = uint128(UNIT);\n int128 public constant UNIT_INT128 = int128(UNIT_INT);\n\n // Numbers representing 1.0 (high precision).\n uint256 public constant UNIT_PRECISE = 1e27;\n int256 public constant UNIT_PRECISE_INT = int256(UNIT_PRECISE);\n int128 public constant UNIT_PRECISE_INT128 = int128(UNIT_PRECISE_INT);\n\n // Precision scaling, (used to scale down/up from one precision to the other).\n uint256 public constant PRECISION_FACTOR = 9; // 27 - 18 = 9 :)\n\n // solhint-enable numcast/safe-cast\n\n // -----------------\n // uint256\n // -----------------\n\n /**\n * @dev Multiplies two low precision decimals.\n *\n * Since the two numbers are assumed to be fixed point numbers,\n * (x * UNIT) * (y * UNIT) = x * y * UNIT ^ 2,\n * the result is divided by UNIT to remove double scaling.\n */\n function mulDecimal(uint256 x, uint256 y) internal pure returns (uint256 z) {\n return (x * y) / UNIT;\n }\n\n /**\n * @dev Divides two low precision decimals.\n *\n * Since the two numbers are assumed to be fixed point numbers,\n * (x * UNIT) / (y * UNIT) = x / y (Decimal representation is lost),\n * x is first scaled up to end up with a decimal representation.\n */\n function divDecimal(uint256 x, uint256 y) internal pure returns (uint256 z) {\n return (x * UNIT) / y;\n }\n\n /**\n * @dev Scales up a value.\n *\n * E.g. if value is not a decimal, a scale up by 18 makes it a low precision decimal.\n * If value is a low precision decimal, a scale up by 9 makes it a high precision decimal.\n */\n function upscale(uint x, uint factor) internal pure returns (uint) {\n return x * 10 ** factor;\n }\n\n /**\n * @dev Scales down a value.\n *\n * E.g. if value is a high precision decimal, a scale down by 9 makes it a low precision decimal.\n * If value is a low precision decimal, a scale down by 9 makes it a regular integer.\n *\n * Scaling down a regular integer would not make sense.\n */\n function downscale(uint x, uint factor) internal pure returns (uint) {\n return x / 10 ** factor;\n }\n\n // -----------------\n // uint128\n // -----------------\n\n // Note: Overloading doesn't seem to work for similar types, i.e. int256 and int128, uint256 and uint128, etc, so explicitly naming the functions differently here.\n\n /**\n * @dev See mulDecimal for uint256.\n */\n function mulDecimalUint128(uint128 x, uint128 y) internal pure returns (uint128) {\n return (x * y) / UNIT_UINT128;\n }\n\n /**\n * @dev See divDecimal for uint256.\n */\n function divDecimalUint128(uint128 x, uint128 y) internal pure returns (uint128) {\n return (x * UNIT_UINT128) / y;\n }\n\n /**\n * @dev See upscale for uint256.\n */\n function upscaleUint128(uint128 x, uint factor) internal pure returns (uint128) {\n return x * (10 ** factor).to128();\n }\n\n /**\n * @dev See downscale for uint256.\n */\n function downscaleUint128(uint128 x, uint factor) internal pure returns (uint128) {\n return x / (10 ** factor).to128();\n }\n\n // -----------------\n // int256\n // -----------------\n\n /**\n * @dev See mulDecimal for uint256.\n */\n function mulDecimal(int256 x, int256 y) internal pure returns (int256) {\n return (x * y) / UNIT_INT;\n }\n\n /**\n * @dev See divDecimal for uint256.\n */\n function divDecimal(int256 x, int256 y) internal pure returns (int256) {\n return (x * UNIT_INT) / y;\n }\n\n /**\n * @dev See upscale for uint256.\n */\n function upscale(int x, uint factor) internal pure returns (int) {\n return x * (10 ** factor).toInt();\n }\n\n /**\n * @dev See downscale for uint256.\n */\n function downscale(int x, uint factor) internal pure returns (int) {\n return x / (10 ** factor).toInt();\n }\n\n // -----------------\n // int128\n // -----------------\n\n /**\n * @dev See mulDecimal for uint256.\n */\n function mulDecimalInt128(int128 x, int128 y) internal pure returns (int128) {\n return (x * y) / UNIT_INT128;\n }\n\n /**\n * @dev See divDecimal for uint256.\n */\n function divDecimalInt128(int128 x, int128 y) internal pure returns (int128) {\n return (x * UNIT_INT128) / y;\n }\n\n /**\n * @dev See upscale for uint256.\n */\n function upscaleInt128(int128 x, uint factor) internal pure returns (int128) {\n return x * ((10 ** factor).toInt()).to128();\n }\n\n /**\n * @dev See downscale for uint256.\n */\n function downscaleInt128(int128 x, uint factor) internal pure returns (int128) {\n return x / ((10 ** factor).toInt().to128());\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/ERC165Helper.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../interfaces/IERC165.sol\";\n\nlibrary ERC165Helper {\n function safeSupportsInterface(\n address candidate,\n bytes4 interfaceID\n ) internal returns (bool supportsInterface) {\n (bool success, bytes memory response) = candidate.call(\n abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceID)\n );\n\n if (!success) {\n return false;\n }\n\n if (response.length == 0) {\n return false;\n }\n\n assembly {\n supportsInterface := mload(add(response, 32))\n }\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/HeapUtil.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n// Eth Heap\n// Author: Zac Mitton\n// License: MIT\n\nlibrary HeapUtil {\n // default max-heap\n\n uint private constant _ROOT_INDEX = 1;\n\n struct Data {\n uint128 idCount;\n Node[] nodes; // root is index 1; index 0 not used\n mapping(uint128 => uint) indices; // unique id => node index\n }\n struct Node {\n uint128 id; //use with another mapping to store arbitrary object types\n int128 priority;\n }\n\n //call init before anything else\n function init(Data storage self) internal {\n if (self.nodes.length == 0) self.nodes.push(Node(0, 0));\n }\n\n function insert(Data storage self, uint128 id, int128 priority) internal returns (Node memory) {\n //√\n if (self.nodes.length == 0) {\n init(self);\n } // test on-the-fly-init\n\n Node memory n;\n\n // MODIFIED: support updates\n extractById(self, id);\n\n self.idCount++;\n self.nodes.push();\n n = Node(id, priority);\n _bubbleUp(self, n, self.nodes.length - 1);\n\n return n;\n }\n\n function extractMax(Data storage self) internal returns (Node memory) {\n //√\n return _extract(self, _ROOT_INDEX);\n }\n\n function extractById(Data storage self, uint128 id) internal returns (Node memory) {\n //√\n return _extract(self, self.indices[id]);\n }\n\n //view\n function dump(Data storage self) internal view returns (Node[] memory) {\n //note: Empty set will return `[Node(0,0)]`. uninitialized will return `[]`.\n return self.nodes;\n }\n\n function getById(Data storage self, uint128 id) internal view returns (Node memory) {\n return getByIndex(self, self.indices[id]); //test that all these return the emptyNode\n }\n\n function getByIndex(Data storage self, uint i) internal view returns (Node memory) {\n return self.nodes.length > i ? self.nodes[i] : Node(0, 0);\n }\n\n function getMax(Data storage self) internal view returns (Node memory) {\n return getByIndex(self, _ROOT_INDEX);\n }\n\n function size(Data storage self) internal view returns (uint) {\n return self.nodes.length > 0 ? self.nodes.length - 1 : 0;\n }\n\n function isNode(Node memory n) internal pure returns (bool) {\n return n.id > 0;\n }\n\n //private\n function _extract(Data storage self, uint i) private returns (Node memory) {\n //√\n if (self.nodes.length <= i || i <= 0) {\n return Node(0, 0);\n }\n\n Node memory extractedNode = self.nodes[i];\n delete self.indices[extractedNode.id];\n\n Node memory tailNode = self.nodes[self.nodes.length - 1];\n self.nodes.pop();\n\n if (i < self.nodes.length) {\n // if extracted node was not tail\n _bubbleUp(self, tailNode, i);\n _bubbleDown(self, self.nodes[i], i); // then try bubbling down\n }\n return extractedNode;\n }\n\n function _bubbleUp(Data storage self, Node memory n, uint i) private {\n //√\n if (i == _ROOT_INDEX || n.priority <= self.nodes[i / 2].priority) {\n _insert(self, n, i);\n } else {\n _insert(self, self.nodes[i / 2], i);\n _bubbleUp(self, n, i / 2);\n }\n }\n\n function _bubbleDown(Data storage self, Node memory n, uint i) private {\n //\n uint length = self.nodes.length;\n uint cIndex = i * 2; // left child index\n\n if (length <= cIndex) {\n _insert(self, n, i);\n } else {\n Node memory largestChild = self.nodes[cIndex];\n\n if (length > cIndex + 1 && self.nodes[cIndex + 1].priority > largestChild.priority) {\n largestChild = self.nodes[++cIndex]; // TEST ++ gets executed first here\n }\n\n if (largestChild.priority <= n.priority) {\n //TEST: priority 0 is valid! negative ints work\n _insert(self, n, i);\n } else {\n _insert(self, largestChild, i);\n _bubbleDown(self, n, cIndex);\n }\n }\n }\n\n function _insert(Data storage self, Node memory n, uint i) private {\n //√\n self.nodes[i] = n;\n self.indices[n.id] = i;\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * Utilities that convert numeric types avoiding silent overflows.\n */\nimport \"./SafeCast/SafeCastU32.sol\";\nimport \"./SafeCast/SafeCastI32.sol\";\nimport \"./SafeCast/SafeCastI24.sol\";\nimport \"./SafeCast/SafeCastU56.sol\";\nimport \"./SafeCast/SafeCastI56.sol\";\nimport \"./SafeCast/SafeCastU64.sol\";\nimport \"./SafeCast/SafeCastI128.sol\";\nimport \"./SafeCast/SafeCastI256.sol\";\nimport \"./SafeCast/SafeCastU128.sol\";\nimport \"./SafeCast/SafeCastU160.sol\";\nimport \"./SafeCast/SafeCastU256.sol\";\nimport \"./SafeCast/SafeCastAddress.sol\";\nimport \"./SafeCast/SafeCastBytes32.sol\";\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastAddress.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastAddress {\n function toBytes32(address x) internal pure returns (bytes32) {\n return bytes32(uint256(uint160(x)));\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastBytes32.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastBytes32 {\n function toAddress(bytes32 x) internal pure returns (address) {\n return address(uint160(uint256(x)));\n }\n\n function toUint(bytes32 x) internal pure returns (uint) {\n return uint(x);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastI128.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastI128 {\n error OverflowInt128ToUint128();\n error OverflowInt128ToInt32();\n\n function toUint(int128 x) internal pure returns (uint128) {\n // ----------------<==============o==============>-----------------\n // ----------------xxxxxxxxxxxxxxxo===============>----------------\n if (x < 0) {\n revert OverflowInt128ToUint128();\n }\n\n return uint128(x);\n }\n\n function to256(int128 x) internal pure returns (int256) {\n return int256(x);\n }\n\n function to32(int128 x) internal pure returns (int32) {\n // ----------------<==============o==============>-----------------\n // ----------------xxxxxxxxxxxx<==o==>xxxxxxxxxxxx-----------------\n if (x < int(type(int32).min) || x > int(type(int32).max)) {\n revert OverflowInt128ToInt32();\n }\n\n return int32(x);\n }\n\n function zero() internal pure returns (int128) {\n return int128(0);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastI24.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastI24 {\n function to256(int24 x) internal pure returns (int256) {\n return int256(x);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastI256.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastI256 {\n error OverflowInt256ToUint256();\n error OverflowInt256ToInt128();\n error OverflowInt256ToInt24();\n\n function to128(int256 x) internal pure returns (int128) {\n // ----<==========================o===========================>----\n // ----xxxxxxxxxxxx<==============o==============>xxxxxxxxxxxxx----\n if (x < int256(type(int128).min) || x > int256(type(int128).max)) {\n revert OverflowInt256ToInt128();\n }\n\n return int128(x);\n }\n\n function to24(int256 x) internal pure returns (int24) {\n // ----<==========================o===========================>----\n // ----xxxxxxxxxxxxxxxxxxxx<======o=======>xxxxxxxxxxxxxxxxxxxx----\n if (x < int256(type(int24).min) || x > int256(type(int24).max)) {\n revert OverflowInt256ToInt24();\n }\n\n return int24(x);\n }\n\n function toUint(int256 x) internal pure returns (uint256) {\n // ----<==========================o===========================>----\n // ----xxxxxxxxxxxxxxxxxxxxxxxxxxxo===============================>\n if (x < 0) {\n revert OverflowInt256ToUint256();\n }\n\n return uint256(x);\n }\n\n function zero() internal pure returns (int256) {\n return int256(0);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastI32.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastI32 {\n error OverflowInt32ToUint32();\n\n function toUint(int32 x) internal pure returns (uint32) {\n // ----------------------<========o========>----------------------\n // ----------------------xxxxxxxxxo=========>----------------------\n if (x < 0) {\n revert OverflowInt32ToUint32();\n }\n\n return uint32(x);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastI56.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastI56 {\n error OverflowInt56ToInt24();\n\n function to24(int56 x) internal pure returns (int24) {\n // ----------------------<========o========>-----------------------\n // ----------------------xxx<=====o=====>xxx-----------------------\n if (x < int(type(int24).min) || x > int(type(int24).max)) {\n revert OverflowInt56ToInt24();\n }\n\n return int24(x);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastU128.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastU128 {\n error OverflowUint128ToInt128();\n\n function to256(uint128 x) internal pure returns (uint256) {\n return uint256(x);\n }\n\n function toInt(uint128 x) internal pure returns (int128) {\n // -------------------------------o===============>----------------\n // ----------------<==============o==============>x----------------\n if (x > uint128(type(int128).max)) {\n revert OverflowUint128ToInt128();\n }\n\n return int128(x);\n }\n\n function toBytes32(uint128 x) internal pure returns (bytes32) {\n return bytes32(uint256(x));\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastU160.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastU160 {\n function to256(uint160 x) internal pure returns (uint256) {\n return uint256(x);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastU256.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastU256 {\n error OverflowUint256ToUint128();\n error OverflowUint256ToInt256();\n error OverflowUint256ToUint64();\n error OverflowUint256ToUint32();\n error OverflowUint256ToUint160();\n\n function to128(uint256 x) internal pure returns (uint128) {\n // -------------------------------o===============================>\n // -------------------------------o===============>xxxxxxxxxxxxxxxx\n if (x > type(uint128).max) {\n revert OverflowUint256ToUint128();\n }\n\n return uint128(x);\n }\n\n function to64(uint256 x) internal pure returns (uint64) {\n // -------------------------------o===============================>\n // -------------------------------o======>xxxxxxxxxxxxxxxxxxxxxxxxx\n if (x > type(uint64).max) {\n revert OverflowUint256ToUint64();\n }\n\n return uint64(x);\n }\n\n function to32(uint256 x) internal pure returns (uint32) {\n // -------------------------------o===============================>\n // -------------------------------o===>xxxxxxxxxxxxxxxxxxxxxxxxxxxx\n if (x > type(uint32).max) {\n revert OverflowUint256ToUint32();\n }\n\n return uint32(x);\n }\n\n function to160(uint256 x) internal pure returns (uint160) {\n // -------------------------------o===============================>\n // -------------------------------o==================>xxxxxxxxxxxxx\n if (x > type(uint160).max) {\n revert OverflowUint256ToUint160();\n }\n\n return uint160(x);\n }\n\n function toBytes32(uint256 x) internal pure returns (bytes32) {\n return bytes32(x);\n }\n\n function toInt(uint256 x) internal pure returns (int256) {\n // -------------------------------o===============================>\n // ----<==========================o===========================>xxxx\n if (x > uint256(type(int256).max)) {\n revert OverflowUint256ToInt256();\n }\n\n return int256(x);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastU32.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastU32 {\n error OverflowUint32ToInt32();\n\n function toInt(uint32 x) internal pure returns (int32) {\n // -------------------------------o=========>----------------------\n // ----------------------<========o========>x----------------------\n if (x > uint32(type(int32).max)) {\n revert OverflowUint32ToInt32();\n }\n\n return int32(x);\n }\n\n function to256(uint32 x) internal pure returns (uint256) {\n return uint256(x);\n }\n\n function to56(uint32 x) internal pure returns (uint56) {\n return uint56(x);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastU56.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastU56 {\n error OverflowUint56ToInt56();\n\n function toInt(uint56 x) internal pure returns (int56) {\n // -------------------------------o=========>----------------------\n // ----------------------<========o========>x----------------------\n if (x > uint56(type(int56).max)) {\n revert OverflowUint56ToInt56();\n }\n\n return int56(x);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SafeCast/SafeCastU64.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title See SafeCast.sol.\n */\nlibrary SafeCastU64 {\n error OverflowUint64ToInt64();\n\n function toInt(uint64 x) internal pure returns (int64) {\n // -------------------------------o=========>----------------------\n // ----------------------<========o========>x----------------------\n if (x > uint64(type(int64).max)) {\n revert OverflowUint64ToInt64();\n }\n\n return int64(x);\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/SetUtil.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./SafeCast.sol\";\n\nlibrary SetUtil {\n using SafeCastAddress for address;\n using SafeCastBytes32 for bytes32;\n using SafeCastU256 for uint256;\n\n // ----------------------------------------\n // Uint support\n // ----------------------------------------\n\n struct UintSet {\n Bytes32Set raw;\n }\n\n function add(UintSet storage set, uint value) internal {\n add(set.raw, value.toBytes32());\n }\n\n function remove(UintSet storage set, uint value) internal {\n remove(set.raw, value.toBytes32());\n }\n\n function replace(UintSet storage set, uint value, uint newValue) internal {\n replace(set.raw, value.toBytes32(), newValue.toBytes32());\n }\n\n function contains(UintSet storage set, uint value) internal view returns (bool) {\n return contains(set.raw, value.toBytes32());\n }\n\n function length(UintSet storage set) internal view returns (uint) {\n return length(set.raw);\n }\n\n function valueAt(UintSet storage set, uint position) internal view returns (uint) {\n return valueAt(set.raw, position).toUint();\n }\n\n function positionOf(UintSet storage set, uint value) internal view returns (uint) {\n return positionOf(set.raw, value.toBytes32());\n }\n\n function values(UintSet storage set) internal view returns (uint[] memory) {\n bytes32[] memory store = values(set.raw);\n uint[] memory result;\n\n assembly {\n result := store\n }\n\n return result;\n }\n\n // ----------------------------------------\n // Address support\n // ----------------------------------------\n\n struct AddressSet {\n Bytes32Set raw;\n }\n\n function add(AddressSet storage set, address value) internal {\n add(set.raw, value.toBytes32());\n }\n\n function remove(AddressSet storage set, address value) internal {\n remove(set.raw, value.toBytes32());\n }\n\n function replace(AddressSet storage set, address value, address newValue) internal {\n replace(set.raw, value.toBytes32(), newValue.toBytes32());\n }\n\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return contains(set.raw, value.toBytes32());\n }\n\n function length(AddressSet storage set) internal view returns (uint) {\n return length(set.raw);\n }\n\n function valueAt(AddressSet storage set, uint position) internal view returns (address) {\n return valueAt(set.raw, position).toAddress();\n }\n\n function positionOf(AddressSet storage set, address value) internal view returns (uint) {\n return positionOf(set.raw, value.toBytes32());\n }\n\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = values(set.raw);\n address[] memory result;\n\n assembly {\n result := store\n }\n\n return result;\n }\n\n // ----------------------------------------\n // Core bytes32 support\n // ----------------------------------------\n\n error PositionOutOfBounds();\n error ValueNotInSet();\n error ValueAlreadyInSet();\n\n struct Bytes32Set {\n bytes32[] _values;\n mapping(bytes32 => uint) _positions; // Position zero is never used.\n }\n\n function add(Bytes32Set storage set, bytes32 value) internal {\n if (contains(set, value)) {\n revert ValueAlreadyInSet();\n }\n\n set._values.push(value);\n set._positions[value] = set._values.length;\n }\n\n function remove(Bytes32Set storage set, bytes32 value) internal {\n uint position = set._positions[value];\n if (position == 0) {\n revert ValueNotInSet();\n }\n\n uint index = position - 1;\n uint lastIndex = set._values.length - 1;\n\n // If the element being deleted is not the last in the values,\n // move the last element to its position.\n if (index != lastIndex) {\n bytes32 lastValue = set._values[lastIndex];\n\n set._values[index] = lastValue;\n set._positions[lastValue] = position;\n }\n\n // Remove the last element in the values.\n set._values.pop();\n delete set._positions[value];\n }\n\n function replace(Bytes32Set storage set, bytes32 value, bytes32 newValue) internal {\n if (!contains(set, value)) {\n revert ValueNotInSet();\n }\n\n if (contains(set, newValue)) {\n revert ValueAlreadyInSet();\n }\n\n uint position = set._positions[value];\n delete set._positions[value];\n\n uint index = position - 1;\n\n set._values[index] = newValue;\n set._positions[newValue] = position;\n }\n\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return set._positions[value] != 0;\n }\n\n function length(Bytes32Set storage set) internal view returns (uint) {\n return set._values.length;\n }\n\n function valueAt(Bytes32Set storage set, uint position) internal view returns (bytes32) {\n if (position == 0 || position > set._values.length) {\n revert PositionOutOfBounds();\n }\n\n uint index = position - 1;\n\n return set._values[index];\n }\n\n function positionOf(Bytes32Set storage set, bytes32 value) internal view returns (uint) {\n if (!contains(set, value)) {\n revert ValueNotInSet();\n }\n\n return set._positions[value];\n }\n\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n return set._values;\n }\n}\n" }, "@synthetixio/core-contracts/contracts/utils/StringUtil.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/*\n Reference implementations:\n * OpenZeppelin - https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol\n*/\n\nlibrary StringUtil {\n function uintToString(uint value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0\";\n }\n\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n // solhint-disable-next-line numcast/safe-cast\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n\n return string(buffer);\n }\n}\n" }, "@synthetixio/core-modules/contracts/interfaces/IAssociatedSystemsModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module for connecting a system with other associated systems.\n\n * Associated systems become available to all system modules for communication and interaction, but as opposed to inter-modular communications, interactions with associated systems will require the use of `CALL`.\n *\n * Associated systems can be managed or unmanaged.\n * - Managed systems are connected via a proxy, which means that their implementation can be updated, and the system controls the execution context of the associated system. Example, an snxUSD token connected to the system, and controlled by the system.\n * - Unmanaged systems are just addresses tracked by the system, for which it has no control whatsoever. Example, Uniswap v3, Curve, etc.\n *\n * Furthermore, associated systems are typed in the AssociatedSystem utility library (See AssociatedSystem.sol):\n * - KIND_ERC20: A managed associated system specifically wrapping an ERC20 implementation.\n * - KIND_ERC721: A managed associated system specifically wrapping an ERC721 implementation.\n * - KIND_UNMANAGED: Any unmanaged associated system.\n */\ninterface IAssociatedSystemsModule {\n /**\n * @notice Emitted when an associated system is set.\n * @param kind The type of associated system (managed ERC20, managed ERC721, unmanaged, etc - See the AssociatedSystem util).\n * @param id The bytes32 identifier of the associated system.\n * @param proxy The main external contract address of the associated system.\n * @param impl The address of the implementation of the associated system (if not behind a proxy, will equal `proxy`).\n */\n event AssociatedSystemSet(\n bytes32 indexed kind,\n bytes32 indexed id,\n address proxy,\n address impl\n );\n\n /**\n * @notice Emitted when the function you are calling requires an associated system, but it\n * has not been registered\n */\n error MissingAssociatedSystem(bytes32 id);\n\n /**\n * @notice Creates or initializes a managed associated ERC20 token.\n * @param id The bytes32 identifier of the associated system. If the id is new to the system, it will create a new proxy for the associated system.\n * @param name The token name that will be used to initialize the proxy.\n * @param symbol The token symbol that will be used to initialize the proxy.\n * @param decimals The token decimals that will be used to initialize the proxy.\n * @param impl The ERC20 implementation of the proxy.\n */\n function initOrUpgradeToken(\n bytes32 id,\n string memory name,\n string memory symbol,\n uint8 decimals,\n address impl\n ) external;\n\n /**\n * @notice Creates or initializes a managed associated ERC721 token.\n * @param id The bytes32 identifier of the associated system. If the id is new to the system, it will create a new proxy for the associated system.\n * @param name The token name that will be used to initialize the proxy.\n * @param symbol The token symbol that will be used to initialize the proxy.\n * @param uri The token uri that will be used to initialize the proxy.\n * @param impl The ERC721 implementation of the proxy.\n */\n function initOrUpgradeNft(\n bytes32 id,\n string memory name,\n string memory symbol,\n string memory uri,\n address impl\n ) external;\n\n /**\n * @notice Registers an unmanaged external contract in the system.\n * @param id The bytes32 identifier to use to reference the associated system.\n * @param endpoint The address of the associated system.\n *\n * Note: The system will not be able to control or upgrade the associated system, only communicate with it.\n */\n function registerUnmanagedSystem(bytes32 id, address endpoint) external;\n\n /**\n * @notice Retrieves an associated system.\n * @param id The bytes32 identifier used to reference the associated system.\n * @return addr The external contract address of the associated system.\n * @return kind The type of associated system (managed ERC20, managed ERC721, unmanaged, etc - See the AssociatedSystem util).\n */\n function getAssociatedSystem(bytes32 id) external view returns (address addr, bytes32 kind);\n}\n" }, "@synthetixio/core-modules/contracts/interfaces/IFeatureFlagModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module for granular enabling and disabling of system features and functions.\n *\n * Interface functions that are controlled by a feature flag simply need to add this line to their body:\n * `FeatureFlag.ensureAccessToFeature(FLAG_ID);`\n *\n * If such a line is not present in a function, then it is not controlled by a feature flag.\n *\n * If a feature flag is set and then removed forever, consider deleting the line mentioned above from the function's body.\n */\ninterface IFeatureFlagModule {\n /**\n * @notice Emitted when general access has been given or removed for a feature.\n * @param feature The bytes32 id of the feature.\n * @param allowAll True if the feature was allowed for everyone and false if it is only allowed for those included in the allowlist.\n */\n event FeatureFlagAllowAllSet(bytes32 indexed feature, bool allowAll);\n\n /**\n * @notice Emitted when general access has been blocked for a feature.\n * @param feature The bytes32 id of the feature.\n * @param denyAll True if the feature was blocked for everyone and false if it is only allowed for those included in the allowlist or if allowAll is set to true.\n */\n event FeatureFlagDenyAllSet(bytes32 indexed feature, bool denyAll);\n\n /**\n * @notice Emitted when an address was given access to a feature.\n * @param feature The bytes32 id of the feature.\n * @param account The address that was given access to the feature.\n */\n event FeatureFlagAllowlistAdded(bytes32 indexed feature, address account);\n\n /**\n * @notice Emitted when access to a feature has been removed from an address.\n * @param feature The bytes32 id of the feature.\n * @param account The address that no longer has access to the feature.\n */\n event FeatureFlagAllowlistRemoved(bytes32 indexed feature, address account);\n\n /**\n * @notice Emitted when the list of addresses which can block a feature has been updated\n * @param feature The bytes32 id of the feature.\n * @param deniers The list of addresses which are allowed to block a feature\n */\n event FeatureFlagDeniersReset(bytes32 indexed feature, address[] deniers);\n\n /**\n * @notice Enables or disables free access to a feature.\n * @param feature The bytes32 id of the feature.\n * @param allowAll True to allow anyone to use the feature, false to fallback to the allowlist.\n */\n function setFeatureFlagAllowAll(bytes32 feature, bool allowAll) external;\n\n /**\n * @notice Enables or disables free access to a feature.\n * @param feature The bytes32 id of the feature.\n * @param denyAll True to allow noone to use the feature, false to fallback to the allowlist.\n */\n function setFeatureFlagDenyAll(bytes32 feature, bool denyAll) external;\n\n /**\n * @notice Allows an address to use a feature.\n * @dev This function does nothing if the specified account is already on the allowlist.\n * @param feature The bytes32 id of the feature.\n * @param account The address that is allowed to use the feature.\n */\n function addToFeatureFlagAllowlist(bytes32 feature, address account) external;\n\n /**\n * @notice Disallows an address from using a feature.\n * @dev This function does nothing if the specified account is already on the allowlist.\n * @param feature The bytes32 id of the feature.\n * @param account The address that is disallowed from using the feature.\n */\n function removeFromFeatureFlagAllowlist(bytes32 feature, address account) external;\n\n /**\n * @notice Sets addresses which can disable a feature (but not enable it). Overwrites any preexisting data.\n * @param feature The bytes32 id of the feature.\n * @param deniers The addresses which should have the ability to unilaterally disable the feature\n */\n function setDeniers(bytes32 feature, address[] memory deniers) external;\n\n /**\n * @notice Gets the list of address which can block a feature\n * @param feature The bytes32 id of the feature.\n */\n function getDeniers(bytes32 feature) external returns (address[] memory);\n\n /**\n * @notice Determines if the given feature is freely allowed to all users.\n * @param feature The bytes32 id of the feature.\n * @return True if anyone is allowed to use the feature, false if per-user control is used.\n */\n function getFeatureFlagAllowAll(bytes32 feature) external view returns (bool);\n\n /**\n * @notice Determines if the given feature is denied to all users.\n * @param feature The bytes32 id of the feature.\n * @return True if noone is allowed to use the feature.\n */\n function getFeatureFlagDenyAll(bytes32 feature) external view returns (bool);\n\n /**\n * @notice Returns a list of addresses that are allowed to use the specified feature.\n * @param feature The bytes32 id of the feature.\n * @return The queried list of addresses.\n */\n function getFeatureFlagAllowlist(bytes32 feature) external view returns (address[] memory);\n\n /**\n * @notice Determines if an address can use the specified feature.\n * @param feature The bytes32 id of the feature.\n * @param account The address that is being queried for access to the feature.\n * @return A boolean with the response to the query.\n */\n function isFeatureAllowed(bytes32 feature, address account) external view returns (bool);\n}\n" }, "@synthetixio/core-modules/contracts/interfaces/INftModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/interfaces/IERC721Enumerable.sol\";\n\n/**\n * @title Module wrapping an ERC721 token implementation.\n */\ninterface INftModule is IERC721Enumerable {\n /**\n * @notice Returns wether the token has been initialized.\n * @return A boolean with the result of the query.\n */\n function isInitialized() external returns (bool);\n\n /**\n * @notice Initializes the token with name, symbol, and uri.\n */\n function initialize(\n string memory tokenName,\n string memory tokenSymbol,\n string memory uri\n ) external;\n\n /**\n * @notice Allows the owner to mint tokens.\n * @param to The address to receive the newly minted tokens.\n * @param tokenId The ID of the newly minted token\n */\n function mint(address to, uint tokenId) external;\n\n /**\n * @notice Allows the owner to mint tokens. Verifies that the receiver can receive the token\n * @param to The address to receive the newly minted token.\n * @param tokenId The ID of the newly minted token\n * @param data any data which should be sent to the receiver\n */\n function safeMint(address to, uint256 tokenId, bytes memory data) external;\n\n /**\n * @notice Allows the owner to burn tokens.\n * @param tokenId The token to burn\n */\n function burn(uint tokenId) external;\n\n /**\n * @notice Allows an address that holds tokens to provide allowance to another.\n * @param tokenId The token which should be allowed to spender\n * @param spender The address that is given allowance.\n */\n function setAllowance(uint tokenId, address spender) external;\n}\n" }, "@synthetixio/core-modules/contracts/interfaces/IOwnerModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module for giving a system owner based access control.\n */\n// solhint-disable-next-line no-empty-blocks\ninterface IOwnerModule {\n\n}\n" }, "@synthetixio/core-modules/contracts/interfaces/ITokenModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/interfaces/IERC20.sol\";\n\n/**\n * @title Module wrapping an ERC20 token implementation.\n */\ninterface ITokenModule is IERC20 {\n /**\n * @notice Returns wether the token has been initialized.\n * @return A boolean with the result of the query.\n */\n function isInitialized() external returns (bool);\n\n /**\n * @notice Initializes the token with name, symbol, and decimals.\n */\n function initialize(\n string memory tokenName,\n string memory tokenSymbol,\n uint8 tokenDecimals\n ) external;\n\n /**\n * @notice Allows the owner to mint tokens.\n * @param to The address to receive the newly minted tokens.\n * @param amount The amount of tokens to mint.\n */\n function mint(address to, uint amount) external;\n\n /**\n * @notice Allows the owner to burn tokens.\n * @param to The address whose tokens will be burnt.\n * @param amount The amount of tokens to burn.\n */\n function burn(address to, uint amount) external;\n\n /**\n * @notice Allows an address that holds tokens to provide allowance to another.\n * @param from The address that is providing allowance.\n * @param spender The address that is given allowance.\n * @param amount The amount of allowance being given.\n */\n function setAllowance(address from, address spender, uint amount) external;\n}\n" }, "@synthetixio/core-modules/contracts/modules/AssociatedSystemsModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/errors/InitError.sol\";\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\nimport \"@synthetixio/core-contracts/contracts/proxy/UUPSProxyWithOwner.sol\";\nimport \"../interfaces/IAssociatedSystemsModule.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/interfaces/IUUPSImplementation.sol\";\nimport \"../interfaces/IOwnerModule.sol\";\nimport \"../interfaces/ITokenModule.sol\";\nimport \"../interfaces/INftModule.sol\";\n\nimport \"../storage/AssociatedSystem.sol\";\n\n/**\n * @title Module for connecting a system with other associated systems.\n * @dev See IAssociatedSystemsModule.\n */\ncontract AssociatedSystemsModule is IAssociatedSystemsModule {\n using AssociatedSystem for AssociatedSystem.Data;\n\n /**\n * @inheritdoc IAssociatedSystemsModule\n */\n function initOrUpgradeToken(\n bytes32 id,\n string memory name,\n string memory symbol,\n uint8 decimals,\n address impl\n ) external override {\n OwnableStorage.onlyOwner();\n _initOrUpgradeToken(id, name, symbol, decimals, impl);\n }\n\n /**\n * @inheritdoc IAssociatedSystemsModule\n */\n function initOrUpgradeNft(\n bytes32 id,\n string memory name,\n string memory symbol,\n string memory uri,\n address impl\n ) external override {\n OwnableStorage.onlyOwner();\n _initOrUpgradeNft(id, name, symbol, uri, impl);\n }\n\n /**\n * @inheritdoc IAssociatedSystemsModule\n */\n function registerUnmanagedSystem(bytes32 id, address endpoint) external override {\n OwnableStorage.onlyOwner();\n // empty string require kind will make sure the system is either unregistered or already unmanaged\n AssociatedSystem.load(id).expectKind(\"\");\n\n _setAssociatedSystem(id, AssociatedSystem.KIND_UNMANAGED, endpoint, endpoint);\n }\n\n /**\n * @inheritdoc IAssociatedSystemsModule\n */\n function getAssociatedSystem(\n bytes32 id\n ) external view override returns (address addr, bytes32 kind) {\n addr = AssociatedSystem.load(id).proxy;\n kind = AssociatedSystem.load(id).kind;\n }\n\n modifier onlyIfAssociated(bytes32 id) {\n if (address(AssociatedSystem.load(id).proxy) == address(0)) {\n revert MissingAssociatedSystem(id);\n }\n\n _;\n }\n\n function _setAssociatedSystem(bytes32 id, bytes32 kind, address proxy, address impl) internal {\n AssociatedSystem.load(id).set(proxy, impl, kind);\n emit AssociatedSystemSet(kind, id, proxy, impl);\n }\n\n function _upgradeToken(bytes32 id, address impl) internal {\n AssociatedSystem.Data storage store = AssociatedSystem.load(id);\n store.expectKind(AssociatedSystem.KIND_ERC20);\n\n store.impl = impl;\n\n address proxy = store.proxy;\n\n // tell the associated proxy to upgrade to the new implementation\n IUUPSImplementation(proxy).upgradeTo(impl);\n\n _setAssociatedSystem(id, AssociatedSystem.KIND_ERC20, proxy, impl);\n }\n\n function _upgradeNft(bytes32 id, address impl) internal {\n AssociatedSystem.Data storage store = AssociatedSystem.load(id);\n store.expectKind(AssociatedSystem.KIND_ERC721);\n\n store.impl = impl;\n\n address proxy = store.proxy;\n\n // tell the associated proxy to upgrade to the new implementation\n IUUPSImplementation(proxy).upgradeTo(impl);\n\n _setAssociatedSystem(id, AssociatedSystem.KIND_ERC721, proxy, impl);\n }\n\n function _initOrUpgradeToken(\n bytes32 id,\n string memory name,\n string memory symbol,\n uint8 decimals,\n address impl\n ) internal {\n AssociatedSystem.Data storage store = AssociatedSystem.load(id);\n\n if (store.proxy != address(0)) {\n _upgradeToken(id, impl);\n } else {\n // create a new proxy and own it\n address proxy = address(new UUPSProxyWithOwner(impl, address(this)));\n\n ITokenModule(proxy).initialize(name, symbol, decimals);\n\n _setAssociatedSystem(id, AssociatedSystem.KIND_ERC20, proxy, impl);\n }\n }\n\n function _initOrUpgradeNft(\n bytes32 id,\n string memory name,\n string memory symbol,\n string memory uri,\n address impl\n ) internal {\n OwnableStorage.onlyOwner();\n AssociatedSystem.Data storage store = AssociatedSystem.load(id);\n\n if (store.proxy != address(0)) {\n _upgradeNft(id, impl);\n } else {\n // create a new proxy and own it\n address proxy = address(new UUPSProxyWithOwner(impl, address(this)));\n\n INftModule(proxy).initialize(name, symbol, uri);\n\n _setAssociatedSystem(id, AssociatedSystem.KIND_ERC721, proxy, impl);\n }\n }\n}\n" }, "@synthetixio/core-modules/contracts/modules/FeatureFlagModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\nimport \"../storage/FeatureFlag.sol\";\n\nimport \"../interfaces/IFeatureFlagModule.sol\";\n\n/**\n * @title Module for granular enabling and disabling of system features and functions.\n * See IFeatureFlagModule.\n */\ncontract FeatureFlagModule is IFeatureFlagModule {\n using SetUtil for SetUtil.AddressSet;\n using FeatureFlag for FeatureFlag.Data;\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function setFeatureFlagAllowAll(bytes32 feature, bool allowAll) external override {\n OwnableStorage.onlyOwner();\n FeatureFlag.load(feature).allowAll = allowAll;\n\n if (allowAll) {\n FeatureFlag.load(feature).denyAll = false;\n }\n\n emit FeatureFlagAllowAllSet(feature, allowAll);\n }\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function setFeatureFlagDenyAll(bytes32 feature, bool denyAll) external override {\n FeatureFlag.Data storage flag = FeatureFlag.load(feature);\n\n if (!denyAll || !flag.isDenier(msg.sender)) {\n OwnableStorage.onlyOwner();\n }\n\n flag.denyAll = denyAll;\n\n emit FeatureFlagDenyAllSet(feature, denyAll);\n }\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function addToFeatureFlagAllowlist(bytes32 feature, address account) external override {\n OwnableStorage.onlyOwner();\n\n SetUtil.AddressSet storage permissionedAddresses = FeatureFlag\n .load(feature)\n .permissionedAddresses;\n\n if (!permissionedAddresses.contains(account)) {\n permissionedAddresses.add(account);\n emit FeatureFlagAllowlistAdded(feature, account);\n }\n }\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function removeFromFeatureFlagAllowlist(bytes32 feature, address account) external override {\n OwnableStorage.onlyOwner();\n\n SetUtil.AddressSet storage permissionedAddresses = FeatureFlag\n .load(feature)\n .permissionedAddresses;\n\n if (permissionedAddresses.contains(account)) {\n FeatureFlag.load(feature).permissionedAddresses.remove(account);\n emit FeatureFlagAllowlistRemoved(feature, account);\n }\n }\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function setDeniers(bytes32 feature, address[] memory deniers) external override {\n OwnableStorage.onlyOwner();\n FeatureFlag.Data storage flag = FeatureFlag.load(feature);\n\n // resize array (its really dumb how you have to do this)\n uint storageLen = flag.deniers.length;\n for (uint i = storageLen; i > deniers.length; i--) {\n flag.deniers.pop();\n }\n\n for (uint i = 0; i < deniers.length; i++) {\n if (i >= storageLen) {\n flag.deniers.push(deniers[i]);\n } else {\n flag.deniers[i] = deniers[i];\n }\n }\n\n emit FeatureFlagDeniersReset(feature, deniers);\n }\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function getDeniers(bytes32 feature) external view override returns (address[] memory) {\n FeatureFlag.Data storage flag = FeatureFlag.load(feature);\n address[] memory addrs = new address[](flag.deniers.length);\n for (uint i = 0; i < addrs.length; i++) {\n addrs[i] = flag.deniers[i];\n }\n\n return addrs;\n }\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function getFeatureFlagAllowAll(bytes32 feature) external view override returns (bool) {\n return FeatureFlag.load(feature).allowAll;\n }\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function getFeatureFlagDenyAll(bytes32 feature) external view override returns (bool) {\n return FeatureFlag.load(feature).denyAll;\n }\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function getFeatureFlagAllowlist(\n bytes32 feature\n ) external view override returns (address[] memory) {\n return FeatureFlag.load(feature).permissionedAddresses.values();\n }\n\n /**\n * @inheritdoc IFeatureFlagModule\n */\n function isFeatureAllowed(\n bytes32 feature,\n address account\n ) external view override returns (bool) {\n return FeatureFlag.hasAccess(feature, account);\n }\n}\n" }, "@synthetixio/core-modules/contracts/modules/NftModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/token/ERC721Enumerable.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/AddressUtil.sol\";\nimport \"@synthetixio/core-contracts/contracts/initializable/InitializableMixin.sol\";\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/AddressError.sol\";\n\nimport \"../storage/Initialized.sol\";\n\nimport \"../interfaces/INftModule.sol\";\n\n/**\n * @title Module wrapping an ERC721 token implementation.\n * See INftModule.\n */\ncontract NftModule is INftModule, ERC721Enumerable, InitializableMixin {\n bytes32 internal constant _INITIALIZED_NAME = \"NftModule\";\n\n /**\n * @inheritdoc INftModule\n */\n function isInitialized() external view returns (bool) {\n return _isInitialized();\n }\n\n /**\n * @inheritdoc INftModule\n */\n function initialize(\n string memory tokenName,\n string memory tokenSymbol,\n string memory uri\n ) public {\n OwnableStorage.onlyOwner();\n\n _initialize(tokenName, tokenSymbol, uri);\n Initialized.load(_INITIALIZED_NAME).initialized = true;\n }\n\n /**\n * @inheritdoc INftModule\n */\n function burn(uint256 tokenId) external override {\n OwnableStorage.onlyOwner();\n _burn(tokenId);\n }\n\n /**\n * @inheritdoc INftModule\n */\n function mint(address to, uint256 tokenId) external override {\n OwnableStorage.onlyOwner();\n _mint(to, tokenId);\n }\n\n /**\n * @inheritdoc INftModule\n */\n function safeMint(address to, uint256 tokenId, bytes memory data) external override {\n OwnableStorage.onlyOwner();\n _mint(to, tokenId);\n\n if (!_checkOnERC721Received(address(0), to, tokenId, data)) {\n revert InvalidTransferRecipient(to);\n }\n }\n\n /**\n * @inheritdoc INftModule\n */\n function setAllowance(uint tokenId, address spender) external override {\n OwnableStorage.onlyOwner();\n ERC721Storage.load().tokenApprovals[tokenId] = spender;\n }\n\n function _isInitialized() internal view override returns (bool) {\n return Initialized.load(_INITIALIZED_NAME).initialized;\n }\n}\n" }, "@synthetixio/core-modules/contracts/modules/OwnerModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/ownership/Ownable.sol\";\nimport \"@synthetixio/core-contracts/contracts/initializable/InitializableMixin.sol\";\nimport \"../interfaces/IOwnerModule.sol\";\n\n/**\n * @title Module for giving a system owner based access control.\n * See IOwnerModule.\n */\ncontract OwnerModule is Ownable, IOwnerModule {\n // solhint-disable-next-line no-empty-blocks\n constructor() Ownable(address(0)) {\n // empty intentionally\n }\n\n // no impl intentionally\n}\n" }, "@synthetixio/core-modules/contracts/modules/UpgradeModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/proxy/UUPSImplementation.sol\";\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\n\ncontract UpgradeModule is UUPSImplementation {\n function upgradeTo(address newImplementation) public override {\n OwnableStorage.onlyOwner();\n _upgradeTo(newImplementation);\n }\n}\n" }, "@synthetixio/core-modules/contracts/storage/AssociatedSystem.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../interfaces/ITokenModule.sol\";\nimport \"../interfaces/INftModule.sol\";\n\nlibrary AssociatedSystem {\n struct Data {\n address proxy;\n address impl;\n bytes32 kind;\n }\n\n error MismatchAssociatedSystemKind(bytes32 expected, bytes32 actual);\n\n function load(bytes32 id) internal pure returns (Data storage store) {\n bytes32 s = keccak256(abi.encode(\"io.synthetix.core-modules.AssociatedSystem\", id));\n assembly {\n store.slot := s\n }\n }\n\n bytes32 public constant KIND_ERC20 = \"erc20\";\n bytes32 public constant KIND_ERC721 = \"erc721\";\n bytes32 public constant KIND_UNMANAGED = \"unmanaged\";\n\n function getAddress(Data storage self) internal view returns (address) {\n return self.proxy;\n }\n\n function asToken(Data storage self) internal view returns (ITokenModule) {\n expectKind(self, KIND_ERC20);\n return ITokenModule(self.proxy);\n }\n\n function asNft(Data storage self) internal view returns (INftModule) {\n expectKind(self, KIND_ERC721);\n return INftModule(self.proxy);\n }\n\n function set(Data storage self, address proxy, address impl, bytes32 kind) internal {\n self.proxy = proxy;\n self.impl = impl;\n self.kind = kind;\n }\n\n function expectKind(Data storage self, bytes32 kind) internal view {\n bytes32 actualKind = self.kind;\n\n if (actualKind != kind && actualKind != KIND_UNMANAGED) {\n revert MismatchAssociatedSystemKind(kind, actualKind);\n }\n }\n}\n" }, "@synthetixio/core-modules/contracts/storage/FeatureFlag.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/SetUtil.sol\";\n\nlibrary FeatureFlag {\n using SetUtil for SetUtil.AddressSet;\n\n error FeatureUnavailable(bytes32 which);\n\n struct Data {\n bytes32 name;\n bool allowAll;\n bool denyAll;\n SetUtil.AddressSet permissionedAddresses;\n address[] deniers;\n }\n\n function load(bytes32 featureName) internal pure returns (Data storage store) {\n bytes32 s = keccak256(abi.encode(\"io.synthetix.core-modules.FeatureFlag\", featureName));\n assembly {\n store.slot := s\n }\n }\n\n function ensureAccessToFeature(bytes32 feature) internal view {\n if (!hasAccess(feature, msg.sender)) {\n revert FeatureUnavailable(feature);\n }\n }\n\n function hasAccess(bytes32 feature, address value) internal view returns (bool) {\n Data storage store = FeatureFlag.load(feature);\n\n if (store.denyAll) {\n return false;\n }\n\n return store.allowAll || store.permissionedAddresses.contains(value);\n }\n\n function isDenier(Data storage self, address possibleDenier) internal view returns (bool) {\n for (uint i = 0; i < self.deniers.length; i++) {\n if (self.deniers[i] == possibleDenier) {\n return true;\n }\n }\n\n return false;\n }\n}\n" }, "@synthetixio/core-modules/contracts/storage/Initialized.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nlibrary Initialized {\n struct Data {\n bool initialized;\n }\n\n function load(bytes32 id) internal pure returns (Data storage store) {\n bytes32 s = keccak256(abi.encode(\"io.synthetix.code-modules.Initialized\", id));\n assembly {\n store.slot := s\n }\n }\n}\n" }, "@synthetixio/oracle-manager/contracts/interfaces/INodeModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../storage/NodeOutput.sol\";\nimport \"../storage/NodeDefinition.sol\";\n\n/// @title Module for managing nodes\ninterface INodeModule {\n /**\n * @notice Thrown when the specified nodeId has not been registered in the system.\n */\n error NodeNotRegistered(bytes32 nodeId);\n\n /**\n * @notice Thrown when a node is registered without a valid definition.\n */\n error InvalidNodeDefinition(NodeDefinition.Data nodeType);\n\n /**\n * @notice Thrown when a node cannot be processed\n */\n error UnprocessableNode(bytes32 nodeId);\n\n /**\n * @notice Thrown when a node is registered with an invalid external node\n */\n error IncorrectExternalNodeInterface(address externalNode);\n\n /**\n * @notice Emitted when `registerNode` is called.\n * @param nodeId The id of the registered node.\n * @param nodeType The nodeType assigned to this node.\n * @param parameters The parameters assigned to this node.\n * @param parents The parents assigned to this node.\n */\n event NodeRegistered(\n bytes32 nodeId,\n NodeDefinition.NodeType nodeType,\n bytes parameters,\n bytes32[] parents\n );\n\n /**\n * @notice Registers a node\n * @param nodeType The nodeType assigned to this node.\n * @param parameters The parameters assigned to this node.\n * @param parents The parents assigned to this node.\n * @return The id of the registered node.\n */\n function registerNode(\n NodeDefinition.NodeType nodeType,\n bytes memory parameters,\n bytes32[] memory parents\n ) external returns (bytes32);\n\n /**\n * @notice Returns the ID of a node, whether or not it has been registered.\n * @param parents The parents assigned to this node.\n * @param nodeType The nodeType assigned to this node.\n * @param parameters The parameters assigned to this node.\n * @return The id of the node.\n */\n function getNodeId(\n NodeDefinition.NodeType nodeType,\n bytes memory parameters,\n bytes32[] memory parents\n ) external returns (bytes32);\n\n /**\n * @notice Returns a node's definition (type, parameters, and parents)\n * @param nodeId The node ID\n * @return The node's definition data\n */\n function getNode(bytes32 nodeId) external view returns (NodeDefinition.Data memory);\n\n /**\n * @notice Returns a node current output data\n * @param nodeId The node ID\n * @return The node's output data\n */\n function process(bytes32 nodeId) external view returns (NodeOutput.Data memory);\n}\n" }, "@synthetixio/oracle-manager/contracts/storage/NodeDefinition.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nlibrary NodeDefinition {\n enum NodeType {\n NONE,\n REDUCER,\n EXTERNAL,\n CHAINLINK,\n UNISWAP,\n PYTH,\n PRICE_DEVIATION_CIRCUIT_BREAKER,\n STALENESS_CIRCUIT_BREAKER\n }\n\n struct Data {\n NodeType nodeType;\n bytes parameters;\n bytes32[] parents;\n }\n\n function load(bytes32 id) internal pure returns (Data storage node) {\n bytes32 s = keccak256(abi.encode(\"io.synthetix.oracle-manager.Node\", id));\n assembly {\n node.slot := s\n }\n }\n\n function create(\n Data memory nodeDefinition\n ) internal returns (NodeDefinition.Data storage node, bytes32 id) {\n id = getId(nodeDefinition);\n\n node = load(id);\n\n node.nodeType = nodeDefinition.nodeType;\n node.parameters = nodeDefinition.parameters;\n node.parents = nodeDefinition.parents;\n }\n\n function getId(Data memory nodeDefinition) internal pure returns (bytes32) {\n return\n keccak256(\n abi.encode(\n nodeDefinition.nodeType,\n nodeDefinition.parameters,\n nodeDefinition.parents\n )\n );\n }\n}\n" }, "@synthetixio/oracle-manager/contracts/storage/NodeOutput.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nlibrary NodeOutput {\n struct Data {\n int256 price;\n uint256 timestamp;\n // solhint-disable-next-line private-vars-leading-underscore\n uint256 __slotAvailableForFutureUse1;\n // solhint-disable-next-line private-vars-leading-underscore\n uint256 __slotAvailableForFutureUse2;\n }\n}\n" }, "contracts/interfaces/external/IAggregatorV3Interface.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/// @title Interface an aggregator needs to adhere.\ninterface IAggregatorV3Interface {\n /// @notice decimals used by the aggregator\n function decimals() external view returns (uint8);\n\n /// @notice aggregator's description\n function description() external view returns (string memory);\n\n /// @notice aggregator's version\n function version() external view returns (uint256);\n\n // getRoundData and latestRoundData should both raise \"No data present\"\n // if they do not have data to report, instead of returning unset values\n // which could be misinterpreted as actual reported values.\n /// @notice get's round data for requested id\n function getRoundData(\n uint80 id\n )\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n /// @notice get's latest round data\n function latestRoundData()\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n}\n" }, "contracts/interfaces/external/IAny2EVMMessageReceiverInterface.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/interfaces/IERC20.sol\";\n\n/**\n * @notice Application contracts that intend to receive CCIP messages from\n * the OffRampRouter should implement this interface.\n */\ninterface IAny2EVMMessageReceiverInterface {\n struct Any2EVMMessage {\n uint256 srcChainId;\n bytes sender;\n bytes data;\n IERC20[] destTokens;\n uint256[] amounts;\n }\n\n /**\n * @notice Called by the OffRampRouter to deliver a message\n * @param message CCIP Message\n * @dev Note ensure you check the msg.sender is the OffRampRouter\n */\n function ccipReceive(Any2EVMMessage calldata message) external;\n}\n" }, "contracts/interfaces/external/IEVM2AnySubscriptionOnRampRouterInterface.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/interfaces/IERC20.sol\";\n\n/**\n * @notice Application contracts that intend to send messages via CCIP\n * will interact with this interface.\n */\ninterface IEVM2AnySubscriptionOnRampRouterInterface {\n struct EVM2AnySubscriptionMessage {\n bytes receiver; // Address of the receiver on the destination chain for EVM chains use abi.encode(destAddress).\n bytes data; // Bytes that we wish to send to the receiver\n IERC20[] tokens; // The ERC20 tokens we wish to send for EVM source chains\n uint256[] amounts; // The amount of ERC20 tokens we wish to send for EVM source chains\n uint256 gasLimit; // the gas limit for the call to the receiver for destination chains\n }\n\n /**\n * @notice Request a message to be sent to the destination chain\n * @param destChainId The destination chain ID\n * @param message The message payload\n */\n function ccipSend(uint256 destChainId, EVM2AnySubscriptionMessage calldata message) external;\n}\n" }, "contracts/interfaces/external/IMarket.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/interfaces/IERC165.sol\";\n\n/// @title Interface a Market needs to adhere.\ninterface IMarket is IERC165 {\n /// @notice returns a human-readable name for a given market\n function name(uint128 marketId) external view returns (string memory);\n\n /// @notice returns amount of USD that the market would try to mint256 if everything was withdrawn\n function reportedDebt(uint128 marketId) external view returns (uint256);\n\n /// @notice returns the amount of collateral which should (in addition to `reportedDebt`) be prevented from withdrawing from this market\n /// if your market does not require locking, set this to `0`\n function locked(uint128 marketId) external view returns (uint256);\n}\n" }, "contracts/interfaces/external/IRewardDistributor.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/interfaces/IERC165.sol\";\n\n/// @title Interface a reward distributor.\ninterface IRewardDistributor is IERC165 {\n /// @notice Returns a human-readable name for the reward distributor\n function name() external returns (string memory);\n\n /// @notice This function should revert if msg.sender is not the Synthetix CoreProxy address.\n /// @return whether or not the payout was executed\n function payout(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n address sender,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Address to ERC-20 token distributed by this distributor, for display purposes only\n /// @dev Return address(0) if providing non ERC-20 rewards\n function token() external returns (address);\n}\n" }, "contracts/interfaces/IAccountModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module for managing accounts.\n * @notice Manages the system's account token NFT. Every user will need to register an account before being able to interact with the system.\n */\ninterface IAccountModule {\n /**\n * @notice Thrown when the account interacting with the system is expected to be the associated account token, but is not.\n */\n error OnlyAccountTokenProxy(address origin);\n\n /**\n * @notice Thrown when an account attempts to renounce a permission that it didn't have.\n */\n error PermissionNotGranted(uint128 accountId, bytes32 permission, address user);\n\n /**\n * @notice Emitted when an account token with id `accountId` is minted to `sender`.\n * @param accountId The id of the account.\n * @param owner The address that owns the created account.\n */\n event AccountCreated(uint128 indexed accountId, address indexed owner);\n\n /**\n * @notice Emitted when `user` is granted `permission` by `sender` for account `accountId`.\n * @param accountId The id of the account that granted the permission.\n * @param permission The bytes32 identifier of the permission.\n * @param user The target address to whom the permission was granted.\n * @param sender The Address that granted the permission.\n */\n event PermissionGranted(\n uint128 indexed accountId,\n bytes32 indexed permission,\n address indexed user,\n address sender\n );\n\n /**\n * @notice Emitted when `user` has `permission` renounced or revoked by `sender` for account `accountId`.\n * @param accountId The id of the account that has had the permission revoked.\n * @param permission The bytes32 identifier of the permission.\n * @param user The target address for which the permission was revoked.\n * @param sender The address that revoked the permission.\n */\n event PermissionRevoked(\n uint128 indexed accountId,\n bytes32 indexed permission,\n address indexed user,\n address sender\n );\n\n /**\n * @dev Data structure for tracking each user's permissions.\n */\n struct AccountPermissions {\n /**\n * @dev The address for which all the permissions are granted.\n */\n address user;\n /**\n * @dev The array of permissions given to the associated address.\n */\n bytes32[] permissions;\n }\n\n /**\n * @notice Returns an array of `AccountPermission` for the provided `accountId`.\n * @param accountId The id of the account whose permissions are being retrieved.\n * @return accountPerms An array of AccountPermission objects describing the permissions granted to the account.\n */\n function getAccountPermissions(\n uint128 accountId\n ) external view returns (AccountPermissions[] memory accountPerms);\n\n /**\n * @notice Mints an account token with id `requestedAccountId` to `msg.sender`.\n * @param requestedAccountId The id requested for the account being created. Reverts if id already exists.\n *\n * Requirements:\n *\n * - `requestedAccountId` must not already be minted.\n *\n * Emits a {AccountCreated} event.\n */\n function createAccount(uint128 requestedAccountId) external;\n\n /**\n * @notice Called by AccountTokenModule to notify the system when the account token is transferred.\n * @dev Resets user permissions and assigns ownership of the account token to the new holder.\n * @param to The new holder of the account NFT.\n * @param accountId The id of the account that was just transferred.\n *\n * Requirements:\n *\n * - `msg.sender` must be the account token.\n */\n function notifyAccountTransfer(address to, uint128 accountId) external;\n\n /**\n * @notice Grants `permission` to `user` for account `accountId`.\n * @param accountId The id of the account that granted the permission.\n * @param permission The bytes32 identifier of the permission.\n * @param user The target address that received the permission.\n *\n * Requirements:\n *\n * - `msg.sender` must own the account token with ID `accountId` or have the \"admin\" permission.\n *\n * Emits a {PermissionGranted} event.\n */\n function grantPermission(uint128 accountId, bytes32 permission, address user) external;\n\n /**\n * @notice Revokes `permission` from `user` for account `accountId`.\n * @param accountId The id of the account that revoked the permission.\n * @param permission The bytes32 identifier of the permission.\n * @param user The target address that no longer has the permission.\n *\n * Requirements:\n *\n * - `msg.sender` must own the account token with ID `accountId` or have the \"admin\" permission.\n *\n * Emits a {PermissionRevoked} event.\n */\n function revokePermission(uint128 accountId, bytes32 permission, address user) external;\n\n /**\n * @notice Revokes `permission` from `msg.sender` for account `accountId`.\n * @param accountId The id of the account whose permission was renounced.\n * @param permission The bytes32 identifier of the permission.\n *\n * Emits a {PermissionRevoked} event.\n */\n function renouncePermission(uint128 accountId, bytes32 permission) external;\n\n /**\n * @notice Returns `true` if `user` has been granted `permission` for account `accountId`.\n * @param accountId The id of the account whose permission is being queried.\n * @param permission The bytes32 identifier of the permission.\n * @param user The target address whose permission is being queried.\n * @return hasPermission A boolean with the response of the query.\n */\n function hasPermission(\n uint128 accountId,\n bytes32 permission,\n address user\n ) external view returns (bool hasPermission);\n\n /**\n * @notice Returns `true` if `target` is authorized to `permission` for account `accountId`.\n * @param accountId The id of the account whose permission is being queried.\n * @param permission The bytes32 identifier of the permission.\n * @param target The target address whose permission is being queried.\n * @return isAuthorized A boolean with the response of the query.\n */\n function isAuthorized(\n uint128 accountId,\n bytes32 permission,\n address target\n ) external view returns (bool isAuthorized);\n\n /**\n * @notice Returns the address for the account token used by the module.\n * @return accountNftToken The address of the account token.\n */\n function getAccountTokenAddress() external view returns (address accountNftToken);\n\n /**\n * @notice Returns the address that owns a given account, as recorded by the system.\n * @param accountId The account id whose owner is being retrieved.\n * @return owner The owner of the given account id.\n */\n function getAccountOwner(uint128 accountId) external view returns (address owner);\n\n /**\n * @notice Returns the last unix timestamp that a permissioned action was taken with this account\n * @param accountId The account id to check\n * @return timestamp The unix timestamp of the last time a permissioned action occured with the account\n */\n function getAccountLastInteraction(uint128 accountId) external view returns (uint256 timestamp);\n}\n" }, "contracts/interfaces/IAccountTokenModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-modules/contracts/interfaces/INftModule.sol\";\n\n/**\n * @title Module with custom NFT logic for the account token.\n */\n// solhint-disable-next-line no-empty-blocks\ninterface IAccountTokenModule is INftModule {\n\n}\n" }, "contracts/interfaces/IAssociateDebtModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module for associating debt with the system.\n * @notice Allows a market to associate debt to a user's existing position.\n * E.g. when migrating a position from v2 into v3's legacy market, the market first scales up everyone's debt, and then associates it to a position using this module.\n */\ninterface IAssociateDebtModule {\n /**\n * @notice Thrown when the specified market is not connected to the specified pool in debt association.\n */\n error NotFundedByPool(uint256 marketId, uint256 poolId);\n\n /**\n * @notice Thrown when a debt association would shift a position below the liquidation ratio.\n */\n error InsufficientCollateralRatio(\n uint256 collateralValue,\n uint256 debt,\n uint256 ratio,\n uint256 minRatio\n );\n\n /**\n * @notice Emitted when `associateDebt` is called.\n * @param marketId The id of the market to which debt was associated.\n * @param poolId The id of the pool associated to the target market.\n * @param collateralType The address of the collateral type that acts as collateral in the corresponding pool.\n * @param accountId The id of the account whose debt is being associated.\n * @param amount The amount of debt being associated with the specified account, denominated with 18 decimals of precision.\n * @param updatedDebt The total updated debt of the account, denominated with 18 decimals of precision\n */\n event DebtAssociated(\n uint128 indexed marketId,\n uint128 indexed poolId,\n address indexed collateralType,\n uint128 accountId,\n uint256 amount,\n int256 updatedDebt\n );\n\n /**\n * @notice Allows a market to associate debt with a specific position.\n * The specified debt will be removed from all vault participants pro-rata. After removing the debt, the amount will\n * be allocated directly to the specified account.\n * **NOTE**: if the specified account is an existing staker on the vault, their position will be included in the pro-rata\n * reduction. Ex: if there are 10 users staking 10 USD of debt on a pool, and associate debt is called with 10 USD on one of those users,\n * their debt after the operation is complete will be 19 USD. This might seem unusual, but its actually ideal behavior when\n * your market has incurred some new debt, and it wants to allocate this amount directly to a specific user. In this case, the user's\n * debt balance would increase pro rata, but then get decreased pro-rata, and then increased to the full amount on their account. All\n * other accounts would be left with no change to their debt, however.\n * @param marketId The id of the market to which debt was associated.\n * @param poolId The id of the pool associated to the target market.\n * @param collateralType The address of the collateral type that acts as collateral in the corresponding pool.\n * @param accountId The id of the account whose debt is being associated.\n * @param amount The amount of debt being associated with the specified account, denominated with 18 decimals of precision.\n * @return debtAmount The updated debt of the position, denominated with 18 decimals of precision.\n */\n function associateDebt(\n uint128 marketId,\n uint128 poolId,\n address collateralType,\n uint128 accountId,\n uint256 amount\n ) external returns (int256 debtAmount);\n}\n" }, "contracts/interfaces/ICollateralConfigurationModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../storage/CollateralConfiguration.sol\";\n\n/**\n * @title Module for configuring system wide collateral.\n * @notice Allows the owner to configure collaterals at a system wide level.\n */\ninterface ICollateralConfigurationModule {\n /**\n * @notice Emitted when a collateral type’s configuration is created or updated.\n * @param collateralType The address of the collateral type that was just configured.\n * @param config The object with the newly configured details.\n */\n event CollateralConfigured(address indexed collateralType, CollateralConfiguration.Data config);\n\n /**\n * @notice Creates or updates the configuration for the given `collateralType`.\n * @param config The CollateralConfiguration object describing the new configuration.\n *\n * Requirements:\n *\n * - `msg.sender` must be the owner of the system.\n *\n * Emits a {CollateralConfigured} event.\n *\n */\n function configureCollateral(CollateralConfiguration.Data memory config) external;\n\n /**\n * @notice Returns a list of detailed information pertaining to all collateral types registered in the system.\n * @dev Optionally returns only those that are currently enabled.\n * @param hideDisabled Wether to hide disabled collaterals or just return the full list of collaterals in the system.\n * @return collaterals The list of collateral configuration objects set in the system.\n */\n function getCollateralConfigurations(\n bool hideDisabled\n ) external view returns (CollateralConfiguration.Data[] memory collaterals);\n\n /**\n * @notice Returns detailed information pertaining the specified collateral type.\n * @param collateralType The address for the collateral whose configuration is being queried.\n * @return collateral The configuration object describing the given collateral.\n */\n function getCollateralConfiguration(\n address collateralType\n ) external view returns (CollateralConfiguration.Data memory collateral);\n\n /**\n * @notice Returns the current value of a specified collateral type.\n * @param collateralType The address for the collateral whose price is being queried.\n * @return priceD18 The price of the given collateral, denominated with 18 decimals of precision.\n */\n function getCollateralPrice(address collateralType) external view returns (uint256 priceD18);\n}\n" }, "contracts/interfaces/ICollateralModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../storage/CollateralLock.sol\";\n\n/**\n * @title Module for managing user collateral.\n * @notice Allows users to deposit and withdraw collateral from the system.\n */\ninterface ICollateralModule {\n /**\n * @notice Thrown when an interacting account does not have sufficient collateral for an operation (withdrawal, lock, etc).\n */\n error InsufficientAccountCollateral(uint256 amount);\n\n /**\n * @notice Emitted when `tokenAmount` of collateral of type `collateralType` is deposited to account `accountId` by `sender`.\n * @param accountId The id of the account that deposited collateral.\n * @param collateralType The address of the collateral that was deposited.\n * @param tokenAmount The amount of collateral that was deposited, denominated in the token's native decimal representation.\n * @param sender The address of the account that triggered the deposit.\n */\n event Deposited(\n uint128 indexed accountId,\n address indexed collateralType,\n uint256 tokenAmount,\n address indexed sender\n );\n\n /**\n * @notice Emitted when a lock is created on someone's account\n * @param accountId The id of the account that received a lock\n * @param collateralType The address of the collateral type that was locked\n * @param tokenAmount The amount of collateral that was locked, demoninated in system units (1e18)\n * @param expireTimestamp unix timestamp at which the lock is due to expire\n */\n event CollateralLockCreated(\n uint128 indexed accountId,\n address indexed collateralType,\n uint256 tokenAmount,\n uint64 expireTimestamp\n );\n\n /**\n * @notice Emitted when a lock is cleared from an account due to expiration\n * @param accountId The id of the account that has the expired lock\n * @param collateralType The address of the collateral type that was unlocked\n * @param tokenAmount The amount of collateral that was unlocked, demoninated in system units (1e18)\n * @param expireTimestamp unix timestamp at which the unlock is due to expire\n */\n event CollateralLockExpired(\n uint128 indexed accountId,\n address indexed collateralType,\n uint256 tokenAmount,\n uint64 expireTimestamp\n );\n\n /**\n * @notice Emitted when `tokenAmount` of collateral of type `collateralType` is withdrawn from account `accountId` by `sender`.\n * @param accountId The id of the account that withdrew collateral.\n * @param collateralType The address of the collateral that was withdrawn.\n * @param tokenAmount The amount of collateral that was withdrawn, denominated in the token's native decimal representation.\n * @param sender The address of the account that triggered the withdrawal.\n */\n event Withdrawn(\n uint128 indexed accountId,\n address indexed collateralType,\n uint256 tokenAmount,\n address indexed sender\n );\n\n /**\n * @notice Deposits `tokenAmount` of collateral of type `collateralType` into account `accountId`.\n * @dev Anyone can deposit into anyone's active account without restriction.\n * @param accountId The id of the account that is making the deposit.\n * @param collateralType The address of the token to be deposited.\n * @param tokenAmount The amount being deposited, denominated in the token's native decimal representation.\n *\n * Emits a {Deposited} event.\n */\n function deposit(uint128 accountId, address collateralType, uint256 tokenAmount) external;\n\n /**\n * @notice Withdraws `tokenAmount` of collateral of type `collateralType` from account `accountId`.\n * @param accountId The id of the account that is making the withdrawal.\n * @param collateralType The address of the token to be withdrawn.\n * @param tokenAmount The amount being withdrawn, denominated in the token's native decimal representation.\n *\n * Requirements:\n *\n * - `msg.sender` must be the owner of the account, have the `ADMIN` permission, or have the `WITHDRAW` permission.\n *\n * Emits a {Withdrawn} event.\n *\n */\n function withdraw(uint128 accountId, address collateralType, uint256 tokenAmount) external;\n\n /**\n * @notice Returns the total values pertaining to account `accountId` for `collateralType`.\n * @param accountId The id of the account whose collateral is being queried.\n * @param collateralType The address of the collateral type whose amount is being queried.\n * @return totalDeposited The total collateral deposited in the account, denominated with 18 decimals of precision.\n * @return totalAssigned The amount of collateral in the account that is delegated to pools, denominated with 18 decimals of precision.\n * @return totalLocked The amount of collateral in the account that cannot currently be undelegated from a pool, denominated with 18 decimals of precision.\n */\n function getAccountCollateral(\n uint128 accountId,\n address collateralType\n ) external view returns (uint256 totalDeposited, uint256 totalAssigned, uint256 totalLocked);\n\n /**\n * @notice Returns the amount of collateral of type `collateralType` deposited with account `accountId` that can be withdrawn or delegated to pools.\n * @param accountId The id of the account whose collateral is being queried.\n * @param collateralType The address of the collateral type whose amount is being queried.\n * @return amountD18 The amount of collateral that is available for withdrawal or delegation, denominated with 18 decimals of precision.\n */\n function getAccountAvailableCollateral(\n uint128 accountId,\n address collateralType\n ) external view returns (uint256 amountD18);\n\n /**\n * @notice Clean expired locks from locked collateral arrays for an account/collateral type. It includes offset and items to prevent gas exhaustion. If both, offset and items, are 0 it will traverse the whole array (unlimited).\n * @param accountId The id of the account whose locks are being cleared.\n * @param collateralType The address of the collateral type to clean locks for.\n * @param offset The index of the first lock to clear.\n * @param count The number of slots to check for cleaning locks. Set to 0 to clean all locks at/after offset\n * @return cleared the number of locks that were actually expired (and therefore cleared)\n */\n function cleanExpiredLocks(\n uint128 accountId,\n address collateralType,\n uint256 offset,\n uint256 count\n ) external returns (uint cleared);\n\n /**\n * @notice Get a list of locks existing in account. Lists all locks in storage, even if they are expired\n * @param accountId The id of the account whose locks we want to read\n * @param collateralType The address of the collateral type for locks we want to read\n * @param offset The index of the first lock to read\n * @param count The number of slots to check for cleaning locks. Set to 0 to read all locks after offset\n */\n function getLocks(\n uint128 accountId,\n address collateralType,\n uint256 offset,\n uint256 count\n ) external view returns (CollateralLock.Data[] memory locks);\n\n /**\n * @notice Create a new lock on the given account. you must have `admin` permission on the specified account to create a lock.\n * @dev Collateral can be withdrawn from the system if it is not assigned or delegated to a pool. Collateral locks are an additional restriction that applies on top of that. I.e. if collateral is not assigned to a pool, but has a lock, it cannot be withdrawn.\n * @dev Collateral locks are initially intended for the Synthetix v2 to v3 migration, but may be used in the future by the Spartan Council, for example, to create and hand off accounts whose withdrawals from the system are locked for a given amount of time.\n * @param accountId The id of the account for which a lock is to be created.\n * @param collateralType The address of the collateral type for which the lock will be created.\n * @param amount The amount of collateral tokens to wrap in the lock being created, denominated with 18 decimals of precision.\n * @param expireTimestamp The date in which the lock will become clearable.\n */\n function createLock(\n uint128 accountId,\n address collateralType,\n uint256 amount,\n uint64 expireTimestamp\n ) external;\n}\n" }, "contracts/interfaces/IIssueUSDModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module for the minting and burning of stablecoins.\n */\ninterface IIssueUSDModule {\n /**\n * @notice Thrown when an account does not have sufficient debt to burn USD.\n */\n error InsufficientDebt(int256 currentDebt);\n\n /**\n * @notice Emitted when {sender} mints {amount} of snxUSD with the specified liquidity position.\n * @param accountId The id of the account for which snxUSD was emitted.\n * @param poolId The id of the pool whose collateral was used to emit the snxUSD.\n * @param collateralType The address of the collateral that is backing up the emitted snxUSD.\n * @param amount The amount of snxUSD emitted, denominated with 18 decimals of precision.\n * @param sender The address that triggered the operation.\n */\n event UsdMinted(\n uint128 indexed accountId,\n uint128 indexed poolId,\n address collateralType,\n uint256 amount,\n address indexed sender\n );\n\n /**\n * @notice Emitted when {sender} burns {amount} of snxUSD with the specified liquidity position.\n * @param accountId The id of the account for which snxUSD was burned.\n * @param poolId The id of the pool whose collateral was used to emit the snxUSD.\n * @param collateralType The address of the collateral that was backing up the emitted snxUSD.\n * @param amount The amount of snxUSD burned, denominated with 18 decimals of precision.\n * @param sender The address that triggered the operation.\n */\n event UsdBurned(\n uint128 indexed accountId,\n uint128 indexed poolId,\n address collateralType,\n uint256 amount,\n address indexed sender\n );\n\n /**\n * @notice Mints {amount} of snxUSD with the specified liquidity position.\n * @param accountId The id of the account that is minting snxUSD.\n * @param poolId The id of the pool whose collateral will be used to back up the mint.\n * @param collateralType The address of the collateral that will be used to back up the mint.\n * @param amount The amount of snxUSD to be minted, denominated with 18 decimals of precision.\n *\n * Requirements:\n *\n * - `msg.sender` must be the owner of the account, have the `ADMIN` permission, or have the `MINT` permission.\n * - After minting, the collateralization ratio of the liquidity position must not be below the target collateralization ratio for the corresponding collateral type.\n *\n * Emits a {UsdMinted} event.\n */\n function mintUsd(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n uint256 amount\n ) external;\n\n /**\n * @notice Burns {amount} of snxUSD with the specified liquidity position.\n * @param accountId The id of the account that is burning snxUSD.\n * @param poolId The id of the pool whose collateral was used to back up the snxUSD.\n * @param collateralType The address of the collateral that was used to back up the snxUSD.\n * @param amount The amount of snxUSD to be burnt, denominated with 18 decimals of precision.\n *\n * Emits a {UsdMinted} event.\n */\n function burnUsd(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n uint256 amount\n ) external;\n}\n" }, "contracts/interfaces/ILiquidationModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module for liquidated positions and vaults that are below the liquidation ratio.\n */\ninterface ILiquidationModule {\n /**\n * @notice Thrown when attempting to liquidate an account that is not eligible for liquidation.\n */\n error IneligibleForLiquidation(\n uint256 collateralValue,\n int256 debt,\n uint256 currentCRatio,\n uint256 cratio\n );\n\n /**\n * @notice Thrown when an entire vault instead of a single account should be liquidated.\n */\n error MustBeVaultLiquidated();\n\n /**\n * @notice Emitted when an account is liquidated.\n * @param accountId The id of the account that was liquidated.\n * @param poolId The pool id of the position that was liquidated.\n * @param collateralType The collateral type used in the position that was liquidated.\n * @param liquidationData The amount of collateral liquidated, debt liquidated, and collateral awarded to the liquidator.\n * @param liquidateAsAccountId Account id that will receive the rewards from the liquidation.\n * @param sender The address of the account that is triggering the liquidation.\n */\n event Liquidation(\n uint128 indexed accountId,\n uint128 indexed poolId,\n address indexed collateralType,\n LiquidationData liquidationData,\n uint128 liquidateAsAccountId,\n address sender\n );\n\n /**\n * @notice Emitted when a vault is liquidated.\n * @param poolId The id of the pool whose vault was liquidated.\n * @param collateralType The collateral address of the vault that was liquidated.\n * @param liquidationData The amount of collateral liquidated, debt liquidated, and collateral awarded to the liquidator.\n * @param liquidateAsAccountId Account id that will receive the rewards from the liquidation.\n * @param sender The address of the account that is triggering the liquidation.\n */\n event VaultLiquidation(\n uint128 indexed poolId,\n address indexed collateralType,\n LiquidationData liquidationData,\n uint128 liquidateAsAccountId,\n address sender\n );\n\n /**\n * @notice Data structure that holds liquidation information, used in events and in return statements.\n */\n struct LiquidationData {\n /**\n * @dev The debt of the position that was liquidated.\n */\n uint256 debtLiquidated;\n /**\n * @dev The collateral of the position that was liquidated.\n */\n uint256 collateralLiquidated;\n /**\n * @dev The amount rewarded in the liquidation.\n */\n uint256 amountRewarded;\n }\n\n /**\n * @notice Liquidates a position by distributing its debt and collateral among other positions in its vault.\n * @param accountId The id of the account whose position is to be liquidated.\n * @param poolId The id of the pool which holds the position that is to be liquidated.\n * @param collateralType The address of the collateral being used in the position that is to be liquidated.\n * @param liquidateAsAccountId Account id that will receive the rewards from the liquidation.\n * @return liquidationData Information about the position that was liquidated.\n */\n function liquidate(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n uint128 liquidateAsAccountId\n ) external returns (LiquidationData memory liquidationData);\n\n /**\n * @notice Liquidates an entire vault.\n * @dev Can only be done if the vault itself is under collateralized.\n * @dev LiquidateAsAccountId determines which account to deposit the seized collateral into (this is necessary particularly if the collateral in the vault is vesting).\n * @dev Will only liquidate a portion of the debt for the vault if `maxUsd` is supplied.\n * @param poolId The id of the pool whose vault is being liquidated.\n * @param collateralType The address of the collateral whose vault is being liquidated.\n * @param maxUsd The maximum amount of USD that the liquidator is willing to provide for the liquidation, denominated with 18 decimals of precision.\n * @return liquidationData Information about the vault that was liquidated.\n */\n function liquidateVault(\n uint128 poolId,\n address collateralType,\n uint128 liquidateAsAccountId,\n uint256 maxUsd\n ) external returns (LiquidationData memory liquidationData);\n\n /**\n * @notice Determines whether a specified position is liquidatable.\n * @param accountId The id of the account whose position is being queried for liquidation.\n * @param poolId The id of the pool whose position is being queried for liquidation.\n * @param collateralType The address of the collateral backing up the position being queried for liquidation.\n * @return canLiquidate A boolean with the response to the query.\n */\n function isPositionLiquidatable(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n ) external returns (bool canLiquidate);\n\n /**\n * @notice Determines whether a specified vault is liquidatable.\n * @param poolId The id of the pool that owns the vault that is being queried for liquidation.\n * @param collateralType The address of the collateral being held at the vault that is being queried for liquidation.\n * @return canVaultLiquidate A boolean with the response to the query.\n */\n function isVaultLiquidatable(\n uint128 poolId,\n address collateralType\n ) external returns (bool canVaultLiquidate);\n}\n" }, "contracts/interfaces/IMarketCollateralModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module for allowing markets to directly increase their credit capacity by providing their own collateral.\n */\ninterface IMarketCollateralModule {\n /**\n * @notice Thrown when a user attempts to deposit more collateral than that allowed by a market.\n */\n error InsufficientMarketCollateralDepositable(\n uint128 marketId,\n address collateralType,\n uint256 tokenAmountToDeposit\n );\n\n /**\n * @notice Thrown when a user attempts to withdraw more collateral from the market than what it has provided.\n */\n error InsufficientMarketCollateralWithdrawable(\n uint128 marketId,\n address collateralType,\n uint256 tokenAmountToWithdraw\n );\n\n /**\n * @notice Emitted when `amount` of collateral of type `collateralType` is deposited to market `marketId` by `sender`.\n * @param marketId The id of the market in which collateral was deposited.\n * @param collateralType The address of the collateral that was directly deposited in the market.\n * @param tokenAmount The amount of tokens that were deposited, denominated in the token's native decimal representation.\n * @param sender The address that triggered the deposit.\n */\n event MarketCollateralDeposited(\n uint128 indexed marketId,\n address indexed collateralType,\n uint256 tokenAmount,\n address indexed sender\n );\n\n /**\n * @notice Emitted when `amount` of collateral of type `collateralType` is withdrawn from market `marketId` by `sender`.\n * @param marketId The id of the market from which collateral was withdrawn.\n * @param collateralType The address of the collateral that was withdrawn from the market.\n * @param tokenAmount The amount of tokens that were withdrawn, denominated in the token's native decimal representation.\n * @param sender The address that triggered the withdrawal.\n */\n event MarketCollateralWithdrawn(\n uint128 indexed marketId,\n address indexed collateralType,\n uint256 tokenAmount,\n address indexed sender\n );\n\n /**\n * @notice Emitted when the system owner specifies the maximum depositable collateral of a given type in a given market.\n * @param marketId The id of the market for which the maximum was configured.\n * @param collateralType The address of the collateral for which the maximum was configured.\n * @param systemAmount The amount to which the maximum was set, denominated with 18 decimals of precision.\n * @param owner The owner of the system, which triggered the configuration change.\n */\n event MaximumMarketCollateralConfigured(\n uint128 indexed marketId,\n address indexed collateralType,\n uint256 systemAmount,\n address indexed owner\n );\n\n /**\n * @notice Allows a market to deposit collateral.\n * @param marketId The id of the market in which the collateral was directly deposited.\n * @param collateralType The address of the collateral that was deposited in the market.\n * @param amount The amount of collateral that was deposited, denominated in the token's native decimal representation.\n */\n function depositMarketCollateral(\n uint128 marketId,\n address collateralType,\n uint256 amount\n ) external;\n\n /**\n * @notice Allows a market to withdraw collateral that it has previously deposited.\n * @param marketId The id of the market from which the collateral was withdrawn.\n * @param collateralType The address of the collateral that was withdrawn from the market.\n * @param amount The amount of collateral that was withdrawn, denominated in the token's native decimal representation.\n */\n function withdrawMarketCollateral(\n uint128 marketId,\n address collateralType,\n uint256 amount\n ) external;\n\n /**\n * @notice Allow the system owner to configure the maximum amount of a given collateral type that a specified market is allowed to deposit.\n * @param marketId The id of the market for which the maximum is to be configured.\n * @param collateralType The address of the collateral for which the maximum is to be applied.\n * @param amount The amount that is to be set as the new maximum, denominated with 18 decimals of precision.\n */\n function configureMaximumMarketCollateral(\n uint128 marketId,\n address collateralType,\n uint256 amount\n ) external;\n\n /**\n * @notice Return the total maximum amount of a given collateral type that a specified market is allowed to deposit.\n * @param marketId The id of the market for which the maximum is being queried.\n * @param collateralType The address of the collateral for which the maximum is being queried.\n * @return amountD18 The maximum amount of collateral set for the market, denominated with 18 decimals of precision.\n */\n function getMaximumMarketCollateral(\n uint128 marketId,\n address collateralType\n ) external returns (uint256 amountD18);\n\n /**\n * @notice Return the total amount of a given collateral type that a specified market has deposited.\n * @param marketId The id of the market for which the directly deposited collateral amount is being queried.\n * @param collateralType The address of the collateral for which the amount is being queried.\n * @return amountD18 The total amount of collateral of this type delegated to the market, denominated with 18 decimals of precision.\n */\n function getMarketCollateralAmount(\n uint128 marketId,\n address collateralType\n ) external returns (uint256 amountD18);\n\n /**\n * @notice Return the total value of collateral that a specified market has deposited.\n * @param marketId The id of the market for which the directly deposited collateral amount is being queried.\n * @return valueD18 The total value of collateral deposited by the market, denominated with 18 decimals of precision.\n */\n function getMarketCollateralValue(uint128 marketId) external returns (uint256 valueD18);\n}\n" }, "contracts/interfaces/IMarketManagerModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title System-wide entry point for the management of markets connected to the system.\n */\ninterface IMarketManagerModule {\n /**\n * @notice Thrown when a market does not have enough liquidity for a withdrawal.\n */\n error NotEnoughLiquidity(uint128 marketId, uint256 amount);\n\n /**\n * @notice Thrown when an attempt to register a market that does not conform to the IMarket interface is made.\n */\n error IncorrectMarketInterface(address market);\n\n /**\n * @notice Emitted when a new market is registered in the system.\n * @param market The address of the external market that was registered in the system.\n * @param marketId The id with which the market was registered in the system.\n * @param sender The account that trigger the registration of the market.\n */\n event MarketRegistered(\n address indexed market,\n uint128 indexed marketId,\n address indexed sender\n );\n\n /**\n * @notice Emitted when a market deposits snxUSD in the system.\n * @param marketId The id of the market that deposited snxUSD in the system.\n * @param target The address of the account that provided the snxUSD in the deposit.\n * @param amount The amount of snxUSD deposited in the system, denominated with 18 decimals of precision.\n * @param market The address of the external market that is depositing.\n */\n event MarketUsdDeposited(\n uint128 indexed marketId,\n address indexed target,\n uint256 amount,\n address indexed market\n );\n\n /**\n * @notice Emitted when a market withdraws snxUSD from the system.\n * @param marketId The id of the market that withdrew snxUSD from the system.\n * @param target The address of the account that received the snxUSD in the withdrawal.\n * @param amount The amount of snxUSD withdrawn from the system, denominated with 18 decimals of precision.\n * @param market The address of the external market that is withdrawing.\n */\n event MarketUsdWithdrawn(\n uint128 indexed marketId,\n address indexed target,\n uint256 amount,\n address indexed market\n );\n\n /**\n * @notice Connects an external market to the system.\n * @dev Creates a Market object to track the external market, and returns the newly created market id.\n * @param market The address of the external market that is to be registered in the system.\n * @return newMarketId The id with which the market will be registered in the system.\n */\n function registerMarket(address market) external returns (uint128 newMarketId);\n\n /**\n * @notice Allows an external market connected to the system to deposit USD in the system.\n * @dev The system burns the incoming USD, increases the market's credit capacity, and reduces its issuance.\n * @dev See `IMarket`.\n * @param marketId The id of the market in which snxUSD will be deposited.\n * @param target The address of the account on who's behalf the deposit will be made.\n * @param amount The amount of snxUSD to be deposited, denominated with 18 decimals of precision.\n */\n function depositMarketUsd(uint128 marketId, address target, uint256 amount) external;\n\n /**\n * @notice Allows an external market connected to the system to withdraw snxUSD from the system.\n * @dev The system mints the requested snxUSD (provided that the market has sufficient credit), reduces the market's credit capacity, and increases its net issuance.\n * @dev See `IMarket`.\n * @param marketId The id of the market from which snxUSD will be withdrawn.\n * @param target The address of the account that will receive the withdrawn snxUSD.\n * @param amount The amount of snxUSD to be withdraw, denominated with 18 decimals of precision.\n */\n function withdrawMarketUsd(uint128 marketId, address target, uint256 amount) external;\n\n /**\n * @notice Returns the total withdrawable snxUSD amount for the specified market.\n * @param marketId The id of the market whose withdrawable USD amount is being queried.\n * @return withdrawableD18 The total amount of snxUSD that the market could withdraw at the time of the query, denominated with 18 decimals of precision.\n */\n function getWithdrawableMarketUsd(\n uint128 marketId\n ) external view returns (uint256 withdrawableD18);\n\n /**\n * @notice Returns the net issuance of the specified market (snxUSD withdrawn - snxUSD deposited).\n * @param marketId The id of the market whose net issuance is being queried.\n * @return issuanceD18 The net issuance of the market, denominated with 18 decimals of precision.\n */\n function getMarketNetIssuance(uint128 marketId) external view returns (int128 issuanceD18);\n\n /**\n * @notice Returns the reported debt of the specified market.\n * @param marketId The id of the market whose reported debt is being queried.\n * @return reportedDebtD18 The market's reported debt, denominated with 18 decimals of precision.\n */\n function getMarketReportedDebt(\n uint128 marketId\n ) external view returns (uint256 reportedDebtD18);\n\n /**\n * @notice Returns the total debt of the specified market.\n * @param marketId The id of the market whose debt is being queried.\n * @return totalDebtD18 The total debt of the market, denominated with 18 decimals of precision.\n */\n function getMarketTotalDebt(uint128 marketId) external view returns (int256 totalDebtD18);\n\n /**\n * @notice Returns the total snxUSD value of the collateral for the specified market.\n * @param marketId The id of the market whose collateral is being queried.\n * @return valueD18 The market's total snxUSD value of collateral, denominated with 18 decimals of precision.\n */\n function getMarketCollateral(uint128 marketId) external view returns (uint256 valueD18);\n\n /**\n * @notice Returns the value per share of the debt of the specified market.\n * @dev This is not a view function, and actually updates the entire debt distribution chain.\n * @param marketId The id of the market whose debt per share is being queried.\n * @return debtPerShareD18 The market's debt per share value, denominated with 18 decimals of precision.\n */\n function getMarketDebtPerShare(uint128 marketId) external returns (int256 debtPerShareD18);\n\n /**\n * @notice Returns wether the capacity of the specified market is locked.\n * @param marketId The id of the market whose capacity is being queried.\n * @return isLocked A boolean that is true if the market's capacity is locked at the time of the query.\n */\n function isMarketCapacityLocked(uint128 marketId) external view returns (bool isLocked);\n\n /**\n * @notice Update a market's current debt registration with the system.\n * This function is provided as an escape hatch for pool griefing, preventing\n * overwhelming the system with a series of very small pools and creating high gas\n * costs to update an account.\n * @param marketId the id of the market that needs pools bumped\n * @return finishedDistributing whether or not all bumpable pools have been bumped and target price has been reached\n */\n function distributeDebtToPools(\n uint128 marketId,\n uint256 maxIter\n ) external returns (bool finishedDistributing);\n}\n" }, "contracts/interfaces/IMulticallModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module that enables calling multiple methods of the system in a single transaction.\n */\ninterface IMulticallModule {\n /**\n * @notice Executes multiple transaction payloads in a single transaction.\n * @dev Each transaction is executed using `delegatecall`, and targets the system address.\n * @param data Array of calldata objects, one for each function that is to be called in the system.\n * @return results Array of each `delegatecall`'s response corresponding to the incoming calldata array.\n */\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\n}\n" }, "contracts/interfaces/IPoolConfigurationModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module that allows the system owner to mark official pools.\n */\ninterface IPoolConfigurationModule {\n /**\n * @notice Emitted when the system owner sets the preferred pool.\n * @param poolId The id of the pool that was set as preferred.\n */\n event PreferredPoolSet(uint256 poolId);\n\n /**\n * @notice Emitted when the system owner adds an approved pool.\n * @param poolId The id of the pool that was approved.\n */\n event PoolApprovedAdded(uint256 poolId);\n\n /**\n * @notice Emitted when the system owner removes an approved pool.\n * @param poolId The id of the pool that is no longer approved.\n */\n event PoolApprovedRemoved(uint256 poolId);\n\n /**\n * @notice Sets the unique system preferred pool.\n * @dev Note: The preferred pool does not receive any special treatment. It is only signaled as preferred here.\n * @param poolId The id of the pool that is to be set as preferred.\n */\n function setPreferredPool(uint128 poolId) external;\n\n /**\n * @notice Marks a pool as approved by the system owner.\n * @dev Approved pools do not receive any special treatment. They are only signaled as approved here.\n * @param poolId The id of the pool that is to be approved.\n */\n function addApprovedPool(uint128 poolId) external;\n\n /**\n * @notice Un-marks a pool as preferred by the system owner.\n * @param poolId The id of the pool that is to be no longer approved.\n */\n function removeApprovedPool(uint128 poolId) external;\n\n /**\n * @notice Retrieves the unique system preferred pool.\n * @return poolId The id of the pool that is currently set as preferred in the system.\n */\n function getPreferredPool() external view returns (uint128 poolId);\n\n /**\n * @notice Retrieves the pool that are approved by the system owner.\n * @return poolIds An array with all of the pool ids that are approved in the system.\n */\n function getApprovedPools() external view returns (uint256[] calldata poolIds);\n}\n" }, "contracts/interfaces/IPoolModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../storage/MarketConfiguration.sol\";\n\n/**\n * @title Module for the creation and management of pools.\n * @dev The pool owner can be specified during creation, can be transferred, and has credentials for configuring the pool.\n */\ninterface IPoolModule {\n /**\n * @notice Thrown when attempting to disconnect a market whose capacity is locked, and whose removal would cause a decrease in its associated pool's credit delegation proportion.\n */\n error CapacityLocked(uint256 marketId);\n\n /**\n * @notice Gets fired when pool will be created.\n * @param poolId The id of the newly created pool.\n * @param owner The owner of the newly created pool.\n * @param sender The address that triggered the creation of the pool.\n */\n event PoolCreated(uint128 indexed poolId, address indexed owner, address indexed sender);\n\n /**\n * @notice Gets fired when pool owner proposes a new owner.\n * @param poolId The id of the pool for which the nomination ocurred.\n * @param nominatedOwner The address that was nominated as the new owner of the pool.\n * @param owner The address of the current owner of the pool.\n */\n event PoolOwnerNominated(\n uint128 indexed poolId,\n address indexed nominatedOwner,\n address indexed owner\n );\n\n /**\n * @notice Gets fired when pool nominee accepts nomination.\n * @param poolId The id of the pool for which the owner nomination was accepted.\n * @param owner The address of the new owner of the pool, which accepted the nomination.\n */\n event PoolOwnershipAccepted(uint128 indexed poolId, address indexed owner);\n\n /**\n * @notice Gets fired when pool owner revokes nomination.\n * @param poolId The id of the pool in which the nomination was revoked.\n * @param owner The current owner of the pool.\n */\n event PoolNominationRevoked(uint128 indexed poolId, address indexed owner);\n\n /**\n * @notice Gets fired when pool nominee renounces nomination.\n * @param poolId The id of the pool for which the owner nomination was renounced.\n * @param owner The current owner of the pool.\n */\n event PoolNominationRenounced(uint128 indexed poolId, address indexed owner);\n\n /**\n * @notice Gets fired when pool name changes.\n * @param poolId The id of the pool whose name was updated.\n * @param name The new name of the pool.\n * @param sender The address that triggered the rename of the pool.\n */\n event PoolNameUpdated(uint128 indexed poolId, string name, address indexed sender);\n\n /**\n * @notice Gets fired when pool gets configured.\n * @param poolId The id of the pool whose configuration was set.\n * @param markets Array of configuration data of the markets that were connected to the pool.\n * @param sender The address that triggered the pool configuration.\n */\n event PoolConfigurationSet(\n uint128 indexed poolId,\n MarketConfiguration.Data[] markets,\n address indexed sender\n );\n\n /**\n * @notice Creates a pool with the requested pool id.\n * @param requestedPoolId The requested id for the new pool. Reverts if the id is not available.\n * @param owner The address that will own the newly created pool.\n */\n function createPool(uint128 requestedPoolId, address owner) external;\n\n /**\n * @notice Allows the pool owner to configure the pool.\n * @dev The pool's configuration is composed of an array of MarketConfiguration objects, which describe which markets the pool provides liquidity to, in what proportion, and to what extent.\n * @dev Incoming market ids need to be provided in ascending order.\n * @param poolId The id of the pool whose configuration is being set.\n * @param marketDistribution The array of market configuration objects that define the list of markets that are connected to the system.\n */\n function setPoolConfiguration(\n uint128 poolId,\n MarketConfiguration.Data[] memory marketDistribution\n ) external;\n\n /**\n * @notice Retrieves the MarketConfiguration of the specified pool.\n * @param poolId The id of the pool whose configuration is being queried.\n * @return markets The array of MarketConfiguration objects that describe the pool's configuration.\n */\n function getPoolConfiguration(\n uint128 poolId\n ) external view returns (MarketConfiguration.Data[] memory markets);\n\n /**\n * @notice Allows the owner of the pool to set the pool's name.\n * @param poolId The id of the pool whose name is being set.\n * @param name The new name to give to the pool.\n */\n function setPoolName(uint128 poolId, string memory name) external;\n\n /**\n * @notice Returns the pool's name.\n * @param poolId The id of the pool whose name is being queried.\n * @return poolName The current name of the pool.\n */\n function getPoolName(uint128 poolId) external view returns (string memory poolName);\n\n /**\n * @notice Allows the current pool owner to nominate a new owner.\n * @param nominatedOwner The address to nominate os the new pool owner.\n * @param poolId The id whose ownership is being transferred.\n */\n function nominatePoolOwner(address nominatedOwner, uint128 poolId) external;\n\n /**\n * @notice After a new pool owner has been nominated, allows it to accept the nomination and thus ownership of the pool.\n * @param poolId The id of the pool for which the caller is to accept ownership.\n */\n function acceptPoolOwnership(uint128 poolId) external;\n\n /**\n * @notice After a new pool owner has been nominated, allows it to reject the nomination.\n * @param poolId The id of the pool for which the new owner nomination is to be revoked.\n */\n function revokePoolNomination(uint128 poolId) external;\n\n /**\n * @notice Allows the current nominated owner to renounce the nomination.\n * @param poolId The id of the pool for which the caller is renouncing ownership nomination.\n */\n function renouncePoolNomination(uint128 poolId) external;\n\n /**\n * @notice Returns the current pool owner.\n * @param poolId The id of the pool whose ownership is being queried.\n * @return owner The current owner of the pool.\n */\n function getPoolOwner(uint128 poolId) external view returns (address owner);\n\n /**\n * @notice Returns the current nominated pool owner.\n * @param poolId The id of the pool whose nominated owner is being queried.\n * @return nominatedOwner The current nominated owner of the pool.\n */\n function getNominatedPoolOwner(uint128 poolId) external view returns (address nominatedOwner);\n\n /**\n * @notice Allows the system owner (not the pool owner) to set the system-wide minimum liquidity ratio.\n * @param minLiquidityRatio The new system-wide minimum liquidity ratio, denominated with 18 decimals of precision. (100% is represented by 1 followed by 18 zeros.)\n */\n function setMinLiquidityRatio(uint256 minLiquidityRatio) external;\n\n /**\n * @notice Retrieves the system-wide minimum liquidity ratio.\n * @return minRatioD18 The current system-wide minimum liquidity ratio, denominated with 18 decimals of precision. (100% is represented by 1 followed by 18 zeros.)\n */\n function getMinLiquidityRatio() external view returns (uint256 minRatioD18);\n}\n" }, "contracts/interfaces/IRewardsManagerModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module for connecting rewards distributors to vaults.\n */\ninterface IRewardsManagerModule {\n /**\n * @notice Emitted when a reward distributor returns `false` from `payout` indicating a problem\n * preventing the payout from being executed. In this case, it is advised to check with the\n * project maintainers, and possibly try again in the future.\n * @param distributor the distributor which originated the issue\n */\n error RewardUnavailable(address distributor);\n\n /**\n * @notice Emitted when the pool owner or an existing reward distributor sets up rewards for vault participants.\n * @param poolId The id of the pool on which rewards were distributed.\n * @param collateralType The collateral type of the pool on which rewards were distributed.\n * @param distributor The reward distributor associated to the rewards that were distributed.\n * @param amount The amount of rewards that were distributed.\n * @param start The date one which the rewards will begin to be claimable.\n * @param duration The time in which all of the distributed rewards will be claimable.\n */\n event RewardsDistributed(\n uint128 indexed poolId,\n address indexed collateralType,\n address distributor,\n uint256 amount,\n uint256 start,\n uint256 duration\n );\n\n /**\n * @notice Emitted when a vault participant claims rewards.\n * @param accountId The id of the account that claimed the rewards.\n * @param poolId The id of the pool where the rewards were claimed.\n * @param collateralType The address of the collateral used in the pool's rewards.\n * @param distributor The address of the rewards distributor associated with these rewards.\n * @param amount The amount of rewards that were claimed.\n */\n event RewardsClaimed(\n uint128 indexed accountId,\n uint128 indexed poolId,\n address indexed collateralType,\n address distributor,\n uint256 amount\n );\n\n /**\n * @notice Emitted when a new rewards distributor is registered.\n * @param poolId The id of the pool whose reward distributor was registered.\n * @param collateralType The address of the collateral used in the pool's rewards.\n * @param distributor The address of the newly registered reward distributor.\n */\n event RewardsDistributorRegistered(\n uint128 indexed poolId,\n address indexed collateralType,\n address indexed distributor\n );\n\n /**\n * @notice Emitted when an already registered rewards distributor is removed.\n * @param poolId The id of the pool whose reward distributor was registered.\n * @param collateralType The address of the collateral used in the pool's rewards.\n * @param distributor The address of the registered reward distributor.\n */\n event RewardsDistributorRemoved(\n uint128 indexed poolId,\n address indexed collateralType,\n address indexed distributor\n );\n\n /**\n * @notice Called by pool owner to register rewards for vault participants.\n * @param poolId The id of the pool whose rewards are to be managed by the specified distributor.\n * @param collateralType The address of the collateral used in the pool's rewards.\n * @param distributor The address of the reward distributor to be registered.\n */\n function registerRewardsDistributor(\n uint128 poolId,\n address collateralType,\n address distributor\n ) external;\n\n /**\n * @notice Called by pool owner to remove a registered rewards distributor for vault participants.\n * WARNING: if you remove a rewards distributor, the same address can never be re-registered again. If you\n * simply want to turn off\n * rewards, call `distributeRewards` with 0 emission. If you need to completely reset the rewards distributor\n * again, create a new rewards distributor at a new address and register the new one.\n * This function is provided since the number of rewards distributors added to an account is finite,\n * so you can remove an unused rewards distributor if need be.\n * NOTE: unclaimed rewards can still be claimed after a rewards distributor is removed (though any\n * rewards-over-time will be halted)\n * @param poolId The id of the pool whose rewards are to be managed by the specified distributor.\n * @param collateralType The address of the collateral used in the pool's rewards.\n * @param distributor The address of the reward distributor to be registered.\n */\n function removeRewardsDistributor(\n uint128 poolId,\n address collateralType,\n address distributor\n ) external;\n\n /**\n * @notice Called by a registered distributor to set up rewards for vault participants.\n * @dev Will revert if the caller is not a registered distributor.\n * @param poolId The id of the pool to distribute rewards to.\n * @param collateralType The address of the collateral used in the pool's rewards.\n * @param amount The amount of rewards to be distributed.\n * @param start The date at which the rewards will begin to be claimable.\n * @param duration The period after which all distributed rewards will be claimable.\n */\n function distributeRewards(\n uint128 poolId,\n address collateralType,\n uint256 amount,\n uint64 start,\n uint32 duration\n ) external;\n\n /**\n * @notice Allows a user with appropriate permissions to claim rewards associated with a position.\n * @param accountId The id of the account that is to claim the rewards.\n * @param poolId The id of the pool to claim rewards on.\n * @param collateralType The address of the collateral used in the pool's rewards.\n * @param distributor The address of the rewards distributor associated with the rewards being claimed.\n * @return amountClaimedD18 The amount of rewards that were available for the account and thus claimed.\n */\n function claimRewards(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n address distributor\n ) external returns (uint256 amountClaimedD18);\n\n /**\n * @notice For a given position, return the rewards that can currently be claimed.\n * @param poolId The id of the pool being queried.\n * @param collateralType The address of the collateral used in the pool's rewards.\n * @param accountId The id of the account whose available rewards are being queried.\n * @return claimableD18 An array of ids of the reward entries that are claimable by the position.\n * @return distributors An array with the addresses of the reward distributors associated with the claimable rewards.\n */\n function updateRewards(\n uint128 poolId,\n address collateralType,\n uint128 accountId\n ) external returns (uint256[] memory claimableD18, address[] memory distributors);\n\n /**\n * @notice Returns the number of individual units of amount emitted per second per share for the given poolId, collateralType, distributor vault.\n * @param poolId The id of the pool being queried.\n * @param collateralType The address of the collateral used in the pool's rewards.\n * @param distributor The address of the rewards distributor associated with the rewards in question.\n * @return rateD18 The queried rewards rate.\n */\n function getRewardRate(\n uint128 poolId,\n address collateralType,\n address distributor\n ) external view returns (uint256 rateD18);\n}\n" }, "contracts/interfaces/IUSDTokenModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-modules/contracts/interfaces/ITokenModule.sol\";\n\n/**\n * @title Module for managing the snxUSD token as an associated system.\n */\ninterface IUSDTokenModule is ITokenModule {\n /**\n * @notice Allows the core system to burn snxUSD held by the `from` address, provided that it has given allowance to `spender`.\n * @param from The address that holds the snxUSD to be burned.\n * @param spender The address to which the holder has given allowance to.\n * @param amount The amount of snxUSD to be burned, denominated with 18 decimals of precision.\n */\n function burnWithAllowance(address from, address spender, uint256 amount) external;\n\n /**\n * @notice Allows users to transfer tokens cross-chain using CCIP. This is disabled until _CCIP_CHAINLINK_SEND is set in UtilsModule. This is currently included for testing purposes. Functionality will change, including fee collection, as CCIP continues development.\n * @param destChainId The id of the chain where tokens are to be transferred to.\n * @param to The destination address in the target chain.\n * @param amount The amount of tokens to be transferred, denominated with 18 decimals of precision.\n * @return feesPaidD18 The amount of fees paid in the cross-chain transfer, denominated with 18 decimals of precision.\n */\n function transferCrossChain(\n uint256 destChainId,\n address to,\n uint256 amount\n ) external returns (uint256 feesPaidD18);\n}\n" }, "contracts/interfaces/IUtilsModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Module with assorted utility functions.\n */\ninterface IUtilsModule {\n /**\n * @notice Configure CCIP addresses on the stablecoin.\n * @param ccipSend The address on this chain to which CCIP messages will be sent.\n * @param ccipReceive The address on this chain from which CCIP messages will be received.\n * @param ccipTokenPool The address where CCIP fees will be sent to when sending and receiving cross chain messages.\n */\n function registerCcip(address ccipSend, address ccipReceive, address ccipTokenPool) external;\n\n /**\n * @notice Configure the system's single oracle manager address.\n * @param oracleManagerAddress The address of the oracle manager.\n */\n function configureOracleManager(address oracleManagerAddress) external;\n\n /**\n * @notice Configure a generic value in the KV system\n * @param k the key of the value to set\n * @param v the value that the key should be set to\n */\n function setConfig(bytes32 k, bytes32 v) external;\n\n /**\n * @notice Read a generic value from the KV system\n * @param k the key to read\n * @return v the value set on the specified k\n */\n function getConfig(bytes32 k) external view returns (bytes32 v);\n}\n" }, "contracts/interfaces/IVaultModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Allows accounts to delegate collateral to a pool.\n * @dev Delegation updates the account's position in the vault that corresponds to the associated pool and collateral type pair.\n * @dev A pool contains one vault for each collateral type it supports, and vaults are not shared between pools.\n */\ninterface IVaultModule {\n /**\n * @notice Thrown when attempting to delegate collateral to a vault with a leverage amount that is not supported by the system.\n */\n error InvalidLeverage(uint256 leverage);\n\n /**\n * @notice Thrown when attempting to delegate collateral to a market whose capacity is locked.\n */\n error CapacityLocked(uint256 marketId);\n\n /**\n * @notice Thrown when the specified new collateral amount to delegate to the vault equals the current existing amount.\n */\n error InvalidCollateralAmount();\n\n /**\n * @notice Emitted when {sender} updates the delegation of collateral in the specified liquidity position.\n * @param accountId The id of the account whose position was updated.\n * @param poolId The id of the pool in which the position was updated.\n * @param collateralType The address of the collateral associated to the position.\n * @param amount The new amount of the position, denominated with 18 decimals of precision.\n * @param leverage The new leverage value of the position, denominated with 18 decimals of precision.\n * @param sender The address that triggered the update of the position.\n */\n event DelegationUpdated(\n uint128 indexed accountId,\n uint128 indexed poolId,\n address collateralType,\n uint256 amount,\n uint256 leverage,\n address indexed sender\n );\n\n /**\n * @notice Updates an account's delegated collateral amount for the specified pool and collateral type pair.\n * @param accountId The id of the account associated with the position that will be updated.\n * @param poolId The id of the pool associated with the position.\n * @param collateralType The address of the collateral used in the position.\n * @param amount The new amount of collateral delegated in the position, denominated with 18 decimals of precision.\n * @param leverage The new leverage amount used in the position, denominated with 18 decimals of precision.\n *\n * Requirements:\n *\n * - `msg.sender` must be the owner of the account, have the `ADMIN` permission, or have the `DELEGATE` permission.\n * - If increasing the amount delegated, it must not exceed the available collateral (`getAccountAvailableCollateral`) associated with the account.\n * - If decreasing the amount delegated, the liquidity position must have a collateralization ratio greater than the target collateralization ratio for the corresponding collateral type.\n *\n * Emits a {DelegationUpdated} event.\n */\n function delegateCollateral(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n uint256 amount,\n uint256 leverage\n ) external;\n\n /**\n * @notice Returns the collateralization ratio of the specified liquidity position. If debt is negative, this function will return 0.\n * @dev Call this function using `callStatic` to treat it as a view function.\n * @dev The return value is a percentage with 18 decimals places.\n * @param accountId The id of the account whose collateralization ratio is being queried.\n * @param poolId The id of the pool in which the account's position is held.\n * @param collateralType The address of the collateral used in the queried position.\n * @return ratioD18 The collateralization ratio of the position (collateral / debt), denominated with 18 decimals of precision.\n */\n function getPositionCollateralRatio(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n ) external returns (uint256 ratioD18);\n\n /**\n * @notice Returns the debt of the specified liquidity position. Credit is expressed as negative debt.\n * @dev This is not a view function, and actually updates the entire debt distribution chain.\n * @dev Call this function using `callStatic` to treat it as a view function.\n * @param accountId The id of the account being queried.\n * @param poolId The id of the pool in which the account's position is held.\n * @param collateralType The address of the collateral used in the queried position.\n * @return debtD18 The amount of debt held by the position, denominated with 18 decimals of precision.\n */\n function getPositionDebt(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n ) external returns (int256 debtD18);\n\n /**\n * @notice Returns the amount and value of the collateral associated with the specified liquidity position.\n * @dev Call this function using `callStatic` to treat it as a view function.\n * @dev collateralAmount is represented as an integer with 18 decimals.\n * @dev collateralValue is represented as an integer with the number of decimals specified by the collateralType.\n * @param accountId The id of the account being queried.\n * @param poolId The id of the pool in which the account's position is held.\n * @param collateralType The address of the collateral used in the queried position.\n * @return collateralAmountD18 The amount of collateral used in the position, denominated with 18 decimals of precision.\n * @return collateralValueD18 The value of collateral used in the position, denominated with 18 decimals of precision.\n */\n function getPositionCollateral(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n ) external view returns (uint256 collateralAmountD18, uint256 collateralValueD18);\n\n /**\n * @notice Returns all information pertaining to a specified liquidity position in the vault module.\n * @param accountId The id of the account being queried.\n * @param poolId The id of the pool in which the account's position is held.\n * @param collateralType The address of the collateral used in the queried position.\n * @return collateralAmountD18 The amount of collateral used in the position, denominated with 18 decimals of precision.\n * @return collateralValueD18 The value of the collateral used in the position, denominated with 18 decimals of precision.\n * @return debtD18 The amount of debt held in the position, denominated with 18 decimals of precision.\n * @return collateralizationRatioD18 The collateralization ratio of the position (collateral / debt), denominated with 18 decimals of precision.\n **/\n function getPosition(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n )\n external\n returns (\n uint256 collateralAmountD18,\n uint256 collateralValueD18,\n int256 debtD18,\n uint256 collateralizationRatioD18\n );\n\n /**\n * @notice Returns the total debt (or credit) that the vault is responsible for. Credit is expressed as negative debt.\n * @dev This is not a view function, and actually updates the entire debt distribution chain.\n * @dev Call this function using `callStatic` to treat it as a view function.\n * @param poolId The id of the pool that owns the vault whose debt is being queried.\n * @param collateralType The address of the collateral of the associated vault.\n * @return debtD18 The overall debt of the vault, denominated with 18 decimals of precision.\n **/\n function getVaultDebt(uint128 poolId, address collateralType) external returns (int256 debtD18);\n\n /**\n * @notice Returns the amount and value of the collateral held by the vault.\n * @dev Call this function using `callStatic` to treat it as a view function.\n * @dev collateralAmount is represented as an integer with 18 decimals.\n * @dev collateralValue is represented as an integer with the number of decimals specified by the collateralType.\n * @param poolId The id of the pool that owns the vault whose collateral is being queried.\n * @param collateralType The address of the collateral of the associated vault.\n * @return collateralAmountD18 The collateral amount of the vault, denominated with 18 decimals of precision.\n * @return collateralValueD18 The collateral value of the vault, denominated with 18 decimals of precision.\n */\n function getVaultCollateral(\n uint128 poolId,\n address collateralType\n ) external returns (uint256 collateralAmountD18, uint256 collateralValueD18);\n\n /**\n * @notice Returns the collateralization ratio of the vault. If debt is negative, this function will return 0.\n * @dev Call this function using `callStatic` to treat it as a view function.\n * @dev The return value is a percentage with 18 decimals places.\n * @param poolId The id of the pool that owns the vault whose collateralization ratio is being queried.\n * @param collateralType The address of the collateral of the associated vault.\n * @return ratioD18 The collateralization ratio of the vault, denominated with 18 decimals of precision.\n */\n function getVaultCollateralRatio(\n uint128 poolId,\n address collateralType\n ) external returns (uint256 ratioD18);\n}\n" }, "contracts/mocks/AggregatorV3Mock.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../interfaces/external/IAggregatorV3Interface.sol\";\n\ncontract AggregatorV3Mock is IAggregatorV3Interface {\n uint80 private _roundId;\n uint256 private _timestamp;\n uint256 private _price;\n\n function decimals() external pure override returns (uint8) {\n return 18;\n }\n\n function description() external pure override returns (string memory) {\n return \"Fake price feed\";\n }\n\n function version() external pure override returns (uint256) {\n return 3;\n }\n\n function mockSetCurrentPrice(uint256 currentPrice) external {\n _price = currentPrice;\n _timestamp = block.timestamp;\n _roundId++;\n }\n\n // getRoundData and latestRoundData should both raise \"No data present\"\n // if they do not have data to report, instead of returning unset values\n // which could be misinterpreted as actual reported values.\n function getRoundData(\n uint80\n )\n external\n view\n override\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n )\n {\n return this.latestRoundData();\n }\n\n function latestRoundData()\n external\n view\n override\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n )\n {\n // solhint-disable-next-line numcast/safe-cast\n return (_roundId, int256(_price), _timestamp, _timestamp, _roundId);\n }\n\n function setRoundId(uint80 roundId) external {\n _roundId = roundId;\n }\n\n function setTimestamp(uint256 timestamp) external {\n _timestamp = timestamp;\n }\n}\n" }, "contracts/mocks/CollateralMock.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/token/ERC20.sol\";\n\ncontract CollateralMock is ERC20 {\n function initialize(\n string memory tokenName,\n string memory tokenSymbol,\n uint8 tokenDecimals\n ) public {\n _initialize(tokenName, tokenSymbol, tokenDecimals);\n }\n\n function burn(uint256 amount) external {\n _burn(msg.sender, amount);\n }\n\n function mint(address recipient, uint256 amount) external {\n _mint(recipient, amount);\n }\n}\n" }, "contracts/mocks/CollateralMockWithoutDecimals.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\ncontract CollateralMockWithoutDecimals {\n bytes32 private constant _SLOT_ERC20_STORAGE =\n keccak256(abi.encode(\"io.synthetix.core-contracts.ERC20\"));\n\n struct Data {\n string name;\n string symbol;\n mapping(address => uint256) balanceOf;\n mapping(address => mapping(address => uint256)) allowance;\n uint256 totalSupply;\n }\n\n function load() internal pure returns (Data storage store) {\n bytes32 s = _SLOT_ERC20_STORAGE;\n assembly {\n store.slot := s\n }\n }\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n error InsufficientAllowance(uint256 required, uint256 existing);\n error InsufficientBalance(uint256 required, uint256 existing);\n error AlreadyInitialized();\n error NotInitialized();\n\n function initialize(string memory tokenName, string memory tokenSymbol) public {\n _initialize(tokenName, tokenSymbol);\n }\n\n function burn(uint256 amount) external {\n _burn(msg.sender, amount);\n }\n\n function mint(address recipient, uint256 amount) external {\n _mint(recipient, amount);\n }\n\n function name() external view returns (string memory) {\n return load().name;\n }\n\n function symbol() external view returns (string memory) {\n return load().symbol;\n }\n\n /**\n * @dev decimals() was intentionally removed from this mock contract.\n */\n\n // function decimals() external view returns (uint8) {}\n\n function totalSupply() external view returns (uint256) {\n return load().totalSupply;\n }\n\n function allowance(address owner, address spender) public view returns (uint256) {\n return load().allowance[owner][spender];\n }\n\n function balanceOf(address owner) public view returns (uint256) {\n return load().balanceOf[owner];\n }\n\n function approve(address spender, uint256 amount) public returns (bool) {\n _approve(msg.sender, spender, amount);\n return true;\n }\n\n function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {\n uint256 currentAllowance = load().allowance[msg.sender][spender];\n _approve(msg.sender, spender, currentAllowance + addedValue);\n\n return true;\n }\n\n function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {\n uint256 currentAllowance = load().allowance[msg.sender][spender];\n _approve(msg.sender, spender, currentAllowance - subtractedValue);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public returns (bool) {\n _transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(address from, address to, uint256 amount) external returns (bool) {\n return _transferFrom(from, to, amount);\n }\n\n function _transferFrom(address from, address to, uint256 amount) internal returns (bool) {\n Data storage store = load();\n\n uint256 currentAllowance = store.allowance[from][msg.sender];\n if (currentAllowance < amount) {\n revert InsufficientAllowance(amount, currentAllowance);\n }\n\n unchecked {\n store.allowance[from][msg.sender] -= amount;\n }\n\n _transfer(from, to, amount);\n\n return true;\n }\n\n function _transfer(address from, address to, uint256 amount) internal {\n Data storage store = load();\n\n uint256 accountBalance = store.balanceOf[from];\n if (accountBalance < amount) {\n revert InsufficientBalance(amount, accountBalance);\n }\n\n // We are now sure that we can perform this operation safely\n // since it didn't revert in the previous step.\n // The total supply cannot exceed the maximum value of uint256,\n // thus we can now perform accounting operations in unchecked mode.\n unchecked {\n store.balanceOf[from] -= amount;\n store.balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n }\n\n function _approve(address owner, address spender, uint256 amount) internal {\n load().allowance[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n function _mint(address to, uint256 amount) internal {\n Data storage store = load();\n\n store.totalSupply += amount;\n\n // No need for overflow check since it is done in the previous step\n unchecked {\n store.balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal {\n Data storage store = load();\n\n uint256 accountBalance = store.balanceOf[from];\n if (accountBalance < amount) {\n revert InsufficientBalance(amount, accountBalance);\n }\n\n // No need for underflow check since it would have occured in the previous step\n unchecked {\n store.balanceOf[from] -= amount;\n store.totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n\n function _initialize(string memory tokenName, string memory tokenSymbol) internal {\n Data storage store = load();\n\n if (bytes(store.name).length > 0 || bytes(store.symbol).length > 0) {\n revert AlreadyInitialized();\n }\n\n store.name = tokenName;\n store.symbol = tokenSymbol;\n }\n}\n" }, "contracts/mocks/MockMarket.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/DecimalMath.sol\";\nimport \"@synthetixio/core-contracts/contracts/interfaces/IERC20.sol\";\nimport \"../interfaces/external/IMarket.sol\";\nimport \"../interfaces/IMarketManagerModule.sol\";\nimport \"../interfaces/IAssociateDebtModule.sol\";\nimport \"../interfaces/IMarketCollateralModule.sol\";\n\ncontract MockMarket is IMarket {\n using DecimalMath for uint256;\n\n uint256 private _reportedDebt;\n uint256 private _locked;\n uint256 private _price;\n\n address private _proxy;\n uint128 private _marketId;\n\n function initialize(address proxy, uint128 marketId, uint256 initialPrice) external {\n _proxy = proxy;\n _marketId = marketId;\n _price = initialPrice;\n }\n\n function callAssociateDebt(\n uint128 poolId,\n address collateralType,\n uint128 accountId,\n uint256 amount\n ) external {\n IAssociateDebtModule(_proxy).associateDebt(\n _marketId,\n poolId,\n collateralType,\n accountId,\n amount\n );\n }\n\n function buySynth(uint256 amount) external {\n _reportedDebt += amount;\n uint256 toDeposit = amount.divDecimal(_price);\n IMarketManagerModule(_proxy).depositMarketUsd(_marketId, msg.sender, toDeposit);\n }\n\n function sellSynth(uint256 amount) external {\n _reportedDebt -= amount;\n uint256 toDeposit = amount.divDecimal(_price);\n IMarketManagerModule(_proxy).withdrawMarketUsd(_marketId, msg.sender, toDeposit);\n }\n\n function depositUsd(uint256 amount) external {\n IMarketManagerModule(_proxy).depositMarketUsd(_marketId, msg.sender, amount);\n }\n\n function withdrawUsd(uint256 amount) external {\n IMarketManagerModule(_proxy).withdrawMarketUsd(_marketId, msg.sender, amount);\n }\n\n function setReportedDebt(uint256 newReportedDebt) external {\n _reportedDebt = newReportedDebt;\n }\n\n function setLocked(uint256 newLocked) external {\n _locked = newLocked;\n }\n\n function reportedDebt(uint128) external view override returns (uint256) {\n return _reportedDebt;\n }\n\n function name(uint128) external pure override returns (string memory) {\n return \"MockMarket\";\n }\n\n function locked(uint128) external view override returns (uint256) {\n return _locked;\n }\n\n function setPrice(uint256 newPrice) external {\n _price = newPrice;\n }\n\n function price() external view returns (uint256) {\n return _price;\n }\n\n function depositCollateral(address collateralType, uint256 amount) external {\n IERC20(collateralType).transferFrom(msg.sender, address(this), amount);\n IERC20(collateralType).approve(_proxy, amount);\n IMarketCollateralModule(_proxy).depositMarketCollateral(_marketId, collateralType, amount);\n }\n\n function withdrawCollateral(address collateralType, uint256 amount) external {\n IMarketCollateralModule(_proxy).withdrawMarketCollateral(_marketId, collateralType, amount);\n IERC20(collateralType).transfer(msg.sender, amount);\n }\n\n function name(uint256) external pure returns (string memory) {\n return \"Mock Market\";\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(\n bytes4 interfaceId\n ) public view virtual override(IERC165) returns (bool) {\n return\n interfaceId == type(IMarket).interfaceId ||\n interfaceId == this.supportsInterface.selector;\n }\n}\n" }, "contracts/mocks/RewardDistributorMock.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/interfaces/IERC20.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/AccessError.sol\";\n\nimport \"../interfaces/IRewardsManagerModule.sol\";\nimport \"../interfaces/external/IRewardDistributor.sol\";\n\ncontract RewardDistributorMock is IRewardDistributor {\n address private _rewardManager;\n address private _token;\n string private _name;\n\n bool public shouldFailPayout;\n\n function initialize(address rewardManager, address token_, string memory name_) public {\n _rewardManager = rewardManager;\n _token = token_;\n _name = name_;\n }\n\n function name() public view override returns (string memory) {\n return _name;\n }\n\n function token() public view override returns (address) {\n return _token;\n }\n\n function setShouldFailPayout(bool fail) external {\n shouldFailPayout = fail;\n }\n\n function payout(\n uint128,\n uint128,\n address,\n address sender,\n uint256 amount\n ) external returns (bool) {\n // IMPORTANT: In production, this function should revert if msg.sender is not the Synthetix CoreProxy address.\n if (msg.sender != _rewardManager) {\n revert AccessError.Unauthorized(msg.sender);\n }\n IERC20(_token).transfer(sender, amount);\n return !shouldFailPayout;\n }\n\n function distributeRewards(\n uint128 poolId,\n address collateralType,\n uint256 amount,\n uint64 start,\n uint32 duration\n ) public {\n IRewardsManagerModule(_rewardManager).distributeRewards(\n poolId,\n collateralType,\n amount,\n start,\n duration\n );\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(\n bytes4 interfaceId\n ) public view virtual override(IERC165) returns (bool) {\n return\n interfaceId == type(IRewardDistributor).interfaceId ||\n interfaceId == this.supportsInterface.selector;\n }\n}\n" }, "contracts/modules/account/AccountTokenModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-modules/contracts/modules/NftModule.sol\";\nimport \"../../../contracts/interfaces/IAccountTokenModule.sol\";\nimport \"../../../contracts/interfaces/IAccountModule.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\n/**\n * @title Module with custom NFT logic for the account token.\n * @dev See IAccountTokenModule.\n */\ncontract AccountTokenModule is IAccountTokenModule, NftModule {\n using SafeCastU256 for uint256;\n\n /**\n * @dev Updates account RBAC storage to track the current owner of the token.\n */\n function _postTransfer(\n address, // from (unused)\n address to,\n uint256 tokenId\n ) internal virtual override {\n IAccountModule(OwnableStorage.getOwner()).notifyAccountTransfer(to, tokenId.to128());\n }\n}\n" }, "contracts/modules/associated-systems/AssociatedSystemsModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport {AssociatedSystemsModule as BaseAssociatedSystemsModule} from \"@synthetixio/core-modules/contracts/modules/AssociatedSystemsModule.sol\";\n\n/**\n * @title Module for connecting to other systems.\n * See core-modules/../AssociatedSystemsModule\n */\n// solhint-disable-next-line no-empty-blocks\ncontract AssociatedSystemsModule is BaseAssociatedSystemsModule {\n\n}\n" }, "contracts/modules/common/OwnerModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport {OwnerModule as BaseOwnerModule} from \"@synthetixio/core-modules/contracts/modules/OwnerModule.sol\";\n\n/**\n * @title Module for owner based access control.\n * See core-modules/../OwnerModule\n */\n// solhint-disable-next-line no-empty-blocks\ncontract OwnerModule is BaseOwnerModule {\n\n}\n" }, "contracts/modules/common/UpgradeModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport {UpgradeModule as BaseUpgradeModule} from \"@synthetixio/core-modules/contracts/modules/UpgradeModule.sol\";\n\n/**\n * @title Module UUPS type upgradeability.\n * See core-modules/../UpgradeModule\n */\n// solhint-disable-next-line no-empty-blocks\ncontract UpgradeModule is BaseUpgradeModule {\n\n}\n" }, "contracts/modules/core/AccountModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-modules/contracts/storage/AssociatedSystem.sol\";\n\nimport \"../../interfaces/IAccountModule.sol\";\nimport \"../../interfaces/IAccountTokenModule.sol\";\nimport \"../../storage/Account.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\n/**\n * @title Module for managing accounts.\n * @dev See IAccountModule.\n */\ncontract AccountModule is IAccountModule {\n using SetUtil for SetUtil.AddressSet;\n using SetUtil for SetUtil.Bytes32Set;\n using AccountRBAC for AccountRBAC.Data;\n using Account for Account.Data;\n\n bytes32 private constant _ACCOUNT_SYSTEM = \"accountNft\";\n\n bytes32 private constant _CREATE_ACCOUNT_FEATURE_FLAG = \"createAccount\";\n\n /**\n * @inheritdoc IAccountModule\n */\n function getAccountTokenAddress() public view override returns (address) {\n return AssociatedSystem.load(_ACCOUNT_SYSTEM).proxy;\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function getAccountPermissions(\n uint128 accountId\n ) external view returns (AccountPermissions[] memory accountPerms) {\n AccountRBAC.Data storage accountRbac = Account.load(accountId).rbac;\n\n uint256 allPermissionsLength = accountRbac.permissionAddresses.length();\n accountPerms = new AccountPermissions[](allPermissionsLength);\n for (uint256 i = 1; i <= allPermissionsLength; i++) {\n address permissionAddress = accountRbac.permissionAddresses.valueAt(i);\n accountPerms[i - 1] = AccountPermissions({\n user: permissionAddress,\n permissions: accountRbac.permissions[permissionAddress].values()\n });\n }\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function createAccount(uint128 requestedAccountId) external override {\n FeatureFlag.ensureAccessToFeature(_CREATE_ACCOUNT_FEATURE_FLAG);\n IAccountTokenModule accountTokenModule = IAccountTokenModule(getAccountTokenAddress());\n accountTokenModule.safeMint(msg.sender, requestedAccountId, \"\");\n\n Account.create(requestedAccountId, msg.sender);\n\n emit AccountCreated(requestedAccountId, msg.sender);\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function notifyAccountTransfer(address to, uint128 accountId) external override {\n _onlyAccountToken();\n\n Account.Data storage account = Account.load(accountId);\n\n address[] memory permissionedAddresses = account.rbac.permissionAddresses.values();\n for (uint i = 0; i < permissionedAddresses.length; i++) {\n account.rbac.revokeAllPermissions(permissionedAddresses[i]);\n }\n\n account.rbac.setOwner(to);\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function hasPermission(\n uint128 accountId,\n bytes32 permission,\n address user\n ) public view override returns (bool) {\n return Account.load(accountId).rbac.hasPermission(permission, user);\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function isAuthorized(\n uint128 accountId,\n bytes32 permission,\n address user\n ) public view override returns (bool) {\n return Account.load(accountId).rbac.authorized(permission, user);\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function grantPermission(\n uint128 accountId,\n bytes32 permission,\n address user\n ) external override {\n AccountRBAC.isPermissionValid(permission);\n\n Account.Data storage account = Account.loadAccountAndValidatePermission(\n accountId,\n AccountRBAC._ADMIN_PERMISSION\n );\n\n account.rbac.grantPermission(permission, user);\n\n emit PermissionGranted(accountId, permission, user, msg.sender);\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function revokePermission(\n uint128 accountId,\n bytes32 permission,\n address user\n ) external override {\n Account.Data storage account = Account.loadAccountAndValidatePermission(\n accountId,\n AccountRBAC._ADMIN_PERMISSION\n );\n\n account.rbac.revokePermission(permission, user);\n\n emit PermissionRevoked(accountId, permission, user, msg.sender);\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function renouncePermission(uint128 accountId, bytes32 permission) external override {\n if (!Account.load(accountId).rbac.hasPermission(permission, msg.sender)) {\n revert PermissionNotGranted(accountId, permission, msg.sender);\n }\n\n Account.load(accountId).rbac.revokePermission(permission, msg.sender);\n\n emit PermissionRevoked(accountId, permission, msg.sender, msg.sender);\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function getAccountOwner(uint128 accountId) public view returns (address) {\n return Account.load(accountId).rbac.owner;\n }\n\n /**\n * @inheritdoc IAccountModule\n */\n function getAccountLastInteraction(uint128 accountId) external view returns (uint256) {\n return Account.load(accountId).lastInteraction;\n }\n\n /**\n * @dev Reverts if the caller is not the account token managed by this module.\n */\n // Note: Disabling Solidity warning, not sure why it suggests pure mutability.\n // solc-ignore-next-line func-mutability\n function _onlyAccountToken() internal view {\n if (msg.sender != address(getAccountTokenAddress())) {\n revert OnlyAccountTokenProxy(msg.sender);\n }\n }\n}\n" }, "contracts/modules/core/AssociateDebtModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../../interfaces/IAssociateDebtModule.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/utils/DecimalMath.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\nimport \"@synthetixio/core-contracts/contracts/token/ERC20Helper.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/AccessError.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\nimport \"../../storage/Account.sol\";\nimport \"../../storage/Pool.sol\";\n\n/**\n * @title Module for associating debt with the system.\n * @dev See IAssociateDebtModule.\n */\ncontract AssociateDebtModule is IAssociateDebtModule {\n using DecimalMath for uint256;\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n using ERC20Helper for address;\n using Distribution for Distribution.Data;\n using Pool for Pool.Data;\n using Vault for Vault.Data;\n using VaultEpoch for VaultEpoch.Data;\n using CollateralConfiguration for CollateralConfiguration.Data;\n using ScalableMapping for ScalableMapping.Data;\n\n bytes32 private constant _USD_TOKEN = \"USDToken\";\n bytes32 private constant _ASSOCIATE_DEBT_FEATURE_FLAG = \"associateDebt\";\n\n /**\n * @inheritdoc IAssociateDebtModule\n */\n function associateDebt(\n uint128 marketId,\n uint128 poolId,\n address collateralType,\n uint128 accountId,\n uint256 amount\n ) external returns (int256) {\n FeatureFlag.ensureAccessToFeature(_ASSOCIATE_DEBT_FEATURE_FLAG);\n Account.exists(accountId);\n\n Pool.Data storage poolData = Pool.load(poolId);\n VaultEpoch.Data storage epochData = poolData.vaults[collateralType].currentEpoch();\n Market.Data storage marketData = Market.load(marketId);\n\n if (msg.sender != marketData.marketAddress) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n // The market must appear in pool configuration of the specified position\n if (!poolData.hasMarket(marketId)) {\n revert NotFundedByPool(marketId, poolId);\n }\n\n // Refresh latest account debt\n poolData.updateAccountDebt(collateralType, accountId);\n\n // Remove the debt we're about to assign to a specific position, pro-rata\n epochData.distributeDebtToAccounts(-amount.toInt());\n\n // Assign this debt to the specified position\n int256 updatedDebt = epochData.assignDebtToAccount(accountId, amount.toInt());\n\n (, uint256 actorCollateralValue) = poolData.currentAccountCollateral(\n collateralType,\n accountId\n );\n\n // Reverts if this debt increase would make the position liquidatable\n _verifyCollateralRatio(\n collateralType,\n updatedDebt > 0 ? updatedDebt.toUint() : 0,\n actorCollateralValue\n );\n\n emit DebtAssociated(marketId, poolId, collateralType, accountId, amount, updatedDebt);\n\n return updatedDebt;\n }\n\n /**\n * @dev Reverts if a collateral ratio would be liquidatable.\n */\n function _verifyCollateralRatio(\n address collateralType,\n uint256 debt,\n uint256 collateralValue\n ) internal view {\n uint256 liquidationRatio = CollateralConfiguration.load(collateralType).liquidationRatioD18;\n if (debt != 0 && collateralValue.divDecimal(debt) < liquidationRatio) {\n revert InsufficientCollateralRatio(\n collateralValue,\n debt,\n collateralValue.divDecimal(debt),\n liquidationRatio\n );\n }\n }\n}\n" }, "contracts/modules/core/CollateralConfigurationModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\n\nimport \"../../interfaces/ICollateralConfigurationModule.sol\";\nimport \"../../storage/CollateralConfiguration.sol\";\n\n/**\n * @title Module for configuring system wide collateral.\n * @dev See ICollateralConfigurationModule.\n */\ncontract CollateralConfigurationModule is ICollateralConfigurationModule {\n using SetUtil for SetUtil.AddressSet;\n using CollateralConfiguration for CollateralConfiguration.Data;\n\n /**\n * @inheritdoc ICollateralConfigurationModule\n */\n function configureCollateral(CollateralConfiguration.Data memory config) external override {\n OwnableStorage.onlyOwner();\n\n CollateralConfiguration.set(config);\n\n emit CollateralConfigured(config.tokenAddress, config);\n }\n\n /**\n * @inheritdoc ICollateralConfigurationModule\n */\n function getCollateralConfigurations(\n bool hideDisabled\n ) external view override returns (CollateralConfiguration.Data[] memory) {\n SetUtil.AddressSet storage collateralTypes = CollateralConfiguration\n .loadAvailableCollaterals();\n\n uint256 numCollaterals = collateralTypes.length();\n CollateralConfiguration.Data[]\n memory filteredCollaterals = new CollateralConfiguration.Data[](numCollaterals);\n\n uint256 collateralsIdx;\n for (uint256 i = 1; i <= numCollaterals; i++) {\n address collateralType = collateralTypes.valueAt(i);\n\n CollateralConfiguration.Data storage collateral = CollateralConfiguration.load(\n collateralType\n );\n\n if (!hideDisabled || collateral.depositingEnabled) {\n filteredCollaterals[collateralsIdx++] = collateral;\n }\n }\n\n return filteredCollaterals;\n }\n\n /**\n * @inheritdoc ICollateralConfigurationModule\n */\n // Note: Disabling Solidity warning, not sure why it suggests pure mutability.\n // solc-ignore-next-line func-mutability\n function getCollateralConfiguration(\n address collateralType\n ) external view override returns (CollateralConfiguration.Data memory) {\n return CollateralConfiguration.load(collateralType);\n }\n\n /**\n * @inheritdoc ICollateralConfigurationModule\n */\n function getCollateralPrice(address collateralType) external view override returns (uint256) {\n return\n CollateralConfiguration.getCollateralPrice(\n CollateralConfiguration.load(collateralType)\n );\n }\n}\n" }, "contracts/modules/core/CollateralModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/token/ERC20Helper.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/ArrayError.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/ParameterError.sol\";\n\nimport \"../../interfaces/ICollateralModule.sol\";\n\nimport \"../../storage/Account.sol\";\nimport \"../../storage/CollateralConfiguration.sol\";\nimport \"../../storage/Config.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\n/**\n * @title Module for managing user collateral.\n * @dev See ICollateralModule.\n */\ncontract CollateralModule is ICollateralModule {\n using SetUtil for SetUtil.AddressSet;\n using ERC20Helper for address;\n using CollateralConfiguration for CollateralConfiguration.Data;\n using Account for Account.Data;\n using AccountRBAC for AccountRBAC.Data;\n using Collateral for Collateral.Data;\n using SafeCastU256 for uint256;\n\n bytes32 private constant _DEPOSIT_FEATURE_FLAG = \"deposit\";\n bytes32 private constant _WITHDRAW_FEATURE_FLAG = \"withdraw\";\n\n bytes32 private constant _CONFIG_TIMEOUT_WITHDRAW = \"accountTimeoutWithdraw\";\n\n /**\n * @inheritdoc ICollateralModule\n */\n function deposit(\n uint128 accountId,\n address collateralType,\n uint256 tokenAmount\n ) external override {\n FeatureFlag.ensureAccessToFeature(_DEPOSIT_FEATURE_FLAG);\n CollateralConfiguration.collateralEnabled(collateralType);\n Account.exists(accountId);\n\n Account.Data storage account = Account.load(accountId);\n\n address depositFrom = msg.sender;\n\n address self = address(this);\n\n uint256 allowance = IERC20(collateralType).allowance(depositFrom, self);\n if (allowance < tokenAmount) {\n revert IERC20.InsufficientAllowance(tokenAmount, allowance);\n }\n\n collateralType.safeTransferFrom(depositFrom, self, tokenAmount);\n\n account.collaterals[collateralType].increaseAvailableCollateral(\n CollateralConfiguration.load(collateralType).convertTokenToSystemAmount(tokenAmount)\n );\n\n emit Deposited(accountId, collateralType, tokenAmount, msg.sender);\n }\n\n /**\n * @inheritdoc ICollateralModule\n */\n function withdraw(\n uint128 accountId,\n address collateralType,\n uint256 tokenAmount\n ) external override {\n FeatureFlag.ensureAccessToFeature(_WITHDRAW_FEATURE_FLAG);\n Account.Data storage account = Account.loadAccountAndValidatePermissionAndTimeout(\n accountId,\n AccountRBAC._WITHDRAW_PERMISSION,\n uint256(Config.read(_CONFIG_TIMEOUT_WITHDRAW))\n );\n\n uint256 tokenAmountD18 = CollateralConfiguration\n .load(collateralType)\n .convertTokenToSystemAmount(tokenAmount);\n\n (uint256 totalDeposited, uint256 totalAssigned, uint256 totalLocked) = account\n .getCollateralTotals(collateralType);\n\n // The amount that cannot be withdrawn from the protocol is the max of either\n // locked collateral or delegated collateral.\n uint256 unavailableCollateral = totalLocked > totalAssigned ? totalLocked : totalAssigned;\n\n uint256 availableForWithdrawal = totalDeposited - unavailableCollateral;\n if (tokenAmountD18 > availableForWithdrawal) {\n revert InsufficientAccountCollateral(tokenAmountD18);\n }\n\n account.collaterals[collateralType].decreaseAvailableCollateral(tokenAmountD18);\n\n collateralType.safeTransfer(msg.sender, tokenAmount);\n\n emit Withdrawn(accountId, collateralType, tokenAmount, msg.sender);\n }\n\n /**\n * @inheritdoc ICollateralModule\n */\n function getAccountCollateral(\n uint128 accountId,\n address collateralType\n )\n external\n view\n override\n returns (uint256 totalDeposited, uint256 totalAssigned, uint256 totalLocked)\n {\n return Account.load(accountId).getCollateralTotals(collateralType);\n }\n\n /**\n * @inheritdoc ICollateralModule\n */\n function getAccountAvailableCollateral(\n uint128 accountId,\n address collateralType\n ) public view override returns (uint256) {\n return Account.load(accountId).collaterals[collateralType].amountAvailableForDelegationD18;\n }\n\n /**\n * @inheritdoc ICollateralModule\n */\n function cleanExpiredLocks(\n uint128 accountId,\n address collateralType,\n uint256 offset,\n uint256 count\n ) external override returns (uint cleared) {\n CollateralLock.Data[] storage locks = Account\n .load(accountId)\n .collaterals[collateralType]\n .locks;\n\n uint64 currentTime = block.timestamp.to64();\n\n uint len = locks.length;\n\n if (offset >= len) {\n return 0;\n }\n\n if (count == 0 || offset + count >= len) {\n count = len - offset;\n }\n\n uint index = offset;\n for (uint i = 0; i < count; i++) {\n if (locks[index].lockExpirationTime <= currentTime) {\n emit CollateralLockExpired(\n accountId,\n collateralType,\n locks[index].amountD18,\n locks[index].lockExpirationTime\n );\n\n locks[index] = locks[locks.length - 1];\n locks.pop();\n } else {\n index++;\n }\n }\n\n return count + offset - index;\n }\n\n /**\n * @inheritdoc ICollateralModule\n */\n function getLocks(\n uint128 accountId,\n address collateralType,\n uint256 offset,\n uint256 count\n ) external view override returns (CollateralLock.Data[] memory locks) {\n CollateralLock.Data[] storage storageLocks = Account\n .load(accountId)\n .collaterals[collateralType]\n .locks;\n uint len = storageLocks.length;\n\n if (count == 0 || offset + count >= len) {\n count = offset < len ? len - offset : 0;\n }\n\n locks = new CollateralLock.Data[](count);\n\n for (uint i = 0; i < count; i++) {\n locks[i] = storageLocks[offset + i];\n }\n }\n\n /**\n * @inheritdoc ICollateralModule\n */\n function createLock(\n uint128 accountId,\n address collateralType,\n uint256 amount,\n uint64 expireTimestamp\n ) external override {\n Account.Data storage account = Account.loadAccountAndValidatePermission(\n accountId,\n AccountRBAC._ADMIN_PERMISSION\n );\n\n (uint256 totalDeposited, , uint256 totalLocked) = account.getCollateralTotals(\n collateralType\n );\n\n if (expireTimestamp <= block.timestamp) {\n revert ParameterError.InvalidParameter(\"expireTimestamp\", \"must be in the future\");\n }\n\n if (amount == 0) {\n revert ParameterError.InvalidParameter(\"amount\", \"must be nonzero\");\n }\n\n if (amount > totalDeposited - totalLocked) {\n revert InsufficientAccountCollateral(amount);\n }\n\n account.collaterals[collateralType].locks.push(\n CollateralLock.Data(amount.to128(), expireTimestamp)\n );\n\n emit CollateralLockCreated(accountId, collateralType, amount, expireTimestamp);\n }\n}\n" }, "contracts/modules/core/FeatureFlagModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport {FeatureFlagModule as BaseFeatureFlagModule} from \"@synthetixio/core-modules/contracts/modules/FeatureFlagModule.sol\";\n\n/**\n * @title Module that allows disabling certain system features.\n *\n * Users will not be able to interact with certain functions associated to disabled features.\n */\n// solhint-disable-next-line no-empty-blocks\ncontract FeatureFlagModule is BaseFeatureFlagModule {\n\n}\n" }, "contracts/modules/core/IssueUSDModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../../interfaces/IIssueUSDModule.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/AssociatedSystem.sol\";\n\nimport \"../../storage/Account.sol\";\nimport \"../../storage/CollateralConfiguration.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\n/**\n * @title Module for the minting and burning of stablecoins.\n * @dev See IIssueUSDModule.\n */\ncontract IssueUSDModule is IIssueUSDModule {\n using Account for Account.Data;\n using AccountRBAC for AccountRBAC.Data;\n using AssociatedSystem for AssociatedSystem.Data;\n using Pool for Pool.Data;\n using CollateralConfiguration for CollateralConfiguration.Data;\n using Vault for Vault.Data;\n using VaultEpoch for VaultEpoch.Data;\n using Distribution for Distribution.Data;\n using ScalableMapping for ScalableMapping.Data;\n\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n\n bytes32 private constant _USD_TOKEN = \"USDToken\";\n\n bytes32 private constant _MINT_FEATURE_FLAG = \"mintUsd\";\n bytes32 private constant _BURN_FEATURE_FLAG = \"burnUsd\";\n\n /**\n * @inheritdoc IIssueUSDModule\n */\n function mintUsd(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n uint256 amount\n ) external override {\n FeatureFlag.ensureAccessToFeature(_MINT_FEATURE_FLAG);\n Account.loadAccountAndValidatePermission(accountId, AccountRBAC._MINT_PERMISSION);\n\n // disabled collateralType cannot be used for minting\n CollateralConfiguration.collateralEnabled(collateralType);\n\n Pool.Data storage pool = Pool.loadExisting(poolId);\n\n int256 debt = pool.updateAccountDebt(collateralType, accountId);\n int256 newDebt = debt + amount.toInt();\n\n // Ensure minting stablecoins is increasing the debt of the position\n if (newDebt <= debt) {\n revert ParameterError.InvalidParameter(\n \"newDebt\",\n \"should be greater than current debt\"\n );\n }\n\n // If the resulting debt of the account is greater than zero, ensure that the resulting c-ratio is sufficient\n (, uint256 collateralValue) = pool.currentAccountCollateral(collateralType, accountId);\n if (newDebt > 0) {\n CollateralConfiguration.load(collateralType).verifyIssuanceRatio(\n newDebt.toUint(),\n collateralValue\n );\n }\n\n VaultEpoch.Data storage epoch = Pool.load(poolId).vaults[collateralType].currentEpoch();\n\n // Increase the debt of the position\n epoch.assignDebtToAccount(accountId, amount.toInt());\n\n // Decrease the credit available in the vault\n pool.recalculateVaultCollateral(collateralType);\n\n // Mint stablecoins to the sender\n AssociatedSystem.load(_USD_TOKEN).asToken().mint(msg.sender, amount);\n\n emit UsdMinted(accountId, poolId, collateralType, amount, msg.sender);\n }\n\n /**\n * @inheritdoc IIssueUSDModule\n */\n function burnUsd(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n uint256 amount\n ) external override {\n FeatureFlag.ensureAccessToFeature(_BURN_FEATURE_FLAG);\n Pool.Data storage pool = Pool.load(poolId);\n\n // Retrieve current position debt\n int256 debt = pool.updateAccountDebt(collateralType, accountId);\n\n // Ensure the position can't burn if it already has no debt\n if (debt <= 0) {\n revert InsufficientDebt(debt);\n }\n\n // Only allow burning the total debt of the position\n if (debt < amount.toInt()) {\n amount = debt.toUint();\n }\n\n // Burn the stablecoins\n AssociatedSystem.load(_USD_TOKEN).asToken().burn(msg.sender, amount);\n\n VaultEpoch.Data storage epoch = Pool.load(poolId).vaults[collateralType].currentEpoch();\n\n // Decrease the debt of the position\n epoch.assignDebtToAccount(accountId, -amount.toInt());\n\n // Increase the credit available in the vault\n pool.recalculateVaultCollateral(collateralType);\n\n emit UsdBurned(accountId, poolId, collateralType, amount, msg.sender);\n }\n}\n" }, "contracts/modules/core/LiquidationModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../../interfaces/ILiquidationModule.sol\";\n\nimport \"../../storage/Account.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/AssociatedSystem.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/errors/ParameterError.sol\";\nimport \"@synthetixio/core-contracts/contracts/token/ERC20Helper.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\n/**\n * @title Module for liquidated positions and vaults that are below the liquidation ratio.\n * @dev See ILiquidationModule.\n */\ncontract LiquidationModule is ILiquidationModule {\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n using DecimalMath for uint256;\n using ERC20Helper for address;\n using AssociatedSystem for AssociatedSystem.Data;\n using CollateralConfiguration for CollateralConfiguration.Data;\n using Collateral for Collateral.Data;\n using Pool for Pool.Data;\n using Vault for Vault.Data;\n using VaultEpoch for VaultEpoch.Data;\n using Distribution for Distribution.Data;\n using ScalableMapping for ScalableMapping.Data;\n\n bytes32 private constant _USD_TOKEN = \"USDToken\";\n\n bytes32 private constant _LIQUIDATE_FEATURE_FLAG = \"liquidate\";\n bytes32 private constant _LIQUIDATE_VAULT_FEATURE_FLAG = \"liquidateVault\";\n\n /**\n * @inheritdoc ILiquidationModule\n */\n function liquidate(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n uint128 liquidateAsAccountId\n ) external override returns (LiquidationData memory liquidationData) {\n FeatureFlag.ensureAccessToFeature(_LIQUIDATE_FEATURE_FLAG);\n // Ensure the account receiving rewards exists\n Account.exists(liquidateAsAccountId);\n\n Pool.Data storage pool = Pool.load(poolId);\n CollateralConfiguration.Data storage collateralConfig = CollateralConfiguration.load(\n collateralType\n );\n VaultEpoch.Data storage epoch = pool.vaults[collateralType].currentEpoch();\n\n int256 rawDebt = pool.updateAccountDebt(collateralType, accountId);\n (uint256 collateralAmount, uint256 collateralValue) = pool.currentAccountCollateral(\n collateralType,\n accountId\n );\n liquidationData.collateralLiquidated = collateralAmount;\n\n // Verify whether the position is eligible for liquidation\n if (rawDebt <= 0 || !_isLiquidatable(collateralType, rawDebt, collateralValue)) {\n revert IneligibleForLiquidation(\n collateralValue,\n rawDebt,\n rawDebt <= 0 ? 0 : collateralValue.divDecimal(rawDebt.toUint()),\n collateralConfig.liquidationRatioD18\n );\n }\n\n liquidationData.debtLiquidated = rawDebt.toUint();\n\n uint256 liquidatedAccountShares = epoch.accountsDebtDistribution.getActorShares(\n accountId.toBytes32()\n );\n if (epoch.accountsDebtDistribution.totalSharesD18 == liquidatedAccountShares) {\n // will be left with 0 shares, which can't be socialized\n revert MustBeVaultLiquidated();\n }\n\n // Although amountRewarded is the minimum to delegate to a vault, this value may increase in the future\n liquidationData.amountRewarded = collateralConfig.liquidationRewardD18;\n if (liquidationData.amountRewarded >= epoch.collateralAmounts.totalAmount()) {\n // vault is too small to be liquidated socialized\n revert MustBeVaultLiquidated();\n }\n\n // This will clear the user's account the same way as if they had withdrawn normally\n epoch.updateAccountPosition(accountId, 0, 0);\n\n // Distribute the liquidated collateral among other positions in the vault, minus the reward amount\n epoch.collateralAmounts.scale(\n liquidationData.collateralLiquidated.toInt() - liquidationData.amountRewarded.toInt()\n );\n\n // Remove the debt assigned to the liquidated account\n epoch.assignDebtToAccount(accountId, -liquidationData.debtLiquidated.toInt());\n\n // Distribute this debt among other accounts in the vault\n epoch.distributeDebtToAccounts(liquidationData.debtLiquidated.toInt());\n\n // The collateral is reduced by `amountRewarded`, so we need to reduce the stablecoins capacity available to the markets\n pool.recalculateVaultCollateral(collateralType);\n\n // Send amountRewarded to the specified account\n Account.load(liquidateAsAccountId).collaterals[collateralType].increaseAvailableCollateral(\n liquidationData.amountRewarded\n );\n\n emit Liquidation(\n accountId,\n poolId,\n collateralType,\n liquidationData,\n liquidateAsAccountId,\n msg.sender\n );\n }\n\n /**\n * @inheritdoc ILiquidationModule\n */\n function liquidateVault(\n uint128 poolId,\n address collateralType,\n uint128 liquidateAsAccountId,\n uint256 maxUsd\n ) external override returns (LiquidationData memory liquidationData) {\n FeatureFlag.ensureAccessToFeature(_LIQUIDATE_VAULT_FEATURE_FLAG);\n // Ensure the account receiving collateral exists\n Account.exists(liquidateAsAccountId);\n\n // The liquidator must provide at least some stablecoins to repay debt\n if (maxUsd == 0) {\n revert ParameterError.InvalidParameter(\"maxUsd\", \"must be higher than 0\");\n }\n\n Pool.Data storage pool = Pool.load(poolId);\n CollateralConfiguration.Data storage collateralConfig = CollateralConfiguration.load(\n collateralType\n );\n Vault.Data storage vault = pool.vaults[collateralType];\n\n // Retrieve the collateral and the debt of the vault\n int256 rawVaultDebt = pool.currentVaultDebt(collateralType);\n (, uint256 collateralValue) = pool.currentVaultCollateral(collateralType);\n\n // Verify whether the vault is eligible for liquidation\n if (!_isLiquidatable(collateralType, rawVaultDebt, collateralValue)) {\n revert IneligibleForLiquidation(\n collateralValue,\n rawVaultDebt,\n rawVaultDebt > 0 ? collateralValue.divDecimal(rawVaultDebt.toUint()) : 0,\n collateralConfig.liquidationRatioD18\n );\n }\n\n uint256 vaultDebt = rawVaultDebt.toUint();\n\n if (vaultDebt <= maxUsd) {\n // Conduct a full vault liquidation\n liquidationData.debtLiquidated = vaultDebt;\n\n // Burn all of the stablecoins necessary to clear the debt of this vault\n AssociatedSystem.load(_USD_TOKEN).asToken().burn(msg.sender, vaultDebt);\n\n // Provide all of the collateral to the liquidator\n liquidationData.collateralLiquidated = vault\n .currentEpoch()\n .collateralAmounts\n .totalAmount();\n\n // Increment the epoch counter\n pool.resetVault(collateralType);\n } else {\n // Conduct a partial vault liquidation\n liquidationData.debtLiquidated = maxUsd;\n\n // Burn all of the stablecoins provided by the liquidator\n AssociatedSystem.load(_USD_TOKEN).asToken().burn(msg.sender, maxUsd);\n\n VaultEpoch.Data storage epoch = vault.currentEpoch();\n\n // Provide the proportional amount of collateral to the liquidator\n liquidationData.collateralLiquidated =\n (epoch.collateralAmounts.totalAmount() * liquidationData.debtLiquidated) /\n vaultDebt;\n\n // Reduce the debt of the remaining positions in the vault\n epoch.distributeDebtToAccounts(-liquidationData.debtLiquidated.toInt());\n\n // Reduce the collateral of the remaining positions in the vault\n epoch.collateralAmounts.scale(-liquidationData.collateralLiquidated.toInt());\n }\n\n // Send liquidationData.collateralLiquidated to the specified account\n Account.load(liquidateAsAccountId).collaterals[collateralType].increaseAvailableCollateral(\n liquidationData.collateralLiquidated\n );\n liquidationData.amountRewarded = liquidationData.collateralLiquidated;\n\n emit VaultLiquidation(\n poolId,\n collateralType,\n liquidationData,\n liquidateAsAccountId,\n msg.sender\n );\n }\n\n /**\n * @dev Returns whether a combination of debt and credit is liquidatable for a specified collateral type\n */\n function _isLiquidatable(\n address collateralType,\n int256 debt,\n uint256 collateralValue\n ) internal view returns (bool) {\n if (debt <= 0) {\n return false;\n }\n return\n collateralValue.divDecimal(debt.toUint()) <\n CollateralConfiguration.load(collateralType).liquidationRatioD18;\n }\n\n /**\n * @inheritdoc ILiquidationModule\n */\n function isPositionLiquidatable(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n ) external override returns (bool) {\n Pool.Data storage pool = Pool.load(poolId);\n int256 rawDebt = pool.updateAccountDebt(collateralType, accountId);\n (, uint256 collateralValue) = pool.currentAccountCollateral(collateralType, accountId);\n return rawDebt >= 0 && _isLiquidatable(collateralType, rawDebt, collateralValue);\n }\n\n /**\n * @inheritdoc ILiquidationModule\n */\n function isVaultLiquidatable(\n uint128 poolId,\n address collateralType\n ) external override returns (bool) {\n Pool.Data storage pool = Pool.load(poolId);\n int256 rawVaultDebt = pool.currentVaultDebt(collateralType);\n (, uint256 collateralValue) = pool.currentVaultCollateral(collateralType);\n return rawVaultDebt >= 0 && _isLiquidatable(collateralType, rawVaultDebt, collateralValue);\n }\n}\n" }, "contracts/modules/core/MarketCollateralModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\nimport \"@synthetixio/core-contracts/contracts/token/ERC20Helper.sol\";\n\nimport \"../../interfaces/IMarketCollateralModule.sol\";\nimport \"../../storage/Market.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\n/**\n * @title Module for allowing markets to directly increase their credit capacity by providing their own collateral.\n * @dev See IMarketCollateralModule.\n */\ncontract MarketCollateralModule is IMarketCollateralModule {\n using SafeCastU256 for uint256;\n using ERC20Helper for address;\n using CollateralConfiguration for CollateralConfiguration.Data;\n using Market for Market.Data;\n\n bytes32 private constant _DEPOSIT_MARKET_COLLATERAL_FEATURE_FLAG = \"depositMarketCollateral\";\n bytes32 private constant _WITHDRAW_MARKET_COLLATERAL_FEATURE_FLAG = \"withdrawMarketCollateral\";\n\n /**\n * @inheritdoc IMarketCollateralModule\n */\n function depositMarketCollateral(\n uint128 marketId,\n address collateralType,\n uint256 tokenAmount\n ) public override {\n FeatureFlag.ensureAccessToFeature(_DEPOSIT_MARKET_COLLATERAL_FEATURE_FLAG);\n Market.Data storage marketData = Market.load(marketId);\n\n // Ensure the sender is the market address associated with the specified marketId\n if (msg.sender != marketData.marketAddress) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n uint256 systemAmount = CollateralConfiguration\n .load(collateralType)\n .convertTokenToSystemAmount(tokenAmount);\n\n uint256 maxDepositable = marketData.maximumDepositableD18[collateralType];\n uint256 depositedCollateralEntryIndex = _findOrCreateDepositEntryIndex(\n marketData,\n collateralType\n );\n Market.DepositedCollateral storage collateralEntry = marketData.depositedCollateral[\n depositedCollateralEntryIndex\n ];\n\n // Ensure that depositing this amount will not exceed the maximum amount allowed for the market\n if (collateralEntry.amountD18 + systemAmount > maxDepositable)\n revert InsufficientMarketCollateralDepositable(marketId, collateralType, tokenAmount);\n\n // Account for the collateral and transfer it into the system.\n collateralEntry.amountD18 += systemAmount;\n collateralType.safeTransferFrom(marketData.marketAddress, address(this), tokenAmount);\n\n emit MarketCollateralDeposited(marketId, collateralType, tokenAmount, msg.sender);\n }\n\n /**\n * @inheritdoc IMarketCollateralModule\n */\n function withdrawMarketCollateral(\n uint128 marketId,\n address collateralType,\n uint256 tokenAmount\n ) public override {\n FeatureFlag.ensureAccessToFeature(_WITHDRAW_MARKET_COLLATERAL_FEATURE_FLAG);\n Market.Data storage marketData = Market.load(marketId);\n\n uint256 systemAmount = CollateralConfiguration\n .load(collateralType)\n .convertTokenToSystemAmount(tokenAmount);\n\n // Ensure the sender is the market address associated with the specified marketId\n if (msg.sender != marketData.marketAddress) revert AccessError.Unauthorized(msg.sender);\n\n uint256 depositedCollateralEntryIndex = _findOrCreateDepositEntryIndex(\n marketData,\n collateralType\n );\n Market.DepositedCollateral storage collateralEntry = marketData.depositedCollateral[\n depositedCollateralEntryIndex\n ];\n\n // Ensure that the market is not withdrawing more collateral than it has deposited\n if (systemAmount > collateralEntry.amountD18) {\n revert InsufficientMarketCollateralWithdrawable(marketId, collateralType, tokenAmount);\n }\n\n // Account for transferring out collateral\n collateralEntry.amountD18 -= systemAmount;\n\n // Ensure that the market is not withdrawing collateral such that it results in a negative getWithdrawableMarketUsd\n int256 newWithdrawableMarketUsd = marketData.creditCapacityD18 +\n marketData.getDepositedCollateralValue().toInt();\n if (newWithdrawableMarketUsd < 0) {\n revert InsufficientMarketCollateralWithdrawable(marketId, collateralType, tokenAmount);\n }\n\n // Transfer the collateral to the market\n collateralType.safeTransfer(marketData.marketAddress, tokenAmount);\n\n emit MarketCollateralWithdrawn(marketId, collateralType, tokenAmount, msg.sender);\n }\n\n /**\n * @dev Returns the index of the relevant deposited collateral entry for the given market and collateral type.\n */\n function _findOrCreateDepositEntryIndex(\n Market.Data storage marketData,\n address collateralType\n ) internal returns (uint256 depositedCollateralEntryIndex) {\n Market.DepositedCollateral[] storage depositedCollateral = marketData.depositedCollateral;\n for (uint256 i = 0; i < depositedCollateral.length; i++) {\n Market.DepositedCollateral storage depositedCollateralEntry = depositedCollateral[i];\n if (depositedCollateralEntry.collateralType == collateralType) {\n return i;\n }\n }\n\n // If this function hasn't returned an index yet, create a new deposited collateral entry and return its index.\n marketData.depositedCollateral.push(Market.DepositedCollateral(collateralType, 0));\n return marketData.depositedCollateral.length - 1;\n }\n\n /**\n * @inheritdoc IMarketCollateralModule\n */\n function configureMaximumMarketCollateral(\n uint128 marketId,\n address collateralType,\n uint256 amount\n ) external override {\n OwnableStorage.onlyOwner();\n\n Market.Data storage marketData = Market.load(marketId);\n marketData.maximumDepositableD18[collateralType] = amount;\n\n emit MaximumMarketCollateralConfigured(marketId, collateralType, amount, msg.sender);\n }\n\n /**\n * @inheritdoc IMarketCollateralModule\n */\n function getMarketCollateralAmount(\n uint128 marketId,\n address collateralType\n ) external view override returns (uint256 collateralAmountD18) {\n Market.Data storage marketData = Market.load(marketId);\n Market.DepositedCollateral[] storage depositedCollateral = marketData.depositedCollateral;\n for (uint256 i = 0; i < depositedCollateral.length; i++) {\n Market.DepositedCollateral storage depositedCollateralEntry = depositedCollateral[i];\n if (depositedCollateralEntry.collateralType == collateralType) {\n return depositedCollateralEntry.amountD18;\n }\n }\n }\n\n /**\n * @inheritdoc IMarketCollateralModule\n */\n function getMarketCollateralValue(uint128 marketId) external view override returns (uint256) {\n return Market.load(marketId).getDepositedCollateralValue();\n }\n\n /**\n * @inheritdoc IMarketCollateralModule\n */\n function getMaximumMarketCollateral(\n uint128 marketId,\n address collateralType\n ) external view override returns (uint256) {\n Market.Data storage marketData = Market.load(marketId);\n return marketData.maximumDepositableD18[collateralType];\n }\n}\n" }, "contracts/modules/core/MarketManagerModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../../interfaces/IMarketManagerModule.sol\";\nimport \"../../interfaces/IUSDTokenModule.sol\";\nimport \"../../interfaces/external/IMarket.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/errors/AccessError.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/ERC165Helper.sol\";\n\nimport \"../../storage/Market.sol\";\nimport \"../../storage/MarketCreator.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/AssociatedSystem.sol\";\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\n/**\n * @title System-wide entry point for the management of markets connected to the system.\n * @dev See IMarketManagerModule.\n */\ncontract MarketManagerModule is IMarketManagerModule {\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n using Market for Market.Data;\n using AssociatedSystem for AssociatedSystem.Data;\n\n bytes32 private constant _USD_TOKEN = \"USDToken\";\n bytes32 private constant _MARKET_FEATURE_FLAG = \"registerMarket\";\n bytes32 private constant _DEPOSIT_MARKET_FEATURE_FLAG = \"depositMarketUsd\";\n bytes32 private constant _WITHDRAW_MARKET_FEATURE_FLAG = \"withdrawMarketUsd\";\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function registerMarket(address market) external override returns (uint128 marketId) {\n FeatureFlag.ensureAccessToFeature(_MARKET_FEATURE_FLAG);\n\n if (!ERC165Helper.safeSupportsInterface(market, type(IMarket).interfaceId)) {\n revert IncorrectMarketInterface(market);\n }\n\n marketId = MarketCreator.create(market).id;\n\n emit MarketRegistered(market, marketId, msg.sender);\n\n return marketId;\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function getWithdrawableMarketUsd(uint128 marketId) public view override returns (uint256) {\n int256 withdrawable = Market.load(marketId).creditCapacityD18 +\n Market.load(marketId).getDepositedCollateralValue().toInt();\n\n return withdrawable < 0 ? 0 : withdrawable.toUint();\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function getMarketNetIssuance(uint128 marketId) external view override returns (int128) {\n return Market.load(marketId).netIssuanceD18;\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function getMarketReportedDebt(uint128 marketId) external view override returns (uint256) {\n return Market.load(marketId).getReportedDebt();\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function getMarketCollateral(uint128 marketId) external view override returns (uint256) {\n return Market.load(marketId).poolsDebtDistribution.totalSharesD18;\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function getMarketTotalDebt(uint128 marketId) external view override returns (int256) {\n return Market.load(marketId).totalDebt();\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function getMarketDebtPerShare(uint128 marketId) external override returns (int256) {\n Market.Data storage market = Market.load(marketId);\n\n market.distributeDebtToPools(999999999);\n\n return market.getDebtPerShare();\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function isMarketCapacityLocked(uint128 marketId) external view override returns (bool) {\n return Market.load(marketId).isCapacityLocked();\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function depositMarketUsd(uint128 marketId, address target, uint256 amount) external override {\n FeatureFlag.ensureAccessToFeature(_DEPOSIT_MARKET_FEATURE_FLAG);\n Market.Data storage market = Market.load(marketId);\n\n // Call must come from the market itself.\n if (msg.sender != market.marketAddress) revert AccessError.Unauthorized(msg.sender);\n\n // verify if the market is authorized to burn the USD for the target\n ITokenModule usdToken = AssociatedSystem.load(_USD_TOKEN).asToken();\n\n // Adjust accounting.\n market.creditCapacityD18 += amount.toInt().to128();\n market.netIssuanceD18 -= amount.toInt().to128();\n\n // Burn the incoming USD.\n // Note: Instead of burning, we could transfer USD to and from the MarketManager,\n // but minting and burning takes the USD out of circulation,\n // which doesn't affect `totalSupply`, thus simplifying accounting.\n IUSDTokenModule(address(usdToken)).burnWithAllowance(target, msg.sender, amount);\n\n emit MarketUsdDeposited(marketId, target, amount, msg.sender);\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function withdrawMarketUsd(uint128 marketId, address target, uint256 amount) external override {\n FeatureFlag.ensureAccessToFeature(_WITHDRAW_MARKET_FEATURE_FLAG);\n Market.Data storage marketData = Market.load(marketId);\n\n // Call must come from the market itself.\n if (msg.sender != marketData.marketAddress) revert AccessError.Unauthorized(msg.sender);\n\n // Ensure that the market's balance allows for this withdrawal.\n if (amount > getWithdrawableMarketUsd(marketId))\n revert NotEnoughLiquidity(marketId, amount);\n\n // Adjust accounting.\n marketData.creditCapacityD18 -= amount.toInt().to128();\n marketData.netIssuanceD18 += amount.toInt().to128();\n\n // Mint the requested USD.\n AssociatedSystem.load(_USD_TOKEN).asToken().mint(target, amount);\n\n emit MarketUsdWithdrawn(marketId, target, amount, msg.sender);\n }\n\n /**\n * @inheritdoc IMarketManagerModule\n */\n function distributeDebtToPools(\n uint128 marketId,\n uint256 maxIter\n ) external override returns (bool) {\n return Market.load(marketId).distributeDebtToPools(maxIter);\n }\n}\n" }, "contracts/modules/core/MulticallModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../../interfaces/IMulticallModule.sol\";\n\n/**\n * @title Module that enables calling multiple methods of the system in a single transaction.\n * @dev See IMulticallModule.\n * @dev Implementation adapted from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol\n */\ncontract MulticallModule is IMulticallModule {\n /**\n * @inheritdoc IMulticallModule\n */\n function multicall(\n bytes[] calldata data\n ) public payable override returns (bytes[] memory results) {\n results = new bytes[](data.length);\n for (uint256 i = 0; i < data.length; i++) {\n (bool success, bytes memory result) = address(this).delegatecall(data[i]);\n\n if (!success) {\n // Next 6 lines from https://ethereum.stackexchange.com/a/83577\n // solhint-disable-next-line reason-string\n if (result.length < 68) revert();\n assembly {\n result := add(result, 0x04)\n }\n revert(abi.decode(result, (string)));\n }\n\n results[i] = result;\n }\n }\n}\n" }, "contracts/modules/core/PoolConfigurationModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SetUtil.sol\";\n\nimport \"../../interfaces/IPoolConfigurationModule.sol\";\nimport \"../../storage/SystemPoolConfiguration.sol\";\n\nimport \"../../storage/Pool.sol\";\n\n/**\n * @title Module that allows the system owner to mark official pools.\n * @dev See IPoolConfigurationModule.\n */\ncontract PoolConfigurationModule is IPoolConfigurationModule {\n using SetUtil for SetUtil.UintSet;\n\n using Pool for Pool.Data;\n\n /**\n * @inheritdoc IPoolConfigurationModule\n */\n function setPreferredPool(uint128 poolId) external override {\n OwnableStorage.onlyOwner();\n Pool.loadExisting(poolId);\n\n SystemPoolConfiguration.load().preferredPool = poolId;\n\n emit PreferredPoolSet(poolId);\n }\n\n /**\n * @inheritdoc IPoolConfigurationModule\n */\n function getPreferredPool() external view override returns (uint128) {\n return SystemPoolConfiguration.load().preferredPool;\n }\n\n /**\n * @inheritdoc IPoolConfigurationModule\n */\n function addApprovedPool(uint128 poolId) external override {\n OwnableStorage.onlyOwner();\n Pool.loadExisting(poolId);\n\n SystemPoolConfiguration.load().approvedPools.add(poolId);\n\n emit PoolApprovedAdded(poolId);\n }\n\n /**\n * @inheritdoc IPoolConfigurationModule\n */\n function removeApprovedPool(uint128 poolId) external override {\n OwnableStorage.onlyOwner();\n Pool.loadExisting(poolId);\n\n SystemPoolConfiguration.load().approvedPools.remove(poolId);\n\n emit PoolApprovedRemoved(poolId);\n }\n\n /**\n * @inheritdoc IPoolConfigurationModule\n */\n function getApprovedPools() external view override returns (uint256[] memory) {\n return SystemPoolConfiguration.load().approvedPools.values();\n }\n}\n" }, "contracts/modules/core/PoolModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/AccessError.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/AddressError.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/ParameterError.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\nimport \"../../interfaces/IPoolModule.sol\";\nimport \"../../storage/Pool.sol\";\n\n/**\n * @title Module for the creation and management of pools.\n * @dev See IPoolModule.\n */\ncontract PoolModule is IPoolModule {\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n using DecimalMath for uint256;\n using Pool for Pool.Data;\n using Market for Market.Data;\n\n bytes32 private constant _POOL_FEATURE_FLAG = \"createPool\";\n\n /**\n * @inheritdoc IPoolModule\n */\n function createPool(uint128 requestedPoolId, address owner) external override {\n FeatureFlag.ensureAccessToFeature(_POOL_FEATURE_FLAG);\n\n if (owner == address(0)) {\n revert AddressError.ZeroAddress();\n }\n\n Pool.create(requestedPoolId, owner);\n\n emit PoolCreated(requestedPoolId, owner, msg.sender);\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function nominatePoolOwner(address nominatedOwner, uint128 poolId) external override {\n Pool.onlyPoolOwner(poolId, msg.sender);\n\n Pool.load(poolId).nominatedOwner = nominatedOwner;\n\n emit PoolOwnerNominated(poolId, nominatedOwner, msg.sender);\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function acceptPoolOwnership(uint128 poolId) external override {\n Pool.Data storage pool = Pool.load(poolId);\n\n if (pool.nominatedOwner != msg.sender) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n pool.owner = msg.sender;\n pool.nominatedOwner = address(0);\n\n emit PoolOwnershipAccepted(poolId, msg.sender);\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function revokePoolNomination(uint128 poolId) external override {\n Pool.onlyPoolOwner(poolId, msg.sender);\n\n Pool.load(poolId).nominatedOwner = address(0);\n\n emit PoolNominationRevoked(poolId, msg.sender);\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function renouncePoolNomination(uint128 poolId) external override {\n Pool.Data storage pool = Pool.load(poolId);\n\n if (pool.nominatedOwner != msg.sender) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n pool.nominatedOwner = address(0);\n\n emit PoolNominationRenounced(poolId, msg.sender);\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function getPoolOwner(uint128 poolId) external view override returns (address) {\n return Pool.load(poolId).owner;\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function getNominatedPoolOwner(uint128 poolId) external view override returns (address) {\n return Pool.load(poolId).nominatedOwner;\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function setPoolConfiguration(\n uint128 poolId,\n MarketConfiguration.Data[] memory newMarketConfigurations\n ) external override {\n Pool.Data storage pool = Pool.loadExisting(poolId);\n Pool.onlyPoolOwner(poolId, msg.sender);\n\n // Update each market's pro-rata liquidity and collect accumulated debt into the pool's debt distribution.\n // Note: This follows the same pattern as Pool.recalculateVaultCollateral(),\n // where we need to distribute the debt, adjust the market configurations and distribute again.\n pool.distributeDebtToVaults();\n\n // Identify markets that need to be removed or verified later for being locked.\n (\n uint128[] memory potentiallyLockedMarkets,\n uint128[] memory removedMarkets\n ) = _analyzePoolConfigurationChange(pool, newMarketConfigurations);\n\n // Replace existing market configurations with the new ones.\n // (May leave old configurations at the end of the array if the new array is shorter).\n uint256 i = 0;\n uint256 totalWeight = 0;\n // Iterate up to the shorter length.\n uint256 len = newMarketConfigurations.length < pool.marketConfigurations.length\n ? newMarketConfigurations.length\n : pool.marketConfigurations.length;\n for (; i < len; i++) {\n pool.marketConfigurations[i] = newMarketConfigurations[i];\n totalWeight += newMarketConfigurations[i].weightD18;\n }\n\n // If the old array was shorter, push the new elements in.\n for (; i < newMarketConfigurations.length; i++) {\n pool.marketConfigurations.push(newMarketConfigurations[i]);\n totalWeight += newMarketConfigurations[i].weightD18;\n }\n\n // If the old array was longer, truncate it.\n uint256 popped = pool.marketConfigurations.length - i;\n for (i = 0; i < popped; i++) {\n pool.marketConfigurations.pop();\n }\n\n // Rebalance all markets that need to be removed.\n for (i = 0; i < removedMarkets.length && removedMarkets[i] != 0; i++) {\n Market.rebalancePools(removedMarkets[i], poolId, 0, 0);\n }\n\n pool.totalWeightsD18 = totalWeight.to128();\n\n // Distribute debt again because the unused credit capacity has been updated, and this information needs to be propagated immediately.\n pool.distributeDebtToVaults();\n\n // The credit delegation proportion of the pool can only stay the same, or increase,\n // so prevent the removal of markets whose capacity is locked.\n // Note: This check is done here because it needs to happen after removed markets are rebalanced.\n for (i = 0; i < potentiallyLockedMarkets.length && potentiallyLockedMarkets[i] != 0; i++) {\n if (Market.load(potentiallyLockedMarkets[i]).isCapacityLocked()) {\n revert CapacityLocked(potentiallyLockedMarkets[i]);\n }\n }\n\n emit PoolConfigurationSet(poolId, newMarketConfigurations, msg.sender);\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function getPoolConfiguration(\n uint128 poolId\n ) external view override returns (MarketConfiguration.Data[] memory) {\n Pool.Data storage pool = Pool.load(poolId);\n\n MarketConfiguration.Data[] memory marketConfigurations = new MarketConfiguration.Data[](\n pool.marketConfigurations.length\n );\n\n for (uint256 i = 0; i < pool.marketConfigurations.length; i++) {\n marketConfigurations[i] = pool.marketConfigurations[i];\n }\n\n return marketConfigurations;\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function setPoolName(uint128 poolId, string memory name) external override {\n Pool.Data storage pool = Pool.loadExisting(poolId);\n Pool.onlyPoolOwner(poolId, msg.sender);\n\n pool.name = name;\n\n emit PoolNameUpdated(poolId, name, msg.sender);\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function getPoolName(uint128 poolId) external view override returns (string memory poolName) {\n return Pool.load(poolId).name;\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function setMinLiquidityRatio(uint256 minLiquidityRatio) external override {\n OwnableStorage.onlyOwner();\n\n SystemPoolConfiguration.load().minLiquidityRatioD18 = minLiquidityRatio;\n }\n\n /**\n * @inheritdoc IPoolModule\n */\n function getMinLiquidityRatio() external view override returns (uint256) {\n return SystemPoolConfiguration.load().minLiquidityRatioD18;\n }\n\n /**\n * @dev Compares a new pool configuration with the existing one,\n * and returns information about markets that need to be removed, or whose capacity might be locked.\n *\n * Note: Stack too deep errors prevent the use of local variables to improve code readability here.\n */\n function _analyzePoolConfigurationChange(\n Pool.Data storage pool,\n MarketConfiguration.Data[] memory newMarketConfigurations\n )\n internal\n view\n returns (uint128[] memory potentiallyLockedMarkets, uint128[] memory removedMarkets)\n {\n uint256 oldIdx = 0;\n uint256 potentiallyLockedMarketsIdx = 0;\n uint256 removedMarketsIdx = 0;\n uint128 lastMarketId = 0;\n\n potentiallyLockedMarkets = new uint128[](pool.marketConfigurations.length);\n removedMarkets = new uint128[](pool.marketConfigurations.length);\n\n // First we need the total weight of the new distribution.\n uint256 totalWeightD18 = 0;\n for (uint256 i = 0; i < newMarketConfigurations.length; i++) {\n totalWeightD18 += newMarketConfigurations[i].weightD18;\n }\n\n // Now, iterate through the incoming market configurations, and compare with them with the existing ones.\n for (uint256 newIdx = 0; newIdx < newMarketConfigurations.length; newIdx++) {\n // Reject duplicate market ids,\n // AND ensure that they are provided in ascending order.\n if (newMarketConfigurations[newIdx].marketId <= lastMarketId) {\n revert ParameterError.InvalidParameter(\n \"markets\",\n \"must be supplied in strictly ascending order\"\n );\n }\n lastMarketId = newMarketConfigurations[newIdx].marketId;\n\n // Reject markets with no weight.\n if (newMarketConfigurations[newIdx].weightD18 == 0) {\n revert ParameterError.InvalidParameter(\"weights\", \"weight must be non-zero\");\n }\n\n // Note: The following blocks of code compare the incoming market (at newIdx) to an existing market (at oldIdx).\n // newIdx increases once per iteration in the for loop, but oldIdx may increase multiple times if certain conditions are met.\n\n // If the market id of newIdx is greater than any of the old market ids,\n // consider all the old ones removed and mark them for post verification (increases oldIdx for each).\n while (\n oldIdx < pool.marketConfigurations.length &&\n pool.marketConfigurations[oldIdx].marketId <\n newMarketConfigurations[newIdx].marketId\n ) {\n potentiallyLockedMarkets[potentiallyLockedMarketsIdx++] = pool\n .marketConfigurations[oldIdx]\n .marketId;\n removedMarkets[removedMarketsIdx++] = potentiallyLockedMarkets[\n potentiallyLockedMarketsIdx - 1\n ];\n\n oldIdx++;\n }\n\n // If the market id of newIdx is equal to any of the old market ids,\n // consider it updated (increases oldIdx once).\n if (\n oldIdx < pool.marketConfigurations.length &&\n pool.marketConfigurations[oldIdx].marketId ==\n newMarketConfigurations[newIdx].marketId\n ) {\n // Get weight ratios for comparison below.\n // Upscale them to make sure that we have compatible precision in case of very small values.\n // If the market's new maximum share value or weight ratio decreased,\n // mark it for later verification.\n if (\n newMarketConfigurations[newIdx].maxDebtShareValueD18 <\n pool.marketConfigurations[oldIdx].maxDebtShareValueD18 ||\n newMarketConfigurations[newIdx]\n .weightD18\n .to256()\n .upscale(DecimalMath.PRECISION_FACTOR)\n .divDecimal(totalWeightD18) < // newWeightRatioD27\n pool\n .marketConfigurations[oldIdx]\n .weightD18\n .to256()\n .upscale(DecimalMath.PRECISION_FACTOR)\n .divDecimal(pool.totalWeightsD18) // oldWeightRatioD27\n ) {\n potentiallyLockedMarkets[\n potentiallyLockedMarketsIdx++\n ] = newMarketConfigurations[newIdx].marketId;\n }\n\n oldIdx++;\n }\n\n // Note: processing or checks for added markets is not necessary.\n } // for end\n\n // If any of the old markets was not processed up to this point,\n // it means that it is not present in the new array, so mark it for removal.\n while (oldIdx < pool.marketConfigurations.length) {\n removedMarkets[removedMarketsIdx++] = pool.marketConfigurations[oldIdx].marketId;\n oldIdx++;\n }\n }\n}\n" }, "contracts/modules/core/RewardsManagerModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/errors/AccessError.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/ParameterError.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/DecimalMath.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/ERC165Helper.sol\";\n\nimport \"../../storage/Account.sol\";\nimport \"../../storage/AccountRBAC.sol\";\nimport \"../../storage/Pool.sol\";\n\nimport \"../../interfaces/IRewardsManagerModule.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\n/**\n * @title Module for connecting rewards distributors to vaults.\n * @dev See IRewardsManagerModule.\n */\ncontract RewardsManagerModule is IRewardsManagerModule {\n using SetUtil for SetUtil.Bytes32Set;\n using DecimalMath for uint256;\n using DecimalMath for int256;\n using SafeCastU32 for uint32;\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n\n using Vault for Vault.Data;\n using Distribution for Distribution.Data;\n using RewardDistribution for RewardDistribution.Data;\n\n uint256 private constant _MAX_REWARD_DISTRIBUTIONS = 10;\n\n bytes32 private constant _CLAIM_FEATURE_FLAG = \"claimRewards\";\n\n /**\n * @inheritdoc IRewardsManagerModule\n */\n function registerRewardsDistributor(\n uint128 poolId,\n address collateralType,\n address distributor\n ) external override {\n Pool.Data storage pool = Pool.load(poolId);\n SetUtil.Bytes32Set storage rewardIds = pool.vaults[collateralType].rewardIds;\n\n if (pool.owner != msg.sender) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n // Limit the maximum amount of rewards distributors can be connected to each vault to prevent excessive gas usage on other calls\n if (rewardIds.length() > _MAX_REWARD_DISTRIBUTIONS) {\n revert ParameterError.InvalidParameter(\"index\", \"too large\");\n }\n\n if (\n !ERC165Helper.safeSupportsInterface(distributor, type(IRewardDistributor).interfaceId)\n ) {\n revert ParameterError.InvalidParameter(\"distributor\", \"invalid interface\");\n }\n\n bytes32 rewardId = _getRewardId(poolId, collateralType, distributor);\n\n if (rewardIds.contains(rewardId)) {\n revert ParameterError.InvalidParameter(\"distributor\", \"is already registered\");\n }\n if (address(pool.vaults[collateralType].rewards[rewardId].distributor) != address(0)) {\n revert ParameterError.InvalidParameter(\"distributor\", \"cant be re-registered\");\n }\n\n rewardIds.add(rewardId);\n if (distributor == address(0)) {\n revert ParameterError.InvalidParameter(\"distributor\", \"must be non-zero\");\n }\n pool.vaults[collateralType].rewards[rewardId].distributor = IRewardDistributor(distributor);\n\n emit RewardsDistributorRegistered(poolId, collateralType, distributor);\n }\n\n /**\n * @inheritdoc IRewardsManagerModule\n */\n function distributeRewards(\n uint128 poolId,\n address collateralType,\n uint256 amount,\n uint64 start,\n uint32 duration\n ) external override {\n Pool.Data storage pool = Pool.load(poolId);\n SetUtil.Bytes32Set storage rewardIds = pool.vaults[collateralType].rewardIds;\n\n // Identify the reward id for the caller, and revert if it is not a registered reward distributor.\n bytes32 rewardId = _getRewardId(poolId, collateralType, msg.sender);\n if (!rewardIds.contains(rewardId)) {\n revert ParameterError.InvalidParameter(\n \"poolId-collateralType-distributor\",\n \"reward is not registered\"\n );\n }\n\n RewardDistribution.Data storage reward = pool.vaults[collateralType].rewards[rewardId];\n\n reward.rewardPerShareD18 += reward\n .distribute(\n pool.vaults[collateralType].currentEpoch().accountsDebtDistribution,\n amount.toInt(),\n start,\n duration\n )\n .toUint()\n .to128();\n\n emit RewardsDistributed(poolId, collateralType, msg.sender, amount, start, duration);\n }\n\n /**\n * @inheritdoc IRewardsManagerModule\n */\n function updateRewards(\n uint128 poolId,\n address collateralType,\n uint128 accountId\n ) external override returns (uint256[] memory, address[] memory) {\n Account.exists(accountId);\n Vault.Data storage vault = Pool.load(poolId).vaults[collateralType];\n return vault.updateRewards(accountId);\n }\n\n /**\n * @inheritdoc IRewardsManagerModule\n */\n function getRewardRate(\n uint128 poolId,\n address collateralType,\n address distributor\n ) external view override returns (uint256) {\n return _getRewardRate(poolId, collateralType, distributor);\n }\n\n /**\n * @inheritdoc IRewardsManagerModule\n */\n function claimRewards(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n address distributor\n ) external override returns (uint256) {\n FeatureFlag.ensureAccessToFeature(_CLAIM_FEATURE_FLAG);\n Account.loadAccountAndValidatePermission(accountId, AccountRBAC._REWARDS_PERMISSION);\n\n Vault.Data storage vault = Pool.load(poolId).vaults[collateralType];\n bytes32 rewardId = keccak256(abi.encode(poolId, collateralType, distributor));\n\n if (address(vault.rewards[rewardId].distributor) != distributor) {\n revert ParameterError.InvalidParameter(\"invalid-params\", \"reward is not found\");\n }\n\n uint256 rewardAmount = vault.updateReward(accountId, rewardId);\n\n RewardDistribution.Data storage reward = vault.rewards[rewardId];\n reward.claimStatus[accountId].pendingSendD18 = 0;\n bool success = vault.rewards[rewardId].distributor.payout(\n accountId,\n poolId,\n collateralType,\n msg.sender,\n rewardAmount\n );\n\n if (!success) {\n revert RewardUnavailable(distributor);\n }\n\n emit RewardsClaimed(\n accountId,\n poolId,\n collateralType,\n address(vault.rewards[rewardId].distributor),\n rewardAmount\n );\n\n return rewardAmount;\n }\n\n /**\n * @dev Return the amount of rewards being distributed to a vault per second\n */\n function _getRewardRate(\n uint128 poolId,\n address collateralType,\n address distributor\n ) internal view returns (uint256) {\n Vault.Data storage vault = Pool.load(poolId).vaults[collateralType];\n uint256 totalShares = vault.currentEpoch().accountsDebtDistribution.totalSharesD18;\n bytes32 rewardId = _getRewardId(poolId, collateralType, distributor);\n\n int256 curTime = block.timestamp.toInt();\n\n // No rewards are currently being distributed if the distributor doesn't exist, they are scheduled to be distributed in the future, or the distribution as already completed\n if (\n address(vault.rewards[rewardId].distributor) == address(0) ||\n vault.rewards[rewardId].start > curTime.toUint() ||\n vault.rewards[rewardId].start + vault.rewards[rewardId].duration <= curTime.toUint()\n ) {\n return 0;\n }\n\n return\n vault.rewards[rewardId].scheduledValueD18.to256().toUint().divDecimal(\n vault.rewards[rewardId].duration.to256().divDecimal(totalShares)\n );\n }\n\n /**\n * @dev Generate an ID for a rewards distributor connection by hashing its address with the vault's collateral type address and pool id\n */\n function _getRewardId(\n uint128 poolId,\n address collateralType,\n address distributor\n ) internal pure returns (bytes32) {\n return keccak256(abi.encode(poolId, collateralType, distributor));\n }\n\n /**\n * @inheritdoc IRewardsManagerModule\n */\n function removeRewardsDistributor(\n uint128 poolId,\n address collateralType,\n address distributor\n ) external override {\n Pool.Data storage pool = Pool.load(poolId);\n SetUtil.Bytes32Set storage rewardIds = pool.vaults[collateralType].rewardIds;\n\n if (pool.owner != msg.sender) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n bytes32 rewardId = _getRewardId(poolId, collateralType, distributor);\n\n if (!rewardIds.contains(rewardId)) {\n revert ParameterError.InvalidParameter(\"distributor\", \"is not registered\");\n }\n\n rewardIds.remove(rewardId);\n\n if (distributor == address(0)) {\n revert ParameterError.InvalidParameter(\"distributor\", \"must be non-zero\");\n }\n\n RewardDistribution.Data storage reward = pool.vaults[collateralType].rewards[rewardId];\n\n // ensure rewards emission is stopped (users can still come in to claim rewards after the fact)\n reward.rewardPerShareD18 += reward\n .distribute(\n pool.vaults[collateralType].currentEpoch().accountsDebtDistribution,\n 0,\n 0,\n 0\n )\n .toUint()\n .to128();\n\n emit RewardsDistributorRemoved(poolId, collateralType, distributor);\n }\n}\n" }, "contracts/modules/core/UtilsModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-modules/contracts/interfaces/IAssociatedSystemsModule.sol\";\nimport \"@synthetixio/core-modules/contracts/storage/AssociatedSystem.sol\";\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\n\nimport \"../../interfaces/IUtilsModule.sol\";\n\nimport \"../../storage/OracleManager.sol\";\nimport \"../../storage/Config.sol\";\n\n/**\n * @title Module with assorted utility functions.\n * @dev See IUtilsModule.\n */\ncontract UtilsModule is IUtilsModule {\n using AssociatedSystem for AssociatedSystem.Data;\n\n bytes32 private constant _USD_TOKEN = \"USDToken\";\n bytes32 private constant _CCIP_CHAINLINK_SEND = \"ccipChainlinkSend\";\n bytes32 private constant _CCIP_CHAINLINK_RECV = \"ccipChainlinkRecv\";\n bytes32 private constant _CCIP_CHAINLINK_TOKEN_POOL = \"ccipChainlinkTokenPool\";\n\n /**\n * @inheritdoc IUtilsModule\n */\n function registerCcip(\n address ccipSend,\n address ccipReceive,\n address ccipTokenPool\n ) external override {\n OwnableStorage.onlyOwner();\n\n IAssociatedSystemsModule usdToken = IAssociatedSystemsModule(\n AssociatedSystem.load(_USD_TOKEN).proxy\n );\n\n usdToken.registerUnmanagedSystem(_CCIP_CHAINLINK_SEND, ccipSend);\n usdToken.registerUnmanagedSystem(_CCIP_CHAINLINK_RECV, ccipReceive);\n usdToken.registerUnmanagedSystem(_CCIP_CHAINLINK_TOKEN_POOL, ccipTokenPool);\n }\n\n /**\n * @inheritdoc IUtilsModule\n */\n function configureOracleManager(address oracleManagerAddress) external override {\n OwnableStorage.onlyOwner();\n\n OracleManager.Data storage oracle = OracleManager.load();\n oracle.oracleManagerAddress = oracleManagerAddress;\n }\n\n function setConfig(bytes32 k, bytes32 v) external override {\n OwnableStorage.onlyOwner();\n return Config.put(k, v);\n }\n\n function getConfig(bytes32 k) external view override returns (bytes32 v) {\n OwnableStorage.onlyOwner();\n return Config.read(k);\n }\n}\n" }, "contracts/modules/core/VaultModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/DecimalMath.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\nimport \"../../storage/Account.sol\";\nimport \"../../storage/Pool.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/FeatureFlag.sol\";\n\nimport \"../../interfaces/IVaultModule.sol\";\n\n/**\n * @title Allows accounts to delegate collateral to a pool.\n * @dev See IVaultModule.\n */\ncontract VaultModule is IVaultModule {\n using SetUtil for SetUtil.UintSet;\n using SetUtil for SetUtil.Bytes32Set;\n using SetUtil for SetUtil.AddressSet;\n using DecimalMath for uint256;\n using Pool for Pool.Data;\n using Vault for Vault.Data;\n using VaultEpoch for VaultEpoch.Data;\n using Collateral for Collateral.Data;\n using CollateralConfiguration for CollateralConfiguration.Data;\n using AccountRBAC for AccountRBAC.Data;\n using Distribution for Distribution.Data;\n using CollateralConfiguration for CollateralConfiguration.Data;\n using ScalableMapping for ScalableMapping.Data;\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n\n bytes32 private constant _DELEGATE_FEATURE_FLAG = \"delegateCollateral\";\n\n /**\n * @inheritdoc IVaultModule\n */\n function delegateCollateral(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n uint256 newCollateralAmountD18,\n uint256 leverage\n ) external override {\n FeatureFlag.ensureAccessToFeature(_DELEGATE_FEATURE_FLAG);\n Pool.loadExisting(poolId);\n Account.loadAccountAndValidatePermission(accountId, AccountRBAC._DELEGATE_PERMISSION);\n\n // Each collateral type may specify a minimum collateral amount that can be delegated.\n // See CollateralConfiguration.minDelegationD18.\n if (newCollateralAmountD18 > 0) {\n CollateralConfiguration.requireSufficientDelegation(\n collateralType,\n newCollateralAmountD18\n );\n }\n\n // System only supports leverage of 1.0 for now.\n if (leverage != DecimalMath.UNIT) revert InvalidLeverage(leverage);\n\n // Identify the vault that corresponds to this collateral type and pool id.\n Vault.Data storage vault = Pool.load(poolId).vaults[collateralType];\n\n // Use account interaction to update its rewards.\n vault.updateRewards(accountId);\n\n uint256 currentCollateralAmount = vault.currentAccountCollateral(accountId);\n\n // Ensure current collateral amount differs from the new collateral amount.\n if (newCollateralAmountD18 == currentCollateralAmount) revert InvalidCollateralAmount();\n\n // If increasing delegated collateral amount,\n // Check that the account has sufficient collateral.\n if (newCollateralAmountD18 > currentCollateralAmount) {\n // Check if the collateral is enabled here because we still want to allow reducing delegation for disabled collaterals.\n CollateralConfiguration.collateralEnabled(collateralType);\n\n Account.requireSufficientCollateral(\n accountId,\n collateralType,\n newCollateralAmountD18 - currentCollateralAmount\n );\n }\n\n // Update the account's position for the given pool and collateral type,\n // Note: This will trigger an update in the entire debt distribution chain.\n uint256 collateralPrice = _updatePosition(\n accountId,\n poolId,\n collateralType,\n newCollateralAmountD18,\n currentCollateralAmount,\n leverage\n );\n\n _updateAccountCollateralPools(\n accountId,\n poolId,\n collateralType,\n newCollateralAmountD18 > 0\n );\n\n // If decreasing the delegated collateral amount,\n // check the account's collateralization ratio.\n // Note: This is the best time to do so since the user's debt and the collateral's price have both been updated.\n if (newCollateralAmountD18 < currentCollateralAmount) {\n int256 debt = vault.currentEpoch().consolidatedDebtAmountsD18[accountId];\n\n // Minimum collateralization ratios are configured in the system per collateral type.abi\n // Ensure that the account's updated position satisfies this requirement.\n CollateralConfiguration.load(collateralType).verifyIssuanceRatio(\n debt < 0 ? 0 : debt.toUint(),\n newCollateralAmountD18.mulDecimal(collateralPrice)\n );\n\n // Accounts cannot reduce collateral if any of the pool's\n // connected market has its capacity locked.\n _verifyNotCapacityLocked(poolId);\n }\n\n emit DelegationUpdated(\n accountId,\n poolId,\n collateralType,\n newCollateralAmountD18,\n leverage,\n msg.sender\n );\n }\n\n /**\n * @inheritdoc IVaultModule\n */\n function getPositionCollateralRatio(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n ) external override returns (uint256) {\n return Pool.load(poolId).currentAccountCollateralRatio(collateralType, accountId);\n }\n\n /**\n * @inheritdoc IVaultModule\n */\n function getVaultCollateralRatio(\n uint128 poolId,\n address collateralType\n ) external override returns (uint256) {\n return Pool.load(poolId).currentVaultCollateralRatio(collateralType);\n }\n\n /**\n * @inheritdoc IVaultModule\n */\n function getPositionCollateral(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n ) external view override returns (uint256 amount, uint256 value) {\n (amount, value) = Pool.load(poolId).currentAccountCollateral(collateralType, accountId);\n }\n\n /**\n * @inheritdoc IVaultModule\n */\n function getPosition(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n )\n external\n override\n returns (\n uint256 collateralAmount,\n uint256 collateralValue,\n int256 debt,\n uint256 collateralizationRatio\n )\n {\n Pool.Data storage pool = Pool.load(poolId);\n\n debt = pool.updateAccountDebt(collateralType, accountId);\n (collateralAmount, collateralValue) = pool.currentAccountCollateral(\n collateralType,\n accountId\n );\n collateralizationRatio = pool.currentAccountCollateralRatio(collateralType, accountId);\n }\n\n /**\n * @inheritdoc IVaultModule\n */\n function getPositionDebt(\n uint128 accountId,\n uint128 poolId,\n address collateralType\n ) external override returns (int256) {\n return Pool.load(poolId).updateAccountDebt(collateralType, accountId);\n }\n\n /**\n * @inheritdoc IVaultModule\n */\n function getVaultCollateral(\n uint128 poolId,\n address collateralType\n ) public view override returns (uint256 amount, uint256 value) {\n return Pool.load(poolId).currentVaultCollateral(collateralType);\n }\n\n /**\n * @inheritdoc IVaultModule\n */\n function getVaultDebt(uint128 poolId, address collateralType) public override returns (int256) {\n return Pool.load(poolId).currentVaultDebt(collateralType);\n }\n\n /**\n * @dev Updates the given account's position regarding the given pool and collateral type,\n * with the new amount of delegated collateral.\n *\n * The update will be reflected in the registered delegated collateral amount,\n * but it will also trigger updates to the entire debt distribution chain.\n */\n function _updatePosition(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n uint256 newCollateralAmount,\n uint256 oldCollateralAmount,\n uint256 leverage\n ) internal returns (uint256 collateralPrice) {\n Pool.Data storage pool = Pool.load(poolId);\n\n // Trigger an update in the debt distribution chain to make sure that\n // the user's debt is up to date.\n pool.updateAccountDebt(collateralType, accountId);\n\n // Get the collateral entry for the given account and collateral type.\n Collateral.Data storage collateral = Account.load(accountId).collaterals[collateralType];\n\n // Adjust collateral depending on increase/decrease of amount.\n if (newCollateralAmount > oldCollateralAmount) {\n collateral.decreaseAvailableCollateral(newCollateralAmount - oldCollateralAmount);\n } else {\n collateral.increaseAvailableCollateral(oldCollateralAmount - newCollateralAmount);\n }\n\n // If the collateral amount is not negative, make sure that the pool exists\n // in the collateral entry's pool array. Otherwise remove it.\n _updateAccountCollateralPools(accountId, poolId, collateralType, newCollateralAmount > 0);\n\n // Update the account's position in the vault data structure.\n pool.vaults[collateralType].currentEpoch().updateAccountPosition(\n accountId,\n newCollateralAmount,\n leverage\n );\n\n // Trigger another update in the debt distribution chain,\n // and surface the latest price for the given collateral type (which is retrieved in the update).\n collateralPrice = pool.recalculateVaultCollateral(collateralType);\n }\n\n function _verifyNotCapacityLocked(uint128 poolId) internal view {\n Pool.Data storage pool = Pool.load(poolId);\n\n Market.Data storage market = pool.findMarketWithCapacityLocked();\n\n if (market.id > 0) {\n revert CapacityLocked(market.id);\n }\n }\n\n /**\n * @dev Registers the pool in the given account's collaterals array.\n */\n function _updateAccountCollateralPools(\n uint128 accountId,\n uint128 poolId,\n address collateralType,\n bool added\n ) internal {\n Collateral.Data storage depositedCollateral = Account.load(accountId).collaterals[\n collateralType\n ];\n\n bool containsPool = depositedCollateral.pools.contains(poolId);\n if (added && !containsPool) {\n depositedCollateral.pools.add(poolId);\n } else if (!added && containsPool) {\n depositedCollateral.pools.remove(poolId);\n }\n }\n}\n" }, "contracts/modules/InitialModuleBundle.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./common/OwnerModule.sol\";\nimport \"./common/UpgradeModule.sol\";\n\n// The below contract is only used during initialization as a kernel for the first release which the system can be upgraded onto.\n// Subsequent upgrades will not need this module bundle\n// In the future on live networks, we may want to find some way to hardcode the owner address here to prevent grieving\n\n// solhint-disable-next-line no-empty-blocks\ncontract InitialModuleBundle is OwnerModule, UpgradeModule {\n\n}\n" }, "contracts/modules/usd/USDTokenModule.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"../../interfaces/IUSDTokenModule.sol\";\nimport \"../../interfaces/external/IEVM2AnySubscriptionOnRampRouterInterface.sol\";\n\nimport \"@synthetixio/core-modules/contracts/storage/AssociatedSystem.sol\";\nimport \"@synthetixio/core-contracts/contracts/token/ERC20.sol\";\nimport \"@synthetixio/core-contracts/contracts/initializable/InitializableMixin.sol\";\nimport \"@synthetixio/core-contracts/contracts/ownership/OwnableStorage.sol\";\n\n/**\n * @title Module for managing the snxUSD token as an associated system.\n * @dev See IUSDTokenModule.\n */\ncontract USDTokenModule is ERC20, InitializableMixin, IUSDTokenModule {\n using AssociatedSystem for AssociatedSystem.Data;\n\n uint256 private constant _TRANSFER_GAS_LIMIT = 100000;\n\n bytes32 private constant _CCIP_CHAINLINK_SEND = \"ccipChainlinkSend\";\n bytes32 private constant _CCIP_CHAINLINK_RECV = \"ccipChainlinkRecv\";\n bytes32 private constant _CCIP_CHAINLINK_TOKEN_POOL = \"ccipChainlinkTokenPool\";\n\n /**\n * @dev For use as an associated system.\n */\n function _isInitialized() internal view override returns (bool) {\n return ERC20Storage.load().decimals != 0;\n }\n\n /**\n * @dev For use as an associated system.\n */\n function isInitialized() external view returns (bool) {\n return _isInitialized();\n }\n\n /**\n * @dev For use as an associated system.\n */\n function initialize(\n string memory tokenName,\n string memory tokenSymbol,\n uint8 tokenDecimals\n ) public virtual {\n OwnableStorage.onlyOwner();\n _initialize(tokenName, tokenSymbol, tokenDecimals);\n }\n\n /**\n * @dev Allows the core system and CCIP to mint tokens.\n */\n function mint(address target, uint256 amount) external override {\n if (\n msg.sender != OwnableStorage.getOwner() &&\n msg.sender != AssociatedSystem.load(_CCIP_CHAINLINK_TOKEN_POOL).proxy\n ) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n _mint(target, amount);\n }\n\n /**\n * @dev Allows the core system and CCIP to burn tokens.\n */\n function burn(address target, uint256 amount) external override {\n if (\n msg.sender != OwnableStorage.getOwner() &&\n msg.sender != AssociatedSystem.load(_CCIP_CHAINLINK_TOKEN_POOL).proxy\n ) {\n revert AccessError.Unauthorized(msg.sender);\n }\n\n _burn(target, amount);\n }\n\n /**\n * @inheritdoc IUSDTokenModule\n */\n function burnWithAllowance(address from, address spender, uint256 amount) external {\n OwnableStorage.onlyOwner();\n\n ERC20Storage.Data storage erc20 = ERC20Storage.load();\n\n if (amount > erc20.allowance[from][spender]) {\n revert InsufficientAllowance(amount, erc20.allowance[from][spender]);\n }\n\n erc20.allowance[from][spender] -= amount;\n\n _burn(from, amount);\n }\n\n /**\n * @inheritdoc IUSDTokenModule\n */\n function transferCrossChain(\n uint256 destChainId,\n address to,\n uint256 amount\n ) external returns (uint256 feesPaid) {\n AssociatedSystem.load(_CCIP_CHAINLINK_SEND).expectKind(AssociatedSystem.KIND_UNMANAGED);\n\n IERC20[] memory tokens = new IERC20[](1);\n tokens[0] = IERC20(address(this));\n\n uint256[] memory amounts = new uint256[](1);\n amounts[0] = amount;\n\n IEVM2AnySubscriptionOnRampRouterInterface(AssociatedSystem.load(_CCIP_CHAINLINK_SEND).proxy)\n .ccipSend(\n destChainId,\n IEVM2AnySubscriptionOnRampRouterInterface.EVM2AnySubscriptionMessage(\n abi.encode(to), // Address of the receiver on the destination chain for EVM chains use abi.encode(destAddress).\n \"\", // Bytes that we wish to send to the receiver\n tokens, // The ERC20 tokens we wish to send for EVM source chains\n amounts, // The amount of ERC20 tokens we wish to send for EVM source chains\n _TRANSFER_GAS_LIMIT // the gas limit for the call to the receiver for destination chains\n )\n );\n\n return (0);\n }\n\n /**\n * @dev Included to satisfy ITokenModule inheritance.\n */\n function setAllowance(address from, address spender, uint256 amount) external override {\n OwnableStorage.onlyOwner();\n ERC20Storage.load().allowance[from][spender] = amount;\n }\n}\n" }, "contracts/Proxy.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport {UUPSProxyWithOwner} from \"@synthetixio/core-contracts/contracts/proxy/UUPSProxyWithOwner.sol\";\n\n/**\n * Synthetix V3 Core Proxy Contract\n *\n * Visit https://usecannon.com/packages/synthetix to interact with this protocol\n */\ncontract Proxy is UUPSProxyWithOwner {\n // solhint-disable-next-line no-empty-blocks\n constructor(\n address firstImplementation,\n address initialOwner\n ) UUPSProxyWithOwner(firstImplementation, initialOwner) {}\n}\n" }, "contracts/storage/Account.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./AccountRBAC.sol\";\nimport \"./Collateral.sol\";\nimport \"./Pool.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\n/**\n * @title Object for tracking accounts with access control and collateral tracking.\n */\nlibrary Account {\n using AccountRBAC for AccountRBAC.Data;\n using Pool for Pool.Data;\n using Collateral for Collateral.Data;\n using SetUtil for SetUtil.UintSet;\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n\n /**\n * @dev Thrown when the given target address does not have the given permission with the given account.\n */\n error PermissionDenied(uint128 accountId, bytes32 permission, address target);\n\n /**\n * @dev Thrown when an account cannot be found.\n */\n error AccountNotFound(uint128 accountId);\n\n /**\n * @dev Thrown when an account does not have sufficient collateral for a particular operation in the system.\n */\n error InsufficientAccountCollateral(uint256 requestedAmount);\n\n /**\n * @dev Thrown when the requested operation requires an activity timeout before the\n */\n error AccountActivityTimeoutPending(\n uint128 accountId,\n uint256 currentTime,\n uint256 requiredTime\n );\n\n struct Data {\n /**\n * @dev Numeric identifier for the account. Must be unique.\n * @dev There cannot be an account with id zero (See ERC721._mint()).\n */\n uint128 id;\n /**\n * @dev Role based access control data for the account.\n */\n AccountRBAC.Data rbac;\n uint64 lastInteraction;\n uint64 __slotAvailableForFutureUse;\n uint128 __slot2AvailableForFutureUse;\n /**\n * @dev Address set of collaterals that are being used in the system by this account.\n */\n mapping(address => Collateral.Data) collaterals;\n }\n\n /**\n * @dev Returns the account stored at the specified account id.\n */\n function load(uint128 id) internal pure returns (Data storage account) {\n bytes32 s = keccak256(abi.encode(\"io.synthetix.synthetix.Account\", id));\n assembly {\n account.slot := s\n }\n }\n\n /**\n * @dev Creates an account for the given id, and associates it to the given owner.\n *\n * Note: Will not fail if the account already exists, and if so, will overwrite the existing owner. Whatever calls this internal function must first check that the account doesn't exist before re-creating it.\n */\n function create(uint128 id, address owner) internal returns (Data storage account) {\n account = load(id);\n\n account.id = id;\n account.rbac.owner = owner;\n }\n\n /**\n * @dev Reverts if the account does not exist with appropriate error. Otherwise, returns the account.\n */\n function exists(uint128 id) internal view returns (Data storage account) {\n Data storage a = load(id);\n if (a.rbac.owner == address(0)) {\n revert AccountNotFound(id);\n }\n\n return a;\n }\n\n /**\n * @dev Given a collateral type, returns information about the total collateral assigned, deposited, and locked by the account\n */\n function getCollateralTotals(\n Data storage self,\n address collateralType\n )\n internal\n view\n returns (uint256 totalDepositedD18, uint256 totalAssignedD18, uint256 totalLockedD18)\n {\n totalAssignedD18 = getAssignedCollateral(self, collateralType);\n totalDepositedD18 =\n totalAssignedD18 +\n self.collaterals[collateralType].amountAvailableForDelegationD18;\n totalLockedD18 = self.collaterals[collateralType].getTotalLocked();\n\n return (totalDepositedD18, totalAssignedD18, totalLockedD18);\n }\n\n /**\n * @dev Returns the total amount of collateral that has been delegated to pools by the account, for the given collateral type.\n */\n function getAssignedCollateral(\n Data storage self,\n address collateralType\n ) internal view returns (uint256) {\n uint256 totalAssignedD18 = 0;\n\n SetUtil.UintSet storage pools = self.collaterals[collateralType].pools;\n\n for (uint256 i = 1; i <= pools.length(); i++) {\n uint128 poolIdx = pools.valueAt(i).to128();\n\n Pool.Data storage pool = Pool.load(poolIdx);\n\n (uint256 collateralAmountD18, ) = pool.currentAccountCollateral(\n collateralType,\n self.id\n );\n totalAssignedD18 += collateralAmountD18;\n }\n\n return totalAssignedD18;\n }\n\n function recordInteraction(Data storage self) internal {\n // solhint-disable-next-line numcast/safe-cast\n self.lastInteraction = uint64(block.timestamp);\n }\n\n /**\n * @dev Loads the Account object for the specified accountId,\n * and validates that sender has the specified permission. It also resets\n * the interaction timeout. These\n * are different actions but they are merged in a single function\n * because loading an account and checking for a permission is a very\n * common use case in other parts of the code.\n */\n function loadAccountAndValidatePermission(\n uint128 accountId,\n bytes32 permission\n ) internal returns (Data storage account) {\n account = Account.load(accountId);\n\n if (!account.rbac.authorized(permission, msg.sender)) {\n revert PermissionDenied(accountId, permission, msg.sender);\n }\n\n recordInteraction(account);\n }\n\n /**\n * @dev Loads the Account object for the specified accountId,\n * and validates that sender has the specified permission. It also resets\n * the interaction timeout. These\n * are different actions but they are merged in a single function\n * because loading an account and checking for a permission is a very\n * common use case in other parts of the code.\n */\n function loadAccountAndValidatePermissionAndTimeout(\n uint128 accountId,\n bytes32 permission,\n uint256 timeout\n ) internal view returns (Data storage account) {\n account = Account.load(accountId);\n\n if (!account.rbac.authorized(permission, msg.sender)) {\n revert PermissionDenied(accountId, permission, msg.sender);\n }\n\n uint256 endWaitingPeriod = account.lastInteraction + timeout;\n if (block.timestamp < endWaitingPeriod) {\n revert AccountActivityTimeoutPending(accountId, block.timestamp, endWaitingPeriod);\n }\n }\n\n /**\n * @dev Ensure that the account has the required amount of collateral funds remaining\n */\n function requireSufficientCollateral(\n uint128 accountId,\n address collateralType,\n uint256 amountD18\n ) internal view {\n if (\n Account.load(accountId).collaterals[collateralType].amountAvailableForDelegationD18 <\n amountD18\n ) {\n revert InsufficientAccountCollateral(amountD18);\n }\n }\n}\n" }, "contracts/storage/AccountRBAC.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/SetUtil.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/AddressError.sol\";\n\n/**\n * @title Object for tracking an accounts permissions (role based access control).\n */\nlibrary AccountRBAC {\n using SetUtil for SetUtil.Bytes32Set;\n using SetUtil for SetUtil.AddressSet;\n\n /**\n * @dev All permissions used by the system\n * need to be hardcoded here.\n */\n bytes32 internal constant _ADMIN_PERMISSION = \"ADMIN\";\n bytes32 internal constant _WITHDRAW_PERMISSION = \"WITHDRAW\";\n bytes32 internal constant _DELEGATE_PERMISSION = \"DELEGATE\";\n bytes32 internal constant _MINT_PERMISSION = \"MINT\";\n bytes32 internal constant _REWARDS_PERMISSION = \"REWARDS\";\n\n /**\n * @dev Thrown when a permission specified by a user does not exist or is invalid.\n */\n error InvalidPermission(bytes32 permission);\n\n struct Data {\n /**\n * @dev The owner of the account and admin of all permissions.\n */\n address owner;\n /**\n * @dev Set of permissions for each address enabled by the account.\n */\n mapping(address => SetUtil.Bytes32Set) permissions;\n /**\n * @dev Array of addresses that this account has given permissions to.\n */\n SetUtil.AddressSet permissionAddresses;\n }\n\n /**\n * @dev Reverts if the specified permission is unknown to the account RBAC system.\n */\n function isPermissionValid(bytes32 permission) internal pure {\n if (\n permission != AccountRBAC._WITHDRAW_PERMISSION &&\n permission != AccountRBAC._DELEGATE_PERMISSION &&\n permission != AccountRBAC._MINT_PERMISSION &&\n permission != AccountRBAC._ADMIN_PERMISSION &&\n permission != AccountRBAC._REWARDS_PERMISSION\n ) {\n revert InvalidPermission(permission);\n }\n }\n\n /**\n * @dev Sets the owner of the account.\n */\n function setOwner(Data storage self, address owner) internal {\n self.owner = owner;\n }\n\n /**\n * @dev Grants a particular permission to the specified target address.\n */\n function grantPermission(Data storage self, bytes32 permission, address target) internal {\n if (target == address(0)) {\n revert AddressError.ZeroAddress();\n }\n\n if (permission == \"\") {\n revert InvalidPermission(\"\");\n }\n\n if (!self.permissionAddresses.contains(target)) {\n self.permissionAddresses.add(target);\n }\n\n self.permissions[target].add(permission);\n }\n\n /**\n * @dev Revokes a particular permission from the specified target address.\n */\n function revokePermission(Data storage self, bytes32 permission, address target) internal {\n self.permissions[target].remove(permission);\n\n if (self.permissions[target].length() == 0) {\n self.permissionAddresses.remove(target);\n }\n }\n\n /**\n * @dev Revokes all permissions for the specified target address.\n * @notice only removes permissions for the given address, not for the entire account\n */\n function revokeAllPermissions(Data storage self, address target) internal {\n bytes32[] memory permissions = self.permissions[target].values();\n\n if (permissions.length == 0) {\n return;\n }\n\n for (uint256 i = 0; i < permissions.length; i++) {\n self.permissions[target].remove(permissions[i]);\n }\n\n self.permissionAddresses.remove(target);\n }\n\n /**\n * @dev Returns wether the specified address has the given permission.\n */\n function hasPermission(\n Data storage self,\n bytes32 permission,\n address target\n ) internal view returns (bool) {\n return target != address(0) && self.permissions[target].contains(permission);\n }\n\n /**\n * @dev Returns wether the specified target address has the given permission, or has the high level admin permission.\n */\n function authorized(\n Data storage self,\n bytes32 permission,\n address target\n ) internal view returns (bool) {\n return ((target == self.owner) ||\n hasPermission(self, _ADMIN_PERMISSION, target) ||\n hasPermission(self, permission, target));\n }\n}\n" }, "contracts/storage/Collateral.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/SetUtil.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\nimport \"./CollateralLock.sol\";\n\n/**\n * @title Stores information about a deposited asset for a given account.\n *\n * Each account will have one of these objects for each type of collateral it deposited in the system.\n */\nlibrary Collateral {\n using SafeCastU256 for uint256;\n\n struct Data {\n /**\n * @dev The amount that can be withdrawn or delegated in this collateral.\n */\n uint256 amountAvailableForDelegationD18;\n /**\n * @dev The pools to which this collateral delegates to.\n */\n SetUtil.UintSet pools;\n /**\n * @dev Marks portions of the collateral as locked,\n * until a given unlock date.\n *\n * Note: Locks apply to delegated collateral and to collateral not\n * assigned or delegated to a pool (see ICollateralModule).\n */\n CollateralLock.Data[] locks;\n }\n\n /**\n * @dev Increments the entry's availableCollateral.\n */\n function increaseAvailableCollateral(Data storage self, uint256 amountD18) internal {\n self.amountAvailableForDelegationD18 += amountD18;\n }\n\n /**\n * @dev Decrements the entry's availableCollateral.\n */\n function decreaseAvailableCollateral(Data storage self, uint256 amountD18) internal {\n self.amountAvailableForDelegationD18 -= amountD18;\n }\n\n /**\n * @dev Returns the total amount in this collateral entry that is locked.\n *\n * Sweeps through all existing locks and accumulates their amount,\n * if their unlock date is in the future.\n */\n function getTotalLocked(Data storage self) internal view returns (uint256) {\n uint64 currentTime = block.timestamp.to64();\n\n uint256 lockedD18;\n for (uint256 i = 0; i < self.locks.length; i++) {\n CollateralLock.Data storage lock = self.locks[i];\n\n if (lock.lockExpirationTime > currentTime) {\n lockedD18 += lock.amountD18;\n }\n }\n\n return lockedD18;\n }\n}\n" }, "contracts/storage/CollateralConfiguration.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/SetUtil.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/DecimalMath.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/ParameterError.sol\";\nimport \"@synthetixio/oracle-manager/contracts/interfaces/INodeModule.sol\";\nimport \"@synthetixio/oracle-manager/contracts/storage/NodeOutput.sol\";\nimport \"@synthetixio/core-contracts/contracts/interfaces/IERC20.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\nimport \"./OracleManager.sol\";\n\n/**\n * @title Tracks system-wide settings for each collateral type, as well as helper functions for it, such as retrieving its current price from the oracle manager.\n */\nlibrary CollateralConfiguration {\n bytes32 private constant _SLOT_AVAILABLE_COLLATERALS =\n keccak256(\n abi.encode(\"io.synthetix.synthetix.CollateralConfiguration_availableCollaterals\")\n );\n\n using SetUtil for SetUtil.AddressSet;\n using DecimalMath for uint256;\n using SafeCastI256 for int256;\n\n /**\n * @dev Thrown when the token address of a collateral cannot be found.\n */\n error CollateralNotFound();\n\n /**\n * @dev Thrown when deposits are disabled for the given collateral type.\n * @param collateralType The address of the collateral type for which depositing was disabled.\n */\n error CollateralDepositDisabled(address collateralType);\n\n /**\n * @dev Thrown when collateral ratio is not sufficient in a given operation in the system.\n * @param collateralValue The net USD value of the position.\n * @param debt The net USD debt of the position.\n * @param ratio The collateralization ratio of the position.\n * @param minRatio The minimum c-ratio which was not met. Could be issuance ratio or liquidation ratio, depending on the case.\n */\n error InsufficientCollateralRatio(\n uint256 collateralValue,\n uint256 debt,\n uint256 ratio,\n uint256 minRatio\n );\n\n /**\n * @dev Thrown when the amount being delegated is less than the minimum expected amount.\n * @param minDelegation The current minimum for deposits and delegation set to this collateral type.\n */\n error InsufficientDelegation(uint256 minDelegation);\n\n /**\n * @dev Thrown when attempting to convert a token to the system amount and the conversion results in a loss of precision.\n * @param tokenAmount The amount of tokens that were attempted to be converted.\n * @param decimals The number of decimals of the token that was attempted to be converted.\n */\n error PrecisionLost(uint tokenAmount, uint8 decimals);\n\n struct Data {\n /**\n * @dev Allows the owner to control deposits and delegation of collateral types.\n */\n bool depositingEnabled;\n /**\n * @dev System-wide collateralization ratio for issuance of snxUSD.\n * Accounts will not be able to mint snxUSD if they are below this issuance c-ratio.\n */\n uint256 issuanceRatioD18;\n /**\n * @dev System-wide collateralization ratio for liquidations of this collateral type.\n * Accounts below this c-ratio can be immediately liquidated.\n */\n uint256 liquidationRatioD18;\n /**\n * @dev Amount of tokens to award when an account is liquidated.\n */\n uint256 liquidationRewardD18;\n /**\n * @dev The oracle manager node id which reports the current price for this collateral type.\n */\n bytes32 oracleNodeId;\n /**\n * @dev The token address for this collateral type.\n */\n address tokenAddress;\n /**\n * @dev Minimum amount that accounts can delegate to pools.\n * Helps prevent spamming on the system.\n * Note: If zero, liquidationRewardD18 will be used.\n */\n uint256 minDelegationD18;\n }\n\n /**\n * @dev Loads the CollateralConfiguration object for the given collateral type.\n * @param token The address of the collateral type.\n * @return collateralConfiguration The CollateralConfiguration object.\n */\n function load(address token) internal pure returns (Data storage collateralConfiguration) {\n bytes32 s = keccak256(abi.encode(\"io.synthetix.synthetix.CollateralConfiguration\", token));\n assembly {\n collateralConfiguration.slot := s\n }\n }\n\n /**\n * @dev Loads all available collateral types configured in the system.\n * @return availableCollaterals An array of addresses, one for each collateral type supported by the system.\n */\n function loadAvailableCollaterals()\n internal\n pure\n returns (SetUtil.AddressSet storage availableCollaterals)\n {\n bytes32 s = _SLOT_AVAILABLE_COLLATERALS;\n assembly {\n availableCollaterals.slot := s\n }\n }\n\n /**\n * @dev Configures a collateral type.\n * @param config The CollateralConfiguration object with all the settings for the collateral type being configured.\n */\n function set(Data memory config) internal {\n SetUtil.AddressSet storage collateralTypes = loadAvailableCollaterals();\n\n if (!collateralTypes.contains(config.tokenAddress)) {\n collateralTypes.add(config.tokenAddress);\n }\n\n if (config.minDelegationD18 < config.liquidationRewardD18) {\n revert ParameterError.InvalidParameter(\n \"minDelegation\",\n \"must be greater than liquidationReward\"\n );\n }\n\n Data storage storedConfig = load(config.tokenAddress);\n\n storedConfig.tokenAddress = config.tokenAddress;\n storedConfig.issuanceRatioD18 = config.issuanceRatioD18;\n storedConfig.liquidationRatioD18 = config.liquidationRatioD18;\n storedConfig.oracleNodeId = config.oracleNodeId;\n storedConfig.liquidationRewardD18 = config.liquidationRewardD18;\n storedConfig.minDelegationD18 = config.minDelegationD18;\n storedConfig.depositingEnabled = config.depositingEnabled;\n }\n\n /**\n * @dev Shows if a given collateral type is enabled for deposits and delegation.\n * @param token The address of the collateral being queried.\n */\n function collateralEnabled(address token) internal view {\n if (!load(token).depositingEnabled) {\n revert CollateralDepositDisabled(token);\n }\n }\n\n /**\n * @dev Reverts if the amount being delegated is insufficient for the system.\n * @param token The address of the collateral type.\n * @param amountD18 The amount being checked for sufficient delegation.\n */\n function requireSufficientDelegation(address token, uint256 amountD18) internal view {\n CollateralConfiguration.Data storage config = load(token);\n\n uint256 minDelegationD18 = config.minDelegationD18;\n\n if (minDelegationD18 == 0) {\n minDelegationD18 = config.liquidationRewardD18;\n }\n\n if (amountD18 < minDelegationD18) {\n revert InsufficientDelegation(minDelegationD18);\n }\n }\n\n /**\n * @dev Returns the price of this collateral configuration object.\n * @param self The CollateralConfiguration object.\n * @return The price of the collateral with 18 decimals of precision.\n */\n function getCollateralPrice(Data storage self) internal view returns (uint256) {\n OracleManager.Data memory oracleManager = OracleManager.load();\n NodeOutput.Data memory node = INodeModule(oracleManager.oracleManagerAddress).process(\n self.oracleNodeId\n );\n\n return node.price.toUint();\n }\n\n /**\n * @dev Reverts if the specified collateral and debt values produce a collateralization ratio which is below the amount required for new issuance of snxUSD.\n * @param self The CollateralConfiguration object whose collateral and settings are being queried.\n * @param debtD18 The debt component of the ratio.\n * @param collateralValueD18 The collateral component of the ratio.\n */\n function verifyIssuanceRatio(\n Data storage self,\n uint256 debtD18,\n uint256 collateralValueD18\n ) internal view {\n if (\n debtD18 != 0 &&\n (collateralValueD18 == 0 ||\n collateralValueD18.divDecimal(debtD18) < self.issuanceRatioD18)\n ) {\n revert InsufficientCollateralRatio(\n collateralValueD18,\n debtD18,\n collateralValueD18.divDecimal(debtD18),\n self.issuanceRatioD18\n );\n }\n }\n\n /**\n * @dev Converts token amounts with non-system decimal precisions, to 18 decimals of precision.\n * E.g: $TOKEN_A uses 6 decimals of precision, so this would upscale it by 12 decimals.\n * E.g: $TOKEN_B uses 20 decimals of precision, so this would downscale it by 2 decimals.\n * @param self The CollateralConfiguration object corresponding to the collateral type being converted.\n * @param tokenAmount The token amount, denominated in its native decimal precision.\n * @return amountD18 The converted amount, denominated in the system's 18 decimal precision.\n */\n function convertTokenToSystemAmount(\n Data storage self,\n uint256 tokenAmount\n ) internal view returns (uint256 amountD18) {\n // this extra condition is to prevent potentially malicious untrusted code from being executed on the next statement\n if (self.tokenAddress == address(0)) {\n revert CollateralNotFound();\n }\n\n /// @dev this try-catch block assumes there is no malicious code in the token's fallback function\n try IERC20(self.tokenAddress).decimals() returns (uint8 decimals) {\n if (decimals == 18) {\n amountD18 = tokenAmount;\n } else if (decimals < 18) {\n amountD18 = (tokenAmount * DecimalMath.UNIT) / (10 ** decimals);\n } else {\n // ensure no precision is lost when converting to 18 decimals\n if (tokenAmount % (10 ** (decimals - 18)) != 0) {\n revert PrecisionLost(tokenAmount, decimals);\n }\n\n // this will scale down the amount by the difference between the token's decimals and 18\n amountD18 = (tokenAmount * DecimalMath.UNIT) / (10 ** decimals);\n }\n } catch {\n // if the token doesn't have a decimals function, assume it's 18 decimals\n amountD18 = tokenAmount;\n }\n }\n}\n" }, "contracts/storage/CollateralLock.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Represents a given amount of collateral locked until a given date.\n */\nlibrary CollateralLock {\n struct Data {\n /**\n * @dev The amount of collateral that has been locked.\n */\n uint128 amountD18;\n /**\n * @dev The date when the locked amount becomes unlocked.\n */\n uint64 lockExpirationTime;\n }\n}\n" }, "contracts/storage/Config.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title System wide configuration for anything\n */\nlibrary Config {\n struct Data {\n uint256 __unused;\n }\n\n /**\n * @dev Returns a config value\n */\n function read(bytes32 k) internal view returns (bytes32 v) {\n bytes32 s = keccak256(abi.encode(\"Config\", k));\n assembly {\n v := sload(s)\n }\n }\n\n function put(bytes32 k, bytes32 v) internal {\n bytes32 s = keccak256(abi.encode(\"Config\", k));\n assembly {\n sstore(s, v)\n }\n }\n}\n" }, "contracts/storage/Distribution.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/DecimalMath.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\nimport \"./DistributionActor.sol\";\n\n/**\n * @title Data structure that allows you to track some global value, distributed amongst a set of actors.\n *\n * The total value can be scaled with a valuePerShare multiplier, and individual actor shares can be calculated as their amount of shares times this multiplier.\n *\n * Furthermore, changes in the value of individual actors can be tracked since their last update, by keeping track of the value of the multiplier, per user, upon each interaction. See DistributionActor.lastValuePerShare.\n *\n * A distribution is similar to a ScalableMapping, but it has the added functionality of being able to remember the previous value of the scalar multiplier for each actor.\n *\n * Whenever the shares of an actor of the distribution is updated, you get information about how the actor's total value changed since it was last updated.\n */\nlibrary Distribution {\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n using DecimalMath for int256;\n\n /**\n * @dev Thrown when an attempt is made to distribute value to a distribution\n * with no shares.\n */\n error EmptyDistribution();\n\n struct Data {\n /**\n * @dev The total number of shares in the distribution.\n */\n uint128 totalSharesD18;\n /**\n * @dev The value per share of the distribution, represented as a high precision decimal.\n */\n int128 valuePerShareD27;\n /**\n * @dev Tracks individual actor information, such as how many shares an actor has, their lastValuePerShare, etc.\n */\n mapping(bytes32 => DistributionActor.Data) actorInfo;\n }\n\n /**\n * @dev Inflates or deflates the total value of the distribution by the given value.\n *\n * The value being distributed ultimately modifies the distribution's valuePerShare.\n */\n function distributeValue(Data storage self, int256 valueD18) internal {\n if (valueD18 == 0) {\n return;\n }\n\n uint256 totalSharesD18 = self.totalSharesD18;\n\n if (totalSharesD18 == 0) {\n revert EmptyDistribution();\n }\n\n int256 valueD45 = valueD18 * DecimalMath.UNIT_PRECISE_INT;\n int256 deltaValuePerShareD27 = valueD45 / totalSharesD18.toInt();\n\n self.valuePerShareD27 += deltaValuePerShareD27.to128();\n }\n\n /**\n * @dev Updates an actor's number of shares in the distribution to the specified amount.\n *\n * Whenever an actor's shares are changed in this way, we record the distribution's current valuePerShare into the actor's lastValuePerShare record.\n *\n * Returns the the amount by which the actors value changed since the last update.\n */\n function setActorShares(\n Data storage self,\n bytes32 actorId,\n uint256 newActorSharesD18\n ) internal returns (int valueChangeD18) {\n valueChangeD18 = getActorValueChange(self, actorId);\n\n DistributionActor.Data storage actor = self.actorInfo[actorId];\n\n uint128 sharesUint128D18 = newActorSharesD18.to128();\n self.totalSharesD18 = self.totalSharesD18 + sharesUint128D18 - actor.sharesD18;\n\n actor.sharesD18 = sharesUint128D18;\n _updateLastValuePerShare(self, actor, newActorSharesD18);\n }\n\n /**\n * @dev Updates an actor's lastValuePerShare to the distribution's current valuePerShare, and\n * returns the change in value for the actor, since their last update.\n */\n function accumulateActor(\n Data storage self,\n bytes32 actorId\n ) internal returns (int valueChangeD18) {\n DistributionActor.Data storage actor = self.actorInfo[actorId];\n return _updateLastValuePerShare(self, actor, actor.sharesD18);\n }\n\n /**\n * @dev Calculates how much an actor's value has changed since its shares were last updated.\n *\n * This change is calculated as:\n * Since `value = valuePerShare * shares`,\n * then `delta_value = valuePerShare_now * shares - valuePerShare_then * shares`,\n * which is `(valuePerShare_now - valuePerShare_then) * shares`,\n * or just `delta_valuePerShare * shares`.\n */\n function getActorValueChange(\n Data storage self,\n bytes32 actorId\n ) internal view returns (int valueChangeD18) {\n return _getActorValueChange(self, self.actorInfo[actorId]);\n }\n\n /**\n * @dev Returns the number of shares owned by an actor in the distribution.\n */\n function getActorShares(\n Data storage self,\n bytes32 actorId\n ) internal view returns (uint256 sharesD18) {\n return self.actorInfo[actorId].sharesD18;\n }\n\n /**\n * @dev Returns the distribution's value per share in normal precision (18 decimals).\n * @param self The distribution whose value per share is being queried.\n * @return The value per share in 18 decimal precision.\n */\n function getValuePerShare(Data storage self) internal view returns (int) {\n return self.valuePerShareD27.to256().downscale(DecimalMath.PRECISION_FACTOR);\n }\n\n function _updateLastValuePerShare(\n Data storage self,\n DistributionActor.Data storage actor,\n uint256 newActorShares\n ) private returns (int valueChangeD18) {\n valueChangeD18 = _getActorValueChange(self, actor);\n\n actor.lastValuePerShareD27 = newActorShares == 0\n ? SafeCastI128.zero()\n : self.valuePerShareD27;\n }\n\n function _getActorValueChange(\n Data storage self,\n DistributionActor.Data storage actor\n ) private view returns (int valueChangeD18) {\n int256 deltaValuePerShareD27 = self.valuePerShareD27 - actor.lastValuePerShareD27;\n\n int256 changedValueD45 = deltaValuePerShareD27 * actor.sharesD18.toInt();\n valueChangeD18 = changedValueD45 / DecimalMath.UNIT_PRECISE_INT;\n }\n}\n" }, "contracts/storage/DistributionActor.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Stores information for specific actors in a Distribution.\n */\nlibrary DistributionActor {\n struct Data {\n /**\n * @dev The actor's current number of shares in the associated distribution.\n */\n uint128 sharesD18;\n /**\n * @dev The value per share that the associated distribution had at the time that the actor's number of shares was last modified.\n *\n * Note: This is also a high precision decimal. See Distribution.valuePerShare.\n */\n int128 lastValuePerShareD27;\n }\n}\n" }, "contracts/storage/Market.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/HeapUtil.sol\";\n\nimport \"./Distribution.sol\";\nimport \"./CollateralConfiguration.sol\";\nimport \"./MarketPoolInfo.sol\";\n\nimport \"../interfaces/external/IMarket.sol\";\n\n/**\n * @title Connects external contracts that implement the `IMarket` interface to the system.\n *\n * Pools provide credit capacity (collateral) to the markets, and are reciprocally exposed to the associated market's debt.\n *\n * The Market object's main responsibility is to track collateral provided by the pools that support it, and to trace their debt back to such pools.\n */\nlibrary Market {\n using Distribution for Distribution.Data;\n using HeapUtil for HeapUtil.Data;\n using DecimalMath for uint256;\n using DecimalMath for uint128;\n using DecimalMath for int256;\n using DecimalMath for int128;\n using SafeCastU256 for uint256;\n using SafeCastU128 for uint128;\n using SafeCastI256 for int256;\n using SafeCastI128 for int128;\n\n /**\n * @dev Thrown when a specified market is not found.\n */\n error MarketNotFound(uint128 marketId);\n\n struct Data {\n /**\n * @dev Numeric identifier for the market. Must be unique.\n * @dev There cannot be a market with id zero (See MarketCreator.create()). Id zero is used as a null market reference.\n */\n uint128 id;\n /**\n * @dev Address for the external contract that implements the `IMarket` interface, which this Market objects connects to.\n *\n * Note: This object is how the system tracks the market. The actual market is external to the system, i.e. its own contract.\n */\n address marketAddress;\n /**\n * @dev Issuance can be seen as how much USD the Market \"has issued\", printed, or has asked the system to mint on its behalf.\n *\n * More precisely it can be seen as the net difference between the USD burnt and the USD minted by the market.\n *\n * More issuance means that the market owes more USD to the system.\n *\n * A market burns USD when users deposit it in exchange for some asset that the market offers.\n * The Market object calls `MarketManager.depositUSD()`, which burns the USD, and decreases its issuance.\n *\n * A market mints USD when users return the asset that the market offered and thus withdraw their USD.\n * The Market object calls `MarketManager.withdrawUSD()`, which mints the USD, and increases its issuance.\n *\n * Instead of burning, the Market object could transfer USD to and from the MarketManager, but minting and burning takes the USD out of circulation, which doesn't affect `totalSupply`, thus simplifying accounting.\n *\n * How much USD a market can mint depends on how much credit capacity is given to the market by the pools that support it, and reflected in `Market.capacity`.\n *\n */\n int128 netIssuanceD18;\n /**\n * @dev The total amount of USD that the market could withdraw if it were to immediately unwrap all its positions.\n *\n * The Market's credit capacity increases when the market burns USD, i.e. when it deposits USD in the MarketManager.\n *\n * It decreases when the market mints USD, i.e. when it withdraws USD from the MarketManager.\n *\n * The Market's credit capacity also depends on how much credit is given to it by the pools that support it.\n *\n * The Market's credit capacity also has a dependency on the external market reported debt as it will respond to that debt (and hence change the credit capacity if it increases or decreases)\n *\n * The credit capacity can go negative if all of the collateral provided by pools is exhausted, and there is market provided collateral available to consume. in this case, the debt is still being\n * appropriately assigned, but the market has a dynamic cap based on deposited collateral types.\n *\n */\n int128 creditCapacityD18;\n /**\n * @dev The total balance that the market had the last time that its debt was distributed.\n *\n * A Market's debt is distributed when the reported debt of its associated external market is rolled into the pools that provide credit capacity to it.\n */\n int128 lastDistributedMarketBalanceD18;\n /**\n * @dev A heap of pools for which the market has not yet hit its maximum credit capacity.\n *\n * The heap is ordered according to this market's max value per share setting in the pools that provide credit capacity to it. See `MarketConfiguration.maxDebtShareValue`.\n *\n * The heap's getMax() and extractMax() functions allow us to retrieve the pool with the lowest `maxDebtShareValue`, since its elements are inserted and prioritized by negating their `maxDebtShareValue`.\n *\n * Lower max values per share are on the top of the heap. I.e. the heap could look like this:\n * . -1\n * / \\\n * / \\\n * -2 \\\n * / \\ -3\n * -4 -5\n *\n * TL;DR: This data structure allows us to easily find the pool with the lowest or \"most vulnerable\" max value per share and process it if its actual value per share goes beyond this limit.\n */\n HeapUtil.Data inRangePools;\n /**\n * @dev A heap of pools for which the market has hit its maximum credit capacity.\n *\n * Used to reconnect pools to the market, when it falls back below its maximum credit capacity.\n *\n * See inRangePools for why a heap is used here.\n */\n HeapUtil.Data outRangePools;\n /**\n * @dev A market's debt distribution connects markets to the debt distribution chain, in this case pools. Pools are actors in the market's debt distribution, where the amount of shares they possess depends on the amount of collateral they provide to the market. The value per share of this distribution depends on the total debt or balance of the market (netIssuance + reportedDebt).\n *\n * The debt distribution chain will move debt from the market into its connected pools.\n *\n * Actors: Pools.\n * Shares: The USD denominated credit capacity that the pool provides to the market.\n * Value per share: Debt per dollar of credit that the associated external market accrues.\n *\n */\n Distribution.Data poolsDebtDistribution;\n /**\n * @dev Additional info needed to remember pools when they are removed from the distribution (or subsequently re-added).\n */\n mapping(uint128 => MarketPoolInfo.Data) pools;\n /**\n * @dev Array of entries of market provided collateral.\n *\n * Markets may obtain additional liquidity, beyond that coming from depositors, by providing their own collateral.\n *\n */\n DepositedCollateral[] depositedCollateral;\n /**\n * @dev The maximum amount of market provided collateral, per type, that this market can deposit.\n */\n mapping(address => uint256) maximumDepositableD18;\n }\n\n /**\n * @dev Data structure that allows the Market to track the amount of market provided collateral, per type.\n */\n struct DepositedCollateral {\n address collateralType;\n uint256 amountD18;\n }\n\n /**\n * @dev Returns the market stored at the specified market id.\n */\n function load(uint128 id) internal pure returns (Data storage market) {\n bytes32 s = keccak256(abi.encode(\"io.synthetix.synthetix.Market\", id));\n assembly {\n market.slot := s\n }\n }\n\n /**\n * @dev Queries the external market contract for the amount of debt it has issued.\n *\n * The reported debt of a market represents the amount of USD that the market would ask the system to mint, if all of its positions were to be immediately closed.\n *\n * The reported debt of a market is collateralized by the assets in the pools which back it.\n *\n * See the `IMarket` interface.\n */\n function getReportedDebt(Data storage self) internal view returns (uint256) {\n return IMarket(self.marketAddress).reportedDebt(self.id);\n }\n\n /**\n * @dev Queries the market for the amount of collateral which should be prevented from withdrawal.\n */\n function getLockedCreditCapacity(Data storage self) internal view returns (uint256) {\n return IMarket(self.marketAddress).locked(self.id);\n }\n\n /**\n * @dev Returns the total debt of the market.\n *\n * A market's total debt represents its debt plus its issuance, and thus represents the total outstanding debt of the market.\n *\n * Note: it also takes into account the deposited collateral value. See note in getDepositedCollateralValue()\n *\n * Example:\n * (1 EUR = 1.11 USD)\n * If an Euro market has received 100 USD to mint 90 EUR, its reported debt is 90 EUR or 100 USD, and its issuance is -100 USD.\n * Thus, its total balance is 100 USD of reported debt minus 100 USD of issuance, which is 0 USD.\n *\n * Additionally, the market's totalDebt might be affected by price fluctuations via reportedDebt, or fees.\n *\n */\n function totalDebt(Data storage self) internal view returns (int256) {\n return\n getReportedDebt(self).toInt() +\n self.netIssuanceD18 -\n getDepositedCollateralValue(self).toInt();\n }\n\n /**\n * @dev Returns the USD value for the total amount of collateral provided by the market itself.\n *\n * Note: This is not credit capacity provided by depositors through pools.\n */\n function getDepositedCollateralValue(Data storage self) internal view returns (uint256) {\n uint256 totalDepositedCollateralValueD18 = 0;\n\n // Sweep all DepositedCollateral entries and aggregate their USD value.\n for (uint256 i = 0; i < self.depositedCollateral.length; i++) {\n DepositedCollateral memory entry = self.depositedCollateral[i];\n CollateralConfiguration.Data storage collateralConfiguration = CollateralConfiguration\n .load(entry.collateralType);\n\n if (entry.amountD18 == 0) {\n continue;\n }\n\n uint256 priceD18 = CollateralConfiguration.getCollateralPrice(collateralConfiguration);\n\n totalDepositedCollateralValueD18 += priceD18.mulDecimal(entry.amountD18);\n }\n\n return totalDepositedCollateralValueD18;\n }\n\n /**\n * @dev Returns the amount of credit capacity that a certain pool provides to the market.\n\n * This credit capacity is obtained by reading the amount of shares that the pool has in the market's debt distribution, which represents the amount of USD denominated credit capacity that the pool has provided to the market.\n */\n function getPoolCreditCapacity(\n Data storage self,\n uint128 poolId\n ) internal view returns (uint256) {\n return self.poolsDebtDistribution.getActorShares(poolId.toBytes32());\n }\n\n /**\n * @dev Given an amount of shares that represent USD credit capacity from a pool, and a maximum value per share, returns the potential contribution to credit capacity that these shares could accrue, if their value per share was to hit the maximum.\n *\n * The resulting value is calculated multiplying the amount of creditCapacity provided by the pool by the delta between the maxValue per share vs current value.\n *\n * This function is used when the Pools are rebalanced to adjust each pool credit capacity based on a change in the amount of shares provided and/or a new maxValue per share\n *\n */\n function getCreditCapacityContribution(\n Data storage self,\n uint256 creditCapacitySharesD18,\n int256 maxShareValueD18\n ) internal view returns (int256 contributionD18) {\n // Determine how much the current value per share deviates from the maximum.\n uint256 deltaValuePerShareD18 = (maxShareValueD18 -\n self.poolsDebtDistribution.getValuePerShare()).toUint();\n\n return deltaValuePerShareD18.mulDecimal(creditCapacitySharesD18).toInt();\n }\n\n /**\n * @dev Returns true if the market's current capacity is below the amount of locked capacity.\n *\n */\n function isCapacityLocked(Data storage self) internal view returns (bool) {\n return self.creditCapacityD18 < getLockedCreditCapacity(self).toInt();\n }\n\n /**\n * @dev Gets any outstanding debt. Do not call this method except in tests\n *\n * Note: This function should only be used in tests!\n */\n // solhint-disable-next-line private-vars-leading-underscore, func-name-mixedcase\n function _testOnly_getOutstandingDebt(\n Data storage self,\n uint128 poolId\n ) internal returns (int256 debtChangeD18) {\n return\n self.pools[poolId].pendingDebtD18.toInt() +\n self.poolsDebtDistribution.accumulateActor(poolId.toBytes32());\n }\n\n /**\n * Returns the number of pools currently active in the market\n *\n * Note: this is test only\n */\n // solhint-disable-next-line private-vars-leading-underscore, func-name-mixedcase\n function _testOnly_inRangePools(Data storage self) internal view returns (uint256) {\n return self.inRangePools.size();\n }\n\n /**\n * Returns the number of pools currently active in the market\n *\n * Note: this is test only\n */\n // solhint-disable-next-line private-vars-leading-underscore, func-name-mixedcase\n function _testOnly_outRangePools(Data storage self) internal view returns (uint256) {\n return self.outRangePools.size();\n }\n\n /**\n * @dev Returns the debt value per share\n */\n function getDebtPerShare(Data storage self) internal view returns (int256 debtPerShareD18) {\n return self.poolsDebtDistribution.getValuePerShare();\n }\n\n /**\n * @dev Wrapper that adjusts a pool's shares in the market's credit capacity, making sure that the market's outstanding debt is first passed on to its connected pools.\n *\n * Called by a pool when it distributes its debt.\n *\n */\n function rebalancePools(\n uint128 marketId,\n uint128 poolId,\n int256 maxDebtShareValueD18, // (in USD)\n uint256 newCreditCapacityD18 // in collateralValue (USD)\n ) internal returns (int256 debtChangeD18) {\n Data storage self = load(marketId);\n\n if (self.marketAddress == address(0)) {\n revert MarketNotFound(marketId);\n }\n\n // Iter avoids griefing - MarketManager can call this with user specified iters and thus clean up a grieved market.\n distributeDebtToPools(self, 9999999999);\n\n return adjustPoolShares(self, poolId, newCreditCapacityD18, maxDebtShareValueD18);\n }\n\n /**\n * @dev Called by pools when they modify the credit capacity provided to the market, as well as the maximum value per share they tolerate for the market.\n *\n * These two settings affect the market in the following ways:\n * - Updates the pool's shares in `poolsDebtDistribution`.\n * - Moves the pool in and out of inRangePools/outRangePools.\n * - Updates the market credit capacity property.\n */\n function adjustPoolShares(\n Data storage self,\n uint128 poolId,\n uint256 newCreditCapacityD18,\n int256 newPoolMaxShareValueD18\n ) internal returns (int256 debtChangeD18) {\n uint256 oldCreditCapacityD18 = getPoolCreditCapacity(self, poolId);\n int256 oldPoolMaxShareValueD18 = -self.inRangePools.getById(poolId).priority;\n\n // Sanity checks\n // require(oldPoolMaxShareValue == 0, \"value is not 0\");\n // require(newPoolMaxShareValue == 0, \"new pool max share value is in fact set\");\n\n self.pools[poolId].creditCapacityAmountD18 = newCreditCapacityD18.to128();\n\n int128 valuePerShareD18 = self.poolsDebtDistribution.getValuePerShare().to128();\n\n if (newCreditCapacityD18 == 0) {\n self.inRangePools.extractById(poolId);\n self.outRangePools.extractById(poolId);\n } else if (newPoolMaxShareValueD18 < valuePerShareD18) {\n // this will ensure calculations below can correctly gauge shares changes\n newCreditCapacityD18 = 0;\n self.inRangePools.extractById(poolId);\n self.outRangePools.insert(poolId, newPoolMaxShareValueD18.to128());\n } else {\n self.inRangePools.insert(poolId, -newPoolMaxShareValueD18.to128());\n self.outRangePools.extractById(poolId);\n }\n\n int256 changedValueD18 = self.poolsDebtDistribution.setActorShares(\n poolId.toBytes32(),\n newCreditCapacityD18\n );\n debtChangeD18 = self.pools[poolId].pendingDebtD18.toInt() + changedValueD18;\n self.pools[poolId].pendingDebtD18 = 0;\n\n // recalculate market capacity\n if (newPoolMaxShareValueD18 > valuePerShareD18) {\n self.creditCapacityD18 += getCreditCapacityContribution(\n self,\n newCreditCapacityD18,\n newPoolMaxShareValueD18\n ).to128();\n }\n\n if (oldPoolMaxShareValueD18 > valuePerShareD18) {\n self.creditCapacityD18 -= getCreditCapacityContribution(\n self,\n oldCreditCapacityD18,\n oldPoolMaxShareValueD18\n ).to128();\n }\n }\n\n /**\n * @dev Moves debt from the market into the pools that connect to it.\n *\n * This function should be called before any of the pools' shares are modified in `poolsDebtDistribution`.\n *\n * Note: The parameter `maxIter` is used as an escape hatch to discourage griefing.\n */\n function distributeDebtToPools(\n Data storage self,\n uint256 maxIter\n ) internal returns (bool fullyDistributed) {\n // Get the current and last distributed market balances.\n // Note: The last distributed balance will be cached within this function's execution.\n int256 targetBalanceD18 = totalDebt(self);\n int256 outstandingBalanceD18 = targetBalanceD18 - self.lastDistributedMarketBalanceD18;\n\n (, bool exhausted) = bumpPools(self, outstandingBalanceD18, maxIter);\n\n if (!exhausted && self.poolsDebtDistribution.totalSharesD18 > 0) {\n // cannot use `outstandingBalance` here because `self.lastDistributedMarketBalance`\n // may have changed after calling the bump functions above\n self.poolsDebtDistribution.distributeValue(\n targetBalanceD18 - self.lastDistributedMarketBalanceD18\n );\n self.lastDistributedMarketBalanceD18 = targetBalanceD18.to128();\n }\n\n return !exhausted;\n }\n\n /**\n * @dev Determine the target valuePerShare of the poolsDebtDistribution, given the value that is yet to be distributed.\n */\n function getTargetValuePerShare(\n Market.Data storage self,\n int256 valueToDistributeD18\n ) internal view returns (int256 targetValuePerShareD18) {\n return\n self.poolsDebtDistribution.getValuePerShare() +\n (\n self.poolsDebtDistribution.totalSharesD18 > 0\n ? valueToDistributeD18.divDecimal(\n self.poolsDebtDistribution.totalSharesD18.toInt()\n ) // solhint-disable-next-line numcast/safe-cast\n : int256(0)\n );\n }\n\n /**\n * @dev Finds pools for which this market's max value per share limit is hit, distributes their debt, and disconnects the market from them.\n *\n * The debt is distributed up to the limit of the max value per share that the pool tolerates on the market.\n */\n function bumpPools(\n Data storage self,\n int256 maxDistributedD18,\n uint256 maxIter\n ) internal returns (int256 actuallyDistributedD18, bool exhausted) {\n if (maxDistributedD18 == 0) {\n return (0, false);\n }\n\n // Determine the direction based on the amount to be distributed.\n int128 k;\n HeapUtil.Data storage fromHeap;\n HeapUtil.Data storage toHeap;\n if (maxDistributedD18 > 0) {\n k = 1;\n fromHeap = self.inRangePools;\n toHeap = self.outRangePools;\n } else {\n k = -1;\n fromHeap = self.outRangePools;\n toHeap = self.inRangePools;\n }\n\n // Note: This loop should rarely execute its main body. When it does, it only executes once for each pool that exceeds the limit since `distributeValue` is not run for most pools. Thus, market users are not hit with any overhead as a result of this.\n uint256 iters;\n for (iters = 0; iters < maxIter; iters++) {\n // Exit if there are no pools that can be moved\n if (fromHeap.size() == 0) {\n break;\n }\n\n // Identify the pool with the lowest maximum value per share.\n HeapUtil.Node memory edgePool = fromHeap.getMax();\n\n // 2 cases where we want to break out of this loop\n if (\n // If there is no pool in range, and we are going down\n (maxDistributedD18 - actuallyDistributedD18 > 0 &&\n self.poolsDebtDistribution.totalSharesD18 == 0) ||\n // If there is a pool in ragne, and the lowest max value per share does not hit the limit, exit\n // Note: `-edgePool.priority` is actually the max value per share limit of the pool\n (self.poolsDebtDistribution.totalSharesD18 > 0 &&\n -edgePool.priority >=\n k * getTargetValuePerShare(self, (maxDistributedD18 - actuallyDistributedD18)))\n ) {\n break;\n }\n\n // The pool has hit its maximum value per share and needs to be removed.\n // Note: No need to update capacity because pool max share value = valuePerShare when this happens.\n togglePool(fromHeap, toHeap);\n\n // Distribute the market's debt to the limit, i.e. for that which exceeds the maximum value per share.\n if (self.poolsDebtDistribution.totalSharesD18 > 0) {\n int256 debtToLimitD18 = self\n .poolsDebtDistribution\n .totalSharesD18\n .toInt()\n .mulDecimal(\n -k * edgePool.priority - self.poolsDebtDistribution.getValuePerShare() // Diff between current value and max value per share.\n );\n self.poolsDebtDistribution.distributeValue(debtToLimitD18);\n\n // Update the global distributed and outstanding balances with the debt that was just distributed.\n actuallyDistributedD18 += debtToLimitD18;\n } else {\n self.poolsDebtDistribution.valuePerShareD27 = (-k * edgePool.priority)\n .to256()\n .upscale(DecimalMath.PRECISION_FACTOR)\n .to128();\n }\n\n // Detach the market from this pool by removing the pool's shares from the market.\n // The pool will remain \"detached\" until the pool manager specifies a new poolsDebtDistribution.\n if (maxDistributedD18 > 0) {\n // the below requires are only for sanity\n require(\n self.poolsDebtDistribution.getActorShares(edgePool.id.toBytes32()) > 0,\n \"no shares before actor removal\"\n );\n\n uint256 newPoolDebtD18 = self\n .poolsDebtDistribution\n .setActorShares(edgePool.id.toBytes32(), 0)\n .toUint();\n self.pools[edgePool.id].pendingDebtD18 += newPoolDebtD18.to128();\n } else {\n require(\n self.poolsDebtDistribution.getActorShares(edgePool.id.toBytes32()) == 0,\n \"actor has shares before add\"\n );\n\n self.poolsDebtDistribution.setActorShares(\n edgePool.id.toBytes32(),\n self.pools[edgePool.id].creditCapacityAmountD18\n );\n }\n }\n\n // Record the accumulated distributed balance.\n self.lastDistributedMarketBalanceD18 += actuallyDistributedD18.to128();\n\n exhausted = iters == maxIter;\n }\n\n /**\n * @dev Moves a pool from one heap into another.\n */\n function togglePool(HeapUtil.Data storage from, HeapUtil.Data storage to) internal {\n HeapUtil.Node memory node = from.extractMax();\n to.insert(node.id, -node.priority);\n }\n}\n" }, "contracts/storage/MarketConfiguration.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Tracks a market's weight within a Pool, and its maximum debt.\n *\n * Each pool has an array of these, with one entry per market managed by the pool.\n *\n * A market's weight determines how much liquidity the pool provides to the market, and how much debt exposure the market gives the pool.\n *\n * Weights are used to calculate percentages by adding all the weights in the pool and dividing the market's weight by the total weights.\n *\n * A market's maximum debt in a pool is indicated with a maximum debt value per share.\n */\nlibrary MarketConfiguration {\n struct Data {\n /**\n * @dev Numeric identifier for the market.\n *\n * Must be unique, and in a list of `MarketConfiguration[]`, must be increasing.\n */\n uint128 marketId;\n /**\n * @dev The ratio of each market's `weight` to the pool's `totalWeights` determines the pro-rata share of the market to the pool's total liquidity.\n */\n uint128 weightD18;\n /**\n * @dev Maximum value per share that a pool will tolerate for this market.\n *\n * If the the limit is met, the markets exceeding debt will be distributed, and it will be disconnected from the pool that no longer provides credit to it.\n *\n * Note: This value will have no effect if the system wide limit is hit first. See `PoolConfiguration.minLiquidityRatioD18`.\n */\n int128 maxDebtShareValueD18;\n }\n}\n" }, "contracts/storage/MarketCreator.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./Market.sol\";\n\n/**\n * @title Encapsulates market creation logic\n */\nlibrary MarketCreator {\n bytes32 private constant _SLOT_MARKET_CREATOR =\n keccak256(abi.encode(\"io.synthetix.synthetix.Markets\"));\n\n struct Data {\n /**\n * @dev Tracks an array of market ids for each external IMarket address.\n */\n mapping(address => uint128[]) marketIdsForAddress;\n /**\n * @dev Keeps track of the last market id created.\n * Used for easily creating new markets.\n */\n uint128 lastCreatedMarketId;\n }\n\n /**\n * @dev Returns the singleton market store of the system.\n */\n function getMarketStore() internal pure returns (Data storage marketStore) {\n bytes32 s = _SLOT_MARKET_CREATOR;\n assembly {\n marketStore.slot := s\n }\n }\n\n /**\n * @dev Given an external contract address representing an `IMarket`, creates a new id for the market, and tracks it internally in the system.\n *\n * The id used to track the market will be automatically assigned by the system according to the last id used.\n *\n * Note: If an external `IMarket` contract tracks several market ids, this function should be called for each market it tracks, resulting in multiple ids for the same address.\n */\n function create(address marketAddress) internal returns (Market.Data storage market) {\n Data storage marketStore = getMarketStore();\n\n uint128 id = marketStore.lastCreatedMarketId;\n id++;\n\n market = Market.load(id);\n\n market.id = id;\n market.marketAddress = marketAddress;\n\n marketStore.lastCreatedMarketId = id;\n\n loadIdsByAddress(marketAddress).push(id);\n }\n\n /**\n * @dev Returns an array of market ids representing the markets linked to the system at a particular external contract address.\n *\n * Note: A contract implementing the `IMarket` interface may represent more than just one market, and thus several market ids could be associated to a single external contract address.\n */\n function loadIdsByAddress(address marketAddress) internal view returns (uint128[] storage ids) {\n return getMarketStore().marketIdsForAddress[marketAddress];\n }\n}\n" }, "contracts/storage/MarketPoolInfo.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Stores information regarding a pool's relationship to a market, such that it can be added or removed from a distribution\n */\nlibrary MarketPoolInfo {\n struct Data {\n /**\n * @dev The credit capacity that this pool is providing to the relevant market. Needed to re-add the pool to the distribution when going back in range.\n */\n uint128 creditCapacityAmountD18;\n /**\n * @dev The amount of debt the pool has which hasn't been passed down the debt distribution chain yet.\n */\n uint128 pendingDebtD18;\n }\n}\n" }, "contracts/storage/OracleManager.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Represents Oracle Manager\n */\nlibrary OracleManager {\n bytes32 private constant _SLOT_ORACLE_MANAGER =\n keccak256(abi.encode(\"io.synthetix.synthetix.OracleManager\"));\n\n struct Data {\n /**\n * @dev The oracle manager address.\n */\n address oracleManagerAddress;\n }\n\n /**\n * @dev Loads the singleton storage info about the oracle manager.\n */\n function load() internal pure returns (Data storage oracleManager) {\n bytes32 s = _SLOT_ORACLE_MANAGER;\n assembly {\n oracleManager.slot := s\n }\n }\n}\n" }, "contracts/storage/Pool.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./Distribution.sol\";\nimport \"./MarketConfiguration.sol\";\nimport \"./Vault.sol\";\nimport \"./Market.sol\";\nimport \"./SystemPoolConfiguration.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/errors/AccessError.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\n/**\n * @title Aggregates collateral from multiple users in order to provide liquidity to a configurable set of markets.\n *\n * The set of markets is configured as an array of MarketConfiguration objects, where the weight of the market can be specified. This weight, and the aggregated total weight of all the configured markets, determines how much collateral from the pool each market has, as well as in what proportion the market passes on debt to the pool and thus to all its users.\n *\n * The pool tracks the collateral provided by users using an array of Vaults objects, for which there will be one per collateral type. Each vault tracks how much collateral each user has delegated to this pool, how much debt the user has because of minting USD, as well as how much corresponding debt the pool has passed on to the user.\n */\nlibrary Pool {\n using CollateralConfiguration for CollateralConfiguration.Data;\n using Market for Market.Data;\n using Vault for Vault.Data;\n using Distribution for Distribution.Data;\n using DecimalMath for uint256;\n using DecimalMath for int256;\n using DecimalMath for int128;\n using SafeCastAddress for address;\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n\n /**\n * @dev Thrown when the specified pool is not found.\n */\n error PoolNotFound(uint128 poolId);\n\n /**\n * @dev Thrown when attempting to create a pool that already exists.\n */\n error PoolAlreadyExists(uint128 poolId);\n\n struct Data {\n /**\n * @dev Numeric identifier for the pool. Must be unique.\n * @dev A pool with id zero exists! (See Pool.loadExisting()). Users can delegate to this pool to be able to mint USD without being exposed to fluctuating debt.\n */\n uint128 id;\n /**\n * @dev Text identifier for the pool.\n *\n * Not required to be unique.\n */\n string name;\n /**\n * @dev Creator of the pool, which has configuration access rights for the pool.\n *\n * See onlyPoolOwner.\n */\n address owner;\n /**\n * @dev Allows the current pool owner to nominate a new owner, and thus transfer pool configuration credentials.\n */\n address nominatedOwner;\n /**\n * @dev Sum of all market weights.\n *\n * Market weights are tracked in `MarketConfiguration.weight`, one for each market. The ratio of each market's `weight` to the pool's `totalWeights` determines the pro-rata share of the market to the pool's total liquidity.\n *\n * Reciprocally, this pro-rata share also determines how much the pool is exposed to each market's debt.\n */\n uint128 totalWeightsD18;\n /**\n * @dev Accumulated cache value of all vault collateral debts\n */\n int128 totalVaultDebtsD18;\n /**\n * @dev Array of markets connected to this pool, and their configurations. I.e. weight, etc.\n *\n * See totalWeights.\n */\n MarketConfiguration.Data[] marketConfigurations;\n /**\n * @dev A pool's debt distribution connects pools to the debt distribution chain, i.e. vaults and markets. Vaults are actors in the pool's debt distribution, where the amount of shares they possess depends on the amount of collateral each vault delegates to the pool.\n *\n * The debt distribution chain will move debt from markets into this pools, and then from pools to vaults.\n *\n * Actors: Vaults.\n * Shares: USD value, proportional to the amount of collateral that the vault delegates to the pool.\n * Value per share: Debt per dollar of collateral. Depends on aggregated debt of connected markets.\n *\n */\n Distribution.Data vaultsDebtDistribution;\n /**\n * @dev Reference to all the vaults that provide liquidity to this pool.\n *\n * Each collateral type will have its own vault, specific to this pool. I.e. if two pools both use SNX collateral, each will have its own SNX vault.\n *\n * Vaults track user collateral and debt using a debt distribution, which is connected to the debt distribution chain.\n */\n mapping(address => Vault.Data) vaults;\n }\n\n /**\n * @dev Returns the pool stored at the specified pool id.\n */\n function load(uint128 id) internal pure returns (Data storage pool) {\n bytes32 s = keccak256(abi.encode(\"io.synthetix.synthetix.Pool\", id));\n assembly {\n pool.slot := s\n }\n }\n\n /**\n * @dev Creates a pool for the given pool id, and assigns the caller as its owner.\n *\n * Reverts if the specified pool already exists.\n */\n function create(uint128 id, address owner) internal returns (Pool.Data storage pool) {\n if (id == 0 || load(id).id == id) {\n revert PoolAlreadyExists(id);\n }\n\n pool = load(id);\n\n pool.id = id;\n pool.owner = owner;\n }\n\n /**\n * @dev Ticker function that updates the debt distribution chain downwards, from markets into the pool, according to each market's weight.\n *\n * It updates the chain by performing these actions:\n * - Splits the pool's total liquidity of the pool into each market, pro-rata. The amount of shares that the pool has on each market depends on how much liquidity the pool provides to the market.\n * - Accumulates the change in debt value from each market into the pools own vault debt distribution's value per share.\n */\n function distributeDebtToVaults(Data storage self) internal {\n uint256 totalWeightsD18 = self.totalWeightsD18;\n\n if (totalWeightsD18 == 0) {\n return; // Nothing to rebalance.\n }\n\n // Read from storage once, before entering the loop below.\n // These values should not change while iterating through each market.\n uint256 totalCreditCapacityD18 = self.vaultsDebtDistribution.totalSharesD18;\n int128 debtPerShareD18 = totalCreditCapacityD18 > 0 // solhint-disable-next-line numcast/safe-cast\n ? int(self.totalVaultDebtsD18).divDecimal(totalCreditCapacityD18.toInt()).to128() // solhint-disable-next-line numcast/safe-cast\n : int128(0);\n\n int256 cumulativeDebtChangeD18 = 0;\n\n uint256 minLiquidityRatioD18 = SystemPoolConfiguration.load().minLiquidityRatioD18;\n\n // Loop through the pool's markets, applying market weights, and tracking how this changes the amount of debt that this pool is responsible for.\n // This debt extracted from markets is then applied to the pool's vault debt distribution, which thus exposes debt to the pool's vaults.\n for (uint256 i = 0; i < self.marketConfigurations.length; i++) {\n MarketConfiguration.Data storage marketConfiguration = self.marketConfigurations[i];\n\n uint256 weightD18 = marketConfiguration.weightD18;\n\n // Calculate each market's pro-rata USD liquidity.\n // Note: the factor `(weight / totalWeights)` is not deduped in the operations below to maintain numeric precision.\n\n uint256 marketCreditCapacityD18 = (totalCreditCapacityD18 * weightD18) /\n totalWeightsD18;\n\n Market.Data storage marketData = Market.load(marketConfiguration.marketId);\n\n // Contain the pool imposed market's maximum debt share value.\n // Imposed by system.\n int256 effectiveMaxShareValueD18 = getSystemMaxValuePerShare(\n marketData.id,\n minLiquidityRatioD18,\n debtPerShareD18\n );\n // Imposed by pool.\n int256 configuredMaxShareValueD18 = marketConfiguration.maxDebtShareValueD18;\n effectiveMaxShareValueD18 = effectiveMaxShareValueD18 < configuredMaxShareValueD18\n ? effectiveMaxShareValueD18\n : configuredMaxShareValueD18;\n\n // Update each market's corresponding credit capacity.\n // The returned value represents how much the market's debt changed after changing the shares of this pool actor, which is aggregated to later be passed on the pools debt distribution.\n cumulativeDebtChangeD18 += Market.rebalancePools(\n marketConfiguration.marketId,\n self.id,\n effectiveMaxShareValueD18,\n marketCreditCapacityD18\n );\n }\n\n // Passes on the accumulated debt changes from the markets, into the pool, so that vaults can later access this debt.\n self.vaultsDebtDistribution.distributeValue(cumulativeDebtChangeD18);\n }\n\n /**\n * @dev Determines the resulting maximum value per share for a market, according to a system-wide minimum liquidity ratio. This prevents markets from assigning more debt to pools than they have collateral to cover.\n *\n * Note: There is a market-wide fail safe for each market at `MarketConfiguration.maxDebtShareValue`. The lower of the two values should be used.\n *\n * See `SystemPoolConfiguration.minLiquidityRatio`.\n */\n function getSystemMaxValuePerShare(\n uint128 marketId,\n uint256 minLiquidityRatioD18,\n int256 debtPerShareD18\n ) internal view returns (int256) {\n // Retrieve the current value per share of the market.\n Market.Data storage marketData = Market.load(marketId);\n int256 valuePerShareD18 = marketData.poolsDebtDistribution.getValuePerShare();\n\n // Calculate the margin of debt that the market would incur if it hit the system wide limit.\n uint256 marginD18 = minLiquidityRatioD18 == 0\n ? DecimalMath.UNIT\n : DecimalMath.UNIT.divDecimal(minLiquidityRatioD18);\n\n // The resulting maximum value per share is the distribution's value per share,\n // plus the margin to hit the limit, minus the current debt per share.\n return valuePerShareD18 + marginD18.toInt() - debtPerShareD18;\n }\n\n /**\n * @dev Reverts if the pool does not exist with appropriate error. Otherwise, returns the pool.\n */\n function loadExisting(uint128 id) internal view returns (Data storage) {\n Data storage p = load(id);\n if (id != 0 && p.id != id) {\n revert PoolNotFound(id);\n }\n\n return p;\n }\n\n /**\n * @dev Returns true if the pool is exposed to the specified market.\n */\n function hasMarket(Data storage self, uint128 marketId) internal view returns (bool) {\n for (uint256 i = 0; i < self.marketConfigurations.length; i++) {\n if (self.marketConfigurations[i].marketId == marketId) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * @dev Ticker function that updates the debt distribution chain for a specific collateral type downwards, from the pool into the corresponding the vault, according to changes in the collateral's price.\n *\n * It updates the chain by performing these actions:\n * - Collects the latest price of the corresponding collateral and updates the vault's liquidity.\n * - Updates the vaults shares in the pool's debt distribution, according to the collateral provided by the vault.\n * - Updates the value per share of the vault's debt distribution.\n */\n function recalculateVaultCollateral(\n Data storage self,\n address collateralType\n ) internal returns (uint256 collateralPriceD18) {\n // Update each market's pro-rata liquidity and collect accumulated debt into the pool's debt distribution.\n distributeDebtToVaults(self);\n\n // Transfer the debt change from the pool into the vault.\n bytes32 actorId = collateralType.toBytes32();\n self.vaults[collateralType].distributeDebtToAccounts(\n self.vaultsDebtDistribution.accumulateActor(actorId)\n );\n\n // Get the latest collateral price.\n collateralPriceD18 = CollateralConfiguration.load(collateralType).getCollateralPrice();\n\n // Changes in price update the corresponding vault's total collateral value as well as its liquidity (collateral - debt).\n (uint256 usdWeightD18, , int256 deltaDebtD18) = self\n .vaults[collateralType]\n .updateCreditCapacity(collateralPriceD18);\n\n // Update the vault's shares in the pool's debt distribution, according to the value of its collateral.\n self.vaultsDebtDistribution.setActorShares(actorId, usdWeightD18);\n\n // Accumulate the change in total liquidity, from the vault, into the pool.\n self.totalVaultDebtsD18 = self.totalVaultDebtsD18 + deltaDebtD18.to128();\n\n // Distribute debt again because the market credit capacity may have changed, so we should ensure the vaults have the most up to date capacities\n distributeDebtToVaults(self);\n }\n\n /**\n * @dev Updates the debt distribution chain for this pool, and consolidates the given account's debt.\n */\n function updateAccountDebt(\n Data storage self,\n address collateralType,\n uint128 accountId\n ) internal returns (int256 debtD18) {\n recalculateVaultCollateral(self, collateralType);\n\n return self.vaults[collateralType].consolidateAccountDebt(accountId);\n }\n\n /**\n * @dev Clears all vault data for the specified collateral type.\n */\n function resetVault(Data storage self, address collateralType) internal {\n // Creates a new epoch in the vault, effectively zeroing out all values.\n self.vaults[collateralType].reset();\n\n // Ensure that the vault's values update the debt distribution chain.\n recalculateVaultCollateral(self, collateralType);\n }\n\n /**\n * @dev Calculates the collateralization ratio of the vault that tracks the given collateral type.\n *\n * The c-ratio is the vault's share of the total debt of the pool, divided by the collateral it delegates to the pool.\n *\n * Note: This is not a view function. It updates the debt distribution chain before performing any calculations.\n */\n function currentVaultCollateralRatio(\n Data storage self,\n address collateralType\n ) internal returns (uint256) {\n int256 vaultDebtD18 = currentVaultDebt(self, collateralType);\n (, uint256 collateralValueD18) = currentVaultCollateral(self, collateralType);\n\n return vaultDebtD18 > 0 ? collateralValueD18.divDecimal(vaultDebtD18.toUint()) : 0;\n }\n\n /**\n * @dev Finds a connected market whose credit capacity has reached its locked limit.\n *\n * Note: Returns market zero (null market) if none is found.\n */\n function findMarketWithCapacityLocked(\n Data storage self\n ) internal view returns (Market.Data storage lockedMarket) {\n for (uint256 i = 0; i < self.marketConfigurations.length; i++) {\n Market.Data storage market = Market.load(self.marketConfigurations[i].marketId);\n\n if (market.isCapacityLocked()) {\n return market;\n }\n }\n\n // Market zero = null market.\n return Market.load(0);\n }\n\n /**\n * @dev Returns the debt of the vault that tracks the given collateral type.\n *\n * The vault's debt is the vault's share of the total debt of the pool, or its share of the total debt of the markets connected to the pool. The size of this share depends on how much collateral the pool provides to the pool.\n *\n * Note: This is not a view function. It updates the debt distribution chain before performing any calculations.\n */\n function currentVaultDebt(Data storage self, address collateralType) internal returns (int256) {\n recalculateVaultCollateral(self, collateralType);\n\n return self.vaults[collateralType].currentDebt();\n }\n\n /**\n * @dev Returns the total amount and value of the specified collateral delegated to this pool.\n */\n function currentVaultCollateral(\n Data storage self,\n address collateralType\n ) internal view returns (uint256 collateralAmountD18, uint256 collateralValueD18) {\n uint256 collateralPriceD18 = CollateralConfiguration\n .load(collateralType)\n .getCollateralPrice();\n\n collateralAmountD18 = self.vaults[collateralType].currentCollateral();\n collateralValueD18 = collateralPriceD18.mulDecimal(collateralAmountD18);\n }\n\n /**\n * @dev Returns the amount and value of collateral that the specified account has delegated to this pool.\n */\n function currentAccountCollateral(\n Data storage self,\n address collateralType,\n uint128 accountId\n ) internal view returns (uint256 collateralAmountD18, uint256 collateralValueD18) {\n uint256 collateralPriceD18 = CollateralConfiguration\n .load(collateralType)\n .getCollateralPrice();\n\n collateralAmountD18 = self.vaults[collateralType].currentAccountCollateral(accountId);\n collateralValueD18 = collateralPriceD18.mulDecimal(collateralAmountD18);\n }\n\n /**\n * @dev Returns the specified account's collateralization ratio (collateral / debt).\n * @dev If the account's debt is negative or zero, returns an \"infinite\" c-ratio.\n */\n function currentAccountCollateralRatio(\n Data storage self,\n address collateralType,\n uint128 accountId\n ) internal returns (uint256) {\n int256 positionDebtD18 = updateAccountDebt(self, collateralType, accountId);\n if (positionDebtD18 <= 0) {\n return type(uint256).max;\n }\n\n (, uint256 positionCollateralValueD18) = currentAccountCollateral(\n self,\n collateralType,\n accountId\n );\n\n return positionCollateralValueD18.divDecimal(positionDebtD18.toUint());\n }\n\n /**\n * @dev Reverts if the caller is not the owner of the specified pool.\n */\n function onlyPoolOwner(uint128 poolId, address caller) internal view {\n if (Pool.load(poolId).owner != caller) {\n revert AccessError.Unauthorized(caller);\n }\n }\n}\n" }, "contracts/storage/RewardDistribution.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/DecimalMath.sol\";\nimport \"@synthetixio/core-contracts/contracts/errors/ParameterError.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\nimport \"../interfaces/external/IRewardDistributor.sol\";\n\nimport \"./Distribution.sol\";\nimport \"./RewardDistributionClaimStatus.sol\";\n\n/**\n * @title Used by vaults to track rewards for its participants. There will be one of these for each pool, collateral type, and distributor combination.\n */\nlibrary RewardDistribution {\n using DecimalMath for int256;\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n using SafeCastU64 for uint64;\n using SafeCastU32 for uint32;\n using SafeCastI32 for int32;\n\n struct Data {\n /**\n * @dev The 3rd party smart contract which holds/mints tokens for distributing rewards to vault participants.\n */\n IRewardDistributor distributor;\n /**\n * @dev Available slot.\n */\n uint128 __slotAvailableForFutureUse;\n /**\n * @dev The value of the rewards in this entry.\n */\n uint128 rewardPerShareD18;\n /**\n * @dev The status for each actor, regarding this distribution's entry.\n */\n mapping(uint256 => RewardDistributionClaimStatus.Data) claimStatus;\n /**\n * @dev Value to be distributed as rewards in a scheduled form.\n */\n int128 scheduledValueD18;\n /**\n * @dev Date at which the entry's rewards will begin to be claimable.\n *\n * Note: Set to <= block.timestamp to distribute immediately to currently participating users.\n */\n uint64 start;\n /**\n * @dev Time span after the start date, in which the whole of the entry's rewards will become claimable.\n */\n uint32 duration;\n /**\n * @dev Date on which this distribution entry was last updated.\n */\n uint32 lastUpdate;\n }\n\n /**\n * @dev Distributes rewards into a new rewards distribution entry.\n *\n * Note: this function allows for more special cases such as distributing at a future date or distributing over time.\n * If you want to apply the distribution to the pool, call `distribute` with the return value. Otherwise, you can\n * record this independently as well.\n */\n function distribute(\n Data storage self,\n Distribution.Data storage dist,\n int256 amountD18,\n uint64 start,\n uint32 duration\n ) internal returns (int256 diffD18) {\n uint256 totalSharesD18 = dist.totalSharesD18;\n\n if (totalSharesD18 == 0) {\n revert ParameterError.InvalidParameter(\n \"amount\",\n \"can't distribute to empty distribution\"\n );\n }\n\n uint256 curTime = block.timestamp;\n\n // Unlocks the entry's distributed amount into its value per share.\n diffD18 += updateEntry(self, totalSharesD18);\n\n // If the current time is past the end of the entry's duration,\n // update any rewards which may have accrued since last run.\n // (instant distribution--immediately disperse amount).\n if (start + duration <= curTime) {\n diffD18 += amountD18.divDecimal(totalSharesD18.toInt());\n\n self.lastUpdate = 0;\n self.start = 0;\n self.duration = 0;\n self.scheduledValueD18 = 0;\n // Else, schedule the amount to distribute.\n } else {\n self.scheduledValueD18 = amountD18.to128();\n\n self.start = start;\n self.duration = duration;\n\n // The amount is actually the amount distributed already *plus* whatever has been specified now.\n self.lastUpdate = 0;\n\n diffD18 += updateEntry(self, totalSharesD18);\n }\n }\n\n /**\n * @dev Updates the total shares of a reward distribution entry, and releases its unlocked value into its value per share, depending on the time elapsed since the start of the distribution's entry.\n *\n * Note: call every time before `totalShares` changes.\n */\n function updateEntry(\n Data storage self,\n uint256 totalSharesAmountD18\n ) internal returns (int256) {\n // Cannot process distributed rewards if a pool is empty or if it has no rewards.\n if (self.scheduledValueD18 == 0 || totalSharesAmountD18 == 0) {\n return 0;\n }\n\n uint256 curTime = block.timestamp;\n\n int256 valuePerShareChangeD18 = 0;\n\n // Cannot update an entry whose start date has not being reached.\n if (curTime < self.start) {\n return 0;\n }\n\n // If the entry's duration is zero and the its last update is zero,\n // consider the entry to be an instant distribution.\n if (self.duration == 0 && self.lastUpdate < self.start) {\n // Simply update the value per share to the total value divided by the total shares.\n valuePerShareChangeD18 = self.scheduledValueD18.to256().divDecimal(\n totalSharesAmountD18.toInt()\n );\n // Else, if the last update was before the end of the duration.\n } else if (self.lastUpdate < self.start + self.duration) {\n // Determine how much was previously distributed.\n // If the last update is zero, then nothing was distributed,\n // otherwise the amount is proportional to the time elapsed since the start.\n int256 lastUpdateDistributedD18 = self.lastUpdate < self.start\n ? SafeCastI128.zero()\n : (self.scheduledValueD18 * (self.lastUpdate - self.start).toInt()) /\n self.duration.toInt();\n\n // If the current time is beyond the duration, then consider all scheduled value to be distributed.\n // Else, the amount distributed is proportional to the elapsed time.\n int256 curUpdateDistributedD18 = self.scheduledValueD18;\n if (curTime < self.start + self.duration) {\n // Note: Not using an intermediate time ratio variable\n // in the following calculation to maintain precision.\n curUpdateDistributedD18 =\n (curUpdateDistributedD18 * (curTime - self.start).toInt()) /\n self.duration.toInt();\n }\n\n // The final value per share change is the difference between what is to be distributed and what was distributed.\n valuePerShareChangeD18 = (curUpdateDistributedD18 - lastUpdateDistributedD18)\n .divDecimal(totalSharesAmountD18.toInt());\n }\n\n self.lastUpdate = curTime.to32();\n\n return valuePerShareChangeD18;\n }\n}\n" }, "contracts/storage/RewardDistributionClaimStatus.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\n/**\n * @title Tracks information per actor within a RewardDistribution.\n */\nlibrary RewardDistributionClaimStatus {\n struct Data {\n /**\n * @dev The last known reward per share for this actor.\n */\n uint128 lastRewardPerShareD18;\n /**\n * @dev The amount of rewards pending to be claimed by this actor.\n */\n uint128 pendingSendD18;\n }\n}\n" }, "contracts/storage/ScalableMapping.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/DecimalMath.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\n/**\n * @title Data structure that wraps a mapping with a scalar multiplier.\n *\n * If you wanted to modify all the values in a mapping by the same amount, you would normally have to loop through each entry in the mapping. This object allows you to modify all of them at once, by simply modifying the scalar multiplier.\n *\n * I.e. a regular mapping represents values like this:\n * value = mapping[id]\n *\n * And a scalable mapping represents values like this:\n * value = mapping[id] * scalar\n *\n * This reduces the number of computations needed for modifying the balances of N users from O(n) to O(1).\n\n * Note: Notice how users are tracked by a generic bytes32 id instead of an address. This allows the actors of the mapping not just to be addresses. They can be anything, for example a pool id, an account id, etc.\n *\n * *********************\n * Conceptual Examples\n * *********************\n *\n * 1) Socialization of collateral during a liquidation.\n *\n * Scalable mappings are very useful for \"socialization\" of collateral, that is, the re-distribution of collateral when an account is liquidated. Suppose 1000 ETH are liquidated, and would need to be distributed amongst 1000 depositors. With a regular mapping, every depositor's balance would have to be modified in a loop that iterates through every single one of them. With a scalable mapping, the scalar would simply need to be incremented so that the total value of the mapping increases by 1000 ETH.\n *\n * 2) Socialization of debt during a liquidation.\n *\n * Similar to the socialization of collateral during a liquidation, the debt of the position that is being liquidated can be re-allocated using a scalable mapping with a single action. Supposing a scalable mapping tracks each user's debt in the system, and that 1000 sUSD has to be distributed amongst 1000 depositors, the debt data structure's scalar would simply need to be incremented so that the total value or debt of the distribution increments by 1000 sUSD.\n *\n */\nlibrary ScalableMapping {\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n using DecimalMath for int256;\n using DecimalMath for uint256;\n\n /**\n * @dev Thrown when attempting to scale a mapping with an amount that is lower than its resolution.\n */\n error InsufficientMappedAmount();\n\n /**\n * @dev Thrown when attempting to scale a mapping with no shares.\n */\n error CannotScaleEmptyMapping();\n\n struct Data {\n uint128 totalSharesD18;\n int128 scaleModifierD27;\n mapping(bytes32 => uint256) sharesD18;\n }\n\n /**\n * @dev Inflates or deflates the total value of the distribution by the given value.\n * @dev The incoming value is split per share, and used as a delta that is *added* to the existing scale modifier. The resulting scale modifier must be in the range [-1, type(int128).max).\n */\n function scale(Data storage self, int256 valueD18) internal {\n if (valueD18 == 0) {\n return;\n }\n\n uint256 totalSharesD18 = self.totalSharesD18;\n if (totalSharesD18 == 0) {\n revert CannotScaleEmptyMapping();\n }\n\n int256 valueD45 = valueD18 * DecimalMath.UNIT_PRECISE_INT;\n int256 deltaScaleModifierD27 = valueD45 / totalSharesD18.toInt();\n\n self.scaleModifierD27 += deltaScaleModifierD27.to128();\n\n if (self.scaleModifierD27 < -DecimalMath.UNIT_PRECISE_INT) {\n revert InsufficientMappedAmount();\n }\n }\n\n /**\n * @dev Updates an actor's individual value in the distribution to the specified amount.\n *\n * The change in value is manifested in the distribution by changing the actor's number of shares in it, and thus the distribution's total number of shares.\n *\n * Returns the resulting amount of shares that the actor has after this change in value.\n */\n function set(\n Data storage self,\n bytes32 actorId,\n uint256 newActorValueD18\n ) internal returns (uint256 resultingSharesD18) {\n // Represent the actor's change in value by changing the actor's number of shares,\n // and keeping the distribution's scaleModifier constant.\n\n resultingSharesD18 = getSharesForAmount(self, newActorValueD18);\n\n // Modify the total shares with the actor's change in shares.\n self.totalSharesD18 = (self.totalSharesD18 + resultingSharesD18 - self.sharesD18[actorId])\n .to128();\n\n self.sharesD18[actorId] = resultingSharesD18.to128();\n }\n\n /**\n * @dev Returns the value owned by the actor in the distribution.\n *\n * i.e. actor.shares * scaleModifier\n */\n function get(Data storage self, bytes32 actorId) internal view returns (uint256 valueD18) {\n uint256 totalSharesD18 = self.totalSharesD18;\n if (totalSharesD18 == 0) {\n return 0;\n }\n\n return (self.sharesD18[actorId] * totalAmount(self)) / totalSharesD18;\n }\n\n /**\n * @dev Returns the total value held in the distribution.\n *\n * i.e. totalShares * scaleModifier\n */\n function totalAmount(Data storage self) internal view returns (uint256 valueD18) {\n return\n ((self.scaleModifierD27 + DecimalMath.UNIT_PRECISE_INT).toUint() *\n self.totalSharesD18) / DecimalMath.UNIT_PRECISE;\n }\n\n function getSharesForAmount(\n Data storage self,\n uint256 amountD18\n ) internal view returns (uint256 sharesD18) {\n sharesD18 =\n (amountD18 * DecimalMath.UNIT_PRECISE) /\n (self.scaleModifierD27 + DecimalMath.UNIT_PRECISE_INT128).toUint();\n }\n}\n" }, "contracts/storage/SystemPoolConfiguration.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"@synthetixio/core-contracts/contracts/utils/SetUtil.sol\";\n\n/**\n * @title System wide configuration for pools.\n */\nlibrary SystemPoolConfiguration {\n bytes32 private constant _SLOT_SYSTEM_POOL_CONFIGURATION =\n keccak256(abi.encode(\"io.synthetix.synthetix.SystemPoolConfiguration\"));\n\n struct Data {\n /**\n * @dev Owner specified system-wide limiting factor that prevents markets from minting too much debt, similar to the issuance ratio to a collateral type.\n *\n * Note: If zero, then this value defaults to 100%.\n */\n uint256 minLiquidityRatioD18;\n uint128 __reservedForFutureUse;\n /**\n * @dev Id of the main pool set by the system owner.\n */\n uint128 preferredPool;\n /**\n * @dev List of pools approved by the system owner.\n */\n SetUtil.UintSet approvedPools;\n }\n\n /**\n * @dev Returns the configuration singleton.\n */\n function load() internal pure returns (Data storage systemPoolConfiguration) {\n bytes32 s = _SLOT_SYSTEM_POOL_CONFIGURATION;\n assembly {\n systemPoolConfiguration.slot := s\n }\n }\n}\n" }, "contracts/storage/Vault.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./VaultEpoch.sol\";\nimport \"./RewardDistribution.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/utils/SetUtil.sol\";\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\n/**\n * @title Tracks collateral and debt distributions in a pool, for a specific collateral type.\n *\n * I.e. if a pool supports SNX and ETH collaterals, it will have an SNX Vault, and an ETH Vault.\n *\n * The Vault data structure is itself split into VaultEpoch sub-structures. This facilitates liquidations,\n * so that whenever one occurs, a clean state of all data is achieved by simply incrementing the epoch index.\n *\n * It is recommended to understand VaultEpoch before understanding this object.\n */\nlibrary Vault {\n using VaultEpoch for VaultEpoch.Data;\n using Distribution for Distribution.Data;\n using RewardDistribution for RewardDistribution.Data;\n using ScalableMapping for ScalableMapping.Data;\n using DecimalMath for uint256;\n using DecimalMath for int128;\n using DecimalMath for int256;\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n using SetUtil for SetUtil.Bytes32Set;\n\n /**\n * @dev Thrown when a non-existent reward distributor is referenced\n */\n error RewardDistributorNotFound();\n\n struct Data {\n /**\n * @dev The vault's current epoch number.\n *\n * Vault data is divided into epochs. An epoch changes when an entire vault is liquidated.\n */\n uint256 epoch;\n /**\n * @dev Unused property, maintained for backwards compatibility in storage layout.\n */\n // solhint-disable-next-line private-vars-leading-underscore\n bytes32 __slotAvailableForFutureUse;\n /**\n * @dev The previous debt of the vault, when `updateCreditCapacity` was last called by the Pool.\n */\n int128 prevTotalDebtD18;\n /**\n * @dev Vault data for all the liquidation cycles divided into epochs.\n */\n mapping(uint256 => VaultEpoch.Data) epochData;\n /**\n * @dev Tracks available rewards, per user, for this vault.\n */\n mapping(bytes32 => RewardDistribution.Data) rewards;\n /**\n * @dev Tracks reward ids, for this vault.\n */\n SetUtil.Bytes32Set rewardIds;\n }\n\n /**\n * @dev Return's the VaultEpoch data for the current epoch.\n */\n function currentEpoch(Data storage self) internal view returns (VaultEpoch.Data storage) {\n return self.epochData[self.epoch];\n }\n\n /**\n * @dev Updates the vault's credit capacity as the value of its collateral minus its debt.\n *\n * Called as a ticker when users interact with pools, allowing pools to set\n * vaults' credit capacity shares within them.\n *\n * Returns the amount of collateral that this vault is providing in net USD terms.\n */\n function updateCreditCapacity(\n Data storage self,\n uint256 collateralPriceD18\n ) internal returns (uint256 usdWeightD18, int256 totalDebtD18, int256 deltaDebtD18) {\n VaultEpoch.Data storage epochData = currentEpoch(self);\n\n usdWeightD18 = (epochData.collateralAmounts.totalAmount()).mulDecimal(collateralPriceD18);\n\n totalDebtD18 = epochData.totalDebt();\n\n deltaDebtD18 = totalDebtD18 - self.prevTotalDebtD18;\n\n self.prevTotalDebtD18 = totalDebtD18.to128();\n }\n\n /**\n * @dev Updated the value per share of the current epoch's incoming debt distribution.\n */\n function distributeDebtToAccounts(Data storage self, int256 debtChangeD18) internal {\n currentEpoch(self).distributeDebtToAccounts(debtChangeD18);\n }\n\n /**\n * @dev Consolidates an accounts debt.\n */\n function consolidateAccountDebt(\n Data storage self,\n uint128 accountId\n ) internal returns (int256) {\n return currentEpoch(self).consolidateAccountDebt(accountId);\n }\n\n /**\n * @dev Traverses available rewards for this vault, and updates an accounts\n * claim on them according to the amount of debt shares they have.\n */\n function updateRewards(\n Data storage self,\n uint128 accountId\n ) internal returns (uint256[] memory, address[] memory) {\n uint256[] memory rewards = new uint256[](self.rewardIds.length());\n address[] memory distributors = new address[](self.rewardIds.length());\n\n uint256 numRewards = self.rewardIds.length();\n for (uint256 i = 0; i < numRewards; i++) {\n RewardDistribution.Data storage dist = self.rewards[self.rewardIds.valueAt(i + 1)];\n\n if (address(dist.distributor) == address(0)) {\n continue;\n }\n\n rewards[i] = updateReward(self, accountId, self.rewardIds.valueAt(i + 1));\n distributors[i] = address(dist.distributor);\n }\n\n return (rewards, distributors);\n }\n\n /**\n * @dev Traverses available rewards for this vault and the reward id, and updates an accounts\n * claim on them according to the amount of debt shares they have.\n */\n function updateReward(\n Data storage self,\n uint128 accountId,\n bytes32 rewardId\n ) internal returns (uint256) {\n uint256 totalSharesD18 = currentEpoch(self).accountsDebtDistribution.totalSharesD18;\n uint256 actorSharesD18 = currentEpoch(self).accountsDebtDistribution.getActorShares(\n accountId.toBytes32()\n );\n\n RewardDistribution.Data storage dist = self.rewards[rewardId];\n\n if (address(dist.distributor) == address(0)) {\n revert RewardDistributorNotFound();\n }\n\n dist.rewardPerShareD18 += dist.updateEntry(totalSharesD18).toUint().to128();\n\n dist.claimStatus[accountId].pendingSendD18 += actorSharesD18\n .mulDecimal(dist.rewardPerShareD18 - dist.claimStatus[accountId].lastRewardPerShareD18)\n .to128();\n\n dist.claimStatus[accountId].lastRewardPerShareD18 = dist.rewardPerShareD18;\n\n return dist.claimStatus[accountId].pendingSendD18;\n }\n\n /**\n * @dev Increments the current epoch index, effectively producing a\n * completely blank new VaultEpoch data structure in the vault.\n */\n function reset(Data storage self) internal {\n self.epoch++;\n }\n\n /**\n * @dev Returns the vault's combined debt (consolidated and unconsolidated),\n * for the current epoch.\n */\n function currentDebt(Data storage self) internal view returns (int256) {\n return currentEpoch(self).totalDebt();\n }\n\n /**\n * @dev Returns the total value in the Vault's collateral distribution, for the current epoch.\n */\n function currentCollateral(Data storage self) internal view returns (uint256) {\n return currentEpoch(self).collateralAmounts.totalAmount();\n }\n\n /**\n * @dev Returns an account's collateral value in this vault's current epoch.\n */\n function currentAccountCollateral(\n Data storage self,\n uint128 accountId\n ) internal view returns (uint256) {\n return currentEpoch(self).getAccountCollateral(accountId);\n }\n}\n" }, "contracts/storage/VaultEpoch.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.11 <0.9.0;\n\nimport \"./Distribution.sol\";\nimport \"./ScalableMapping.sol\";\n\nimport \"@synthetixio/core-contracts/contracts/utils/SafeCast.sol\";\n\n/**\n * @title Tracks collateral and debt distributions in a pool, for a specific collateral type, in a given epoch.\n *\n * Collateral is tracked with a distribution as opposed to a regular mapping because liquidations cause collateral to be socialized. If collateral was tracked using a regular mapping, such socialization would be difficult and require looping through individual balances, or some other sort of complex and expensive mechanism. Distributions make socialization easy.\n *\n * Debt is also tracked in a distribution for the same reason, but it is additionally split in two distributions: incoming and consolidated debt.\n *\n * Incoming debt is modified when a liquidations occurs.\n * Consolidated debt is updated when users interact with the system.\n */\nlibrary VaultEpoch {\n using Distribution for Distribution.Data;\n using DecimalMath for uint256;\n using SafeCastU128 for uint128;\n using SafeCastU256 for uint256;\n using SafeCastI128 for int128;\n using SafeCastI256 for int256;\n using ScalableMapping for ScalableMapping.Data;\n\n struct Data {\n /**\n * @dev Amount of debt in this Vault that is yet to be consolidated.\n *\n * E.g. when a given amount of debt is socialized during a liquidation, but it yet hasn't been rolled into\n * the consolidated debt distribution.\n */\n int128 unconsolidatedDebtD18;\n /**\n * @dev Amount of debt in this Vault that has been consolidated.\n */\n int128 totalConsolidatedDebtD18;\n /**\n * @dev Tracks incoming debt for each user.\n *\n * The value of shares in this distribution change as the associate market changes, i.e. price changes in an asset in\n * a spot market.\n *\n * Also, when debt is socialized in a liquidation, it is done onto this distribution. As users\n * interact with the system, their independent debt is consolidated or rolled into consolidatedDebtDist.\n */\n Distribution.Data accountsDebtDistribution;\n /**\n * @dev Tracks collateral delegated to this vault, for each user.\n *\n * Uses a distribution instead of a regular market because of the way collateral is socialized during liquidations.\n *\n * A regular mapping would require looping over the mapping of each account's collateral, or moving the liquidated\n * collateral into a place where it could later be claimed. With a distribution, liquidated collateral can be\n * socialized very easily.\n */\n ScalableMapping.Data collateralAmounts;\n /**\n * @dev Tracks consolidated debt for each user.\n *\n * Updated when users interact with the system, consolidating changes from the fluctuating accountsDebtDistribution,\n * and directly when users mint or burn USD, or repay debt.\n */\n mapping(uint256 => int256) consolidatedDebtAmountsD18;\n }\n\n /**\n * @dev Updates the value per share of the incoming debt distribution.\n * Used for socialization during liquidations, and to bake in market changes.\n *\n * Called from:\n * - LiquidationModule.liquidate\n * - Pool.recalculateVaultCollateral (ticker)\n */\n function distributeDebtToAccounts(Data storage self, int256 debtChangeD18) internal {\n self.accountsDebtDistribution.distributeValue(debtChangeD18);\n\n // Cache total debt here.\n // Will roll over to individual users as they interact with the system.\n self.unconsolidatedDebtD18 += debtChangeD18.to128();\n }\n\n /**\n * @dev Adjusts the debt associated with `accountId` by `amountD18`.\n * Used to add or remove debt from/to a specific account, instead of all accounts at once (use distributeDebtToAccounts for that)\n */\n function assignDebtToAccount(\n Data storage self,\n uint128 accountId,\n int256 amountD18\n ) internal returns (int256 newDebtD18) {\n int256 currentDebtD18 = self.consolidatedDebtAmountsD18[accountId];\n self.consolidatedDebtAmountsD18[accountId] += amountD18;\n self.totalConsolidatedDebtD18 += amountD18.to128();\n return currentDebtD18 + amountD18;\n }\n\n /**\n * @dev Consolidates user debt as they interact with the system.\n *\n * Fluctuating debt is moved from incoming to consolidated debt.\n *\n * Called as a ticker from various parts of the system, usually whenever the\n * real debt of a user needs to be known.\n */\n function consolidateAccountDebt(\n Data storage self,\n uint128 accountId\n ) internal returns (int256 currentDebtD18) {\n int256 newDebtD18 = self.accountsDebtDistribution.accumulateActor(accountId.toBytes32());\n\n currentDebtD18 = assignDebtToAccount(self, accountId, newDebtD18);\n self.unconsolidatedDebtD18 -= newDebtD18.to128();\n }\n\n /**\n * @dev Updates a user's collateral value, and sets their exposure to debt\n * according to the collateral they delegated and the leverage used.\n *\n * Called whenever a user's collateral changes.\n */\n function updateAccountPosition(\n Data storage self,\n uint128 accountId,\n uint256 collateralAmountD18,\n uint256 leverageD18\n ) internal {\n bytes32 actorId = accountId.toBytes32();\n\n // Ensure account debt is consolidated before we do next things.\n consolidateAccountDebt(self, accountId);\n\n self.collateralAmounts.set(actorId, collateralAmountD18);\n self.accountsDebtDistribution.setActorShares(\n actorId,\n self.collateralAmounts.sharesD18[actorId].mulDecimal(leverageD18)\n );\n }\n\n /**\n * @dev Returns the vault's total debt in this epoch, including the debt\n * that hasn't yet been consolidated into individual accounts.\n */\n function totalDebt(Data storage self) internal view returns (int256) {\n return self.unconsolidatedDebtD18 + self.totalConsolidatedDebtD18;\n }\n\n /**\n * @dev Returns an account's value in the Vault's collateral distribution.\n */\n function getAccountCollateral(\n Data storage self,\n uint128 accountId\n ) internal view returns (uint256 amountD18) {\n return self.collateralAmounts.get(accountId.toBytes32());\n }\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }