diff --git a/.gitignore b/.gitignore index 2ebe628..8f0a83c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,11 @@ # Ignores compiler files -cache/ -out/ +/cache/ +/out/ # Ignores development broadcast logs -!/broadcast +!/broadcast/ /broadcast/*/31337/ /broadcast/**/dry-run/ - -# Soldeer -/dependencies +# Ignores Soldeer dependencies +/dependencies/ diff --git a/README.md b/README.md index 7fc1117..d741810 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,6 @@ Very simple contract that can consume the FTSO prices is shown in `examples/netw An example usage of the FTSO system to dynamically price token in a contract is showcased in `examples/network/DynamicToken.sol` with a more detailed explanation in the [blogpost](https://medium.com/@j0-0sko/taking-it-up-to-11-74dd91c39c2b). - ### I want to confirm something using the attestation client Coming soon. diff --git a/foundry.toml b/foundry.toml index 364fe6a..8c893a4 100644 --- a/foundry.toml +++ b/foundry.toml @@ -1,6 +1,6 @@ [package] name = "flare-periphery" -version = "0.0.24" +version = "0.1.37" [profile.default] src = "src" @@ -11,18 +11,18 @@ libs = ["lib", "dependencies"] "@openzeppelin-contracts" = "5.2.0-rc.1" [soldeer] -# whether soldeer manages remappings +# Whether Soldeer manages remappings remappings_generate = true -# whether soldeer re-generates all remappings when installing, updating or uninstalling deps +# Whether Soldeer re-generates all remappings when installing, updating or uninstalling deps remappings_regenerate = false -# whether to suffix the remapping with the version: `name-a.b.c` +# Whether to suffix the remapping with the version: `name-a.b.c` remappings_version = false -# where to store the remappings ("txt" for `remappings.txt` or "config" for `foundry.toml`) -# ignored when `soldeer.toml` is used as config (uses `remappings.txt`) +# Where to store the remappings ("txt" for `remappings.txt` or "config" for `foundry.toml`) +# Ignored when `soldeer.toml` is used as config (uses `remappings.txt`) remappings_location = "txt" -# Install all subdependencies +# Whether to install all sub-dependencies recursive_deps = true diff --git a/remappings.txt b/remappings.txt index e0b6b31..8fc5144 100644 --- a/remappings.txt +++ b/remappings.txt @@ -1,2 +1,2 @@ -@openzeppelin-contracts/=dependencies/@openzeppelin-contracts-5.2.0-rc.1/ +@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.2.0-rc.1/ forge-std/=dependencies/forge-std-1.9.5/ diff --git a/soldeer.lock b/soldeer.lock index 78ef312..4b2f833 100644 --- a/soldeer.lock +++ b/soldeer.lock @@ -4,10 +4,3 @@ version = "5.2.0-rc.1" url = "https://soldeer-revisions.s3.amazonaws.com/@openzeppelin-contracts/5_2_0-rc_1_18-12-2024_19:26:33_contracts.zip" checksum = "0430f56c556a4864cb2c0f28edbd497304a1e367d30dd07942778bef3a0f7a5f" integrity = "17e24d71e2995a505f428ff1e4b514723175d8c6f7b84db6a96cfa31bc73fe23" - -[[dependencies]] -name = "forge-std" -version = "1.9.5" -url = "https://soldeer-revisions.s3.amazonaws.com/forge-std/1_9_5_21-12-2024_15:04:05_forge-std-1.9.zip" -checksum = "57ada736f383289db77fac4472d48f820e7c98172cf9b01681b0c37065ce043f" -integrity = "4753ffdfa0dde40878372b6a4d8e8fd1648b190b33996896c8b92f6f1680850f" diff --git a/src/coston/ContractRegistry.sol b/src/coston/ContractRegistry.sol index 7ef6952..a5ad492 100644 --- a/src/coston/ContractRegistry.sol +++ b/src/coston/ContractRegistry.sol @@ -1,48 +1,47 @@ // SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; +pragma solidity ^0.8.25; -import {IFlareContractRegistry} from "./IFlareContractRegistry.sol"; - -// Auto generated imports +import { IFlareContractRegistry } from "./IFlareContractRegistry.sol"; // AUTO GENERATED - DO NOT EDIT BELOW THIS LINE -import {IPriceSubmitter} from "./IPriceSubmitter.sol"; -import {IGovernanceSettings} from "./IGovernanceSettings.sol"; -import {IFtsoRewardManager} from "./IFtsoRewardManager.sol"; -import {IFtsoRegistry} from "./IFtsoRegistry.sol"; -import {IVoterWhitelister} from "./IVoterWhitelister.sol"; -import {IFtsoManager} from "./IFtsoManager.sol"; -import {IWNat} from "./IWNat.sol"; -import {IGovernanceVotePower} from "./IGovernanceVotePower.sol"; -import {IClaimSetupManager} from "./IClaimSetupManager.sol"; -import {IFlareAssetRegistry} from "./IFlareAssetRegistry.sol"; -import {IFlareContractRegistry} from "./IFlareContractRegistry.sol"; -import {ISubmission} from "./ISubmission.sol"; -import {IEntityManager} from "./IEntityManager.sol"; -import {IVoterRegistry} from "./IVoterRegistry.sol"; -import {IFlareSystemsCalculator} from "./IFlareSystemsCalculator.sol"; -import {IFlareSystemsManager} from "./IFlareSystemsManager.sol"; -import {IRewardManager} from "./IRewardManager.sol"; -import {IRelay} from "./IRelay.sol"; -import {IWNatDelegationFee} from "./IWNatDelegationFee.sol"; -import {IFtsoInflationConfigurations} from "./IFtsoInflationConfigurations.sol"; -import {IFtsoRewardOffersManager} from "./IFtsoRewardOffersManager.sol"; -import {IFtsoFeedDecimals} from "./IFtsoFeedDecimals.sol"; -import {IFtsoFeedPublisher} from "./IFtsoFeedPublisher.sol"; -import {IFtsoFeedIdConverter} from "./IFtsoFeedIdConverter.sol"; -import {IFastUpdateIncentiveManager} from "./IFastUpdateIncentiveManager.sol"; -import {IFastUpdater} from "./IFastUpdater.sol"; -import {IFastUpdatesConfiguration} from "./IFastUpdatesConfiguration.sol"; -import {IFeeCalculator} from "./IFeeCalculator.sol"; -import {FtsoV2Interface} from "./FtsoV2Interface.sol"; -import {TestFtsoV2Interface} from "./TestFtsoV2Interface.sol"; -import {ProtocolsV2Interface} from "./ProtocolsV2Interface.sol"; -import {RandomNumberV2Interface} from "./RandomNumberV2Interface.sol"; -import {RewardsV2Interface} from "./RewardsV2Interface.sol"; -import {IFdcVerification} from "./IFdcVerification.sol"; -import {IFdcHub} from "./IFdcHub.sol"; -import {IFdcRequestFeeConfigurations} from "./IFdcRequestFeeConfigurations.sol"; -import {IJsonApiVerification} from "./IJsonApiVerification.sol"; -import {IWeb2JsonVerification} from "./IWeb2JsonVerification.sol"; +import { IPriceSubmitter } from "./IPriceSubmitter.sol"; +import { IGovernanceSettings } from "./IGovernanceSettings.sol"; +import { IFtsoRewardManager } from "./IFtsoRewardManager.sol"; +import { IFtsoRegistry } from "./IFtsoRegistry.sol"; +import { IVoterWhitelister } from "./IVoterWhitelister.sol"; +import { IFtsoManager } from "./IFtsoManager.sol"; +import { IWNat } from "./IWNat.sol"; +import { IGovernanceVotePower } from "./IGovernanceVotePower.sol"; +import { IClaimSetupManager } from "./IClaimSetupManager.sol"; +import { IFlareAssetRegistry } from "./IFlareAssetRegistry.sol"; +import { IFlareContractRegistry } from "./IFlareContractRegistry.sol"; +import { ISubmission } from "./ISubmission.sol"; +import { IEntityManager } from "./IEntityManager.sol"; +import { IVoterRegistry } from "./IVoterRegistry.sol"; +import { IFlareSystemsCalculator } from "./IFlareSystemsCalculator.sol"; +import { IFlareSystemsManager } from "./IFlareSystemsManager.sol"; +import { IRewardManager } from "./IRewardManager.sol"; +import { IRelay } from "./IRelay.sol"; +import { IWNatDelegationFee } from "./IWNatDelegationFee.sol"; +import { IFtsoInflationConfigurations } from "./IFtsoInflationConfigurations.sol"; +import { IFtsoRewardOffersManager } from "./IFtsoRewardOffersManager.sol"; +import { IFtsoFeedDecimals } from "./IFtsoFeedDecimals.sol"; +import { IFtsoFeedPublisher } from "./IFtsoFeedPublisher.sol"; +import { IFtsoFeedIdConverter } from "./IFtsoFeedIdConverter.sol"; +import { IFastUpdateIncentiveManager } from "./IFastUpdateIncentiveManager.sol"; +import { IFastUpdater } from "./IFastUpdater.sol"; +import { IFastUpdatesConfiguration } from "./IFastUpdatesConfiguration.sol"; +import { IFeeCalculator } from "./IFeeCalculator.sol"; +import { FtsoV2Interface } from "./FtsoV2Interface.sol"; +import { TestFtsoV2Interface } from "./TestFtsoV2Interface.sol"; +import { ProtocolsV2Interface } from "./ProtocolsV2Interface.sol"; +import { RandomNumberV2Interface } from "./RandomNumberV2Interface.sol"; +import { RewardsV2Interface } from "./RewardsV2Interface.sol"; +import { IFdcVerification } from "./IFdcVerification.sol"; +import { IFdcHub } from "./IFdcHub.sol"; +import { IFdcRequestFeeConfigurations } from "./IFdcRequestFeeConfigurations.sol"; +import { IAssetManagerController } from "./IAssetManagerController.sol"; +import { IAssetManager } from "./IAssetManager.sol"; +import { IJsonApiVerification } from "./IJsonApiVerification.sol"; // END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE // Library is intended to be used inline, so the strings are all memory allocated (instead of calldata) @@ -105,14 +104,18 @@ library ContractRegistry { } // Nice typed getters for all the important contracts - // AUTO GENERATED - DO NOT EDIT BELOW THIS LINE - function getPriceSubmitter() internal view returns (IPriceSubmitter) { +// AUTO GENERATED - DO NOT EDIT BELOW THIS LINE + function getPriceSubmitter() + internal + view + returns (IPriceSubmitter) + { return IPriceSubmitter( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PriceSubmitter")) - ) - ); + keccak256(abi.encode("PriceSubmitter")) + ) + ); } function getGovernanceSettings() @@ -123,54 +126,74 @@ library ContractRegistry { return IGovernanceSettings( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("GovernanceSettings")) - ) - ); + keccak256(abi.encode("GovernanceSettings")) + ) + ); } - function getFtsoRewardManager() internal view returns (IFtsoRewardManager) { + function getFtsoRewardManager() + internal + view + returns (IFtsoRewardManager) + { return IFtsoRewardManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRewardManager")) - ) - ); + keccak256(abi.encode("FtsoRewardManager")) + ) + ); } - function getFtsoRegistry() internal view returns (IFtsoRegistry) { + function getFtsoRegistry() + internal + view + returns (IFtsoRegistry) + { return IFtsoRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRegistry")) - ) - ); + keccak256(abi.encode("FtsoRegistry")) + ) + ); } - function getVoterWhitelister() internal view returns (IVoterWhitelister) { + function getVoterWhitelister() + internal + view + returns (IVoterWhitelister) + { return IVoterWhitelister( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("VoterWhitelister")) - ) - ); + keccak256(abi.encode("VoterWhitelister")) + ) + ); } - function getFtsoManager() internal view returns (IFtsoManager) { + function getFtsoManager() + internal + view + returns (IFtsoManager) + { return IFtsoManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoManager")) - ) - ); + keccak256(abi.encode("FtsoManager")) + ) + ); } - function getWNat() internal view returns (IWNat) { + function getWNat() + internal + view + returns (IWNat) + { return IWNat( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("WNat")) - ) - ); + keccak256(abi.encode("WNat")) + ) + ); } function getGovernanceVotePower() @@ -181,18 +204,22 @@ library ContractRegistry { return IGovernanceVotePower( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("GovernanceVotePower")) - ) - ); + keccak256(abi.encode("GovernanceVotePower")) + ) + ); } - function getClaimSetupManager() internal view returns (IClaimSetupManager) { + function getClaimSetupManager() + internal + view + returns (IClaimSetupManager) + { return IClaimSetupManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ClaimSetupManager")) - ) - ); + keccak256(abi.encode("ClaimSetupManager")) + ) + ); } function getFlareAssetRegistry() @@ -203,9 +230,9 @@ library ContractRegistry { return IFlareAssetRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareAssetRegistry")) - ) - ); + keccak256(abi.encode("FlareAssetRegistry")) + ) + ); } function getFlareContractRegistry() @@ -216,36 +243,48 @@ library ContractRegistry { return IFlareContractRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareContractRegistry")) - ) - ); + keccak256(abi.encode("FlareContractRegistry")) + ) + ); } - function getSubmission() internal view returns (ISubmission) { + function getSubmission() + internal + view + returns (ISubmission) + { return ISubmission( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("Submission")) - ) - ); + keccak256(abi.encode("Submission")) + ) + ); } - function getEntityManager() internal view returns (IEntityManager) { + function getEntityManager() + internal + view + returns (IEntityManager) + { return IEntityManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("EntityManager")) - ) - ); + keccak256(abi.encode("EntityManager")) + ) + ); } - function getVoterRegistry() internal view returns (IVoterRegistry) { + function getVoterRegistry() + internal + view + returns (IVoterRegistry) + { return IVoterRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("VoterRegistry")) - ) - ); + keccak256(abi.encode("VoterRegistry")) + ) + ); } function getFlareSystemsCalculator() @@ -256,9 +295,9 @@ library ContractRegistry { return IFlareSystemsCalculator( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareSystemsCalculator")) - ) - ); + keccak256(abi.encode("FlareSystemsCalculator")) + ) + ); } function getFlareSystemsManager() @@ -269,36 +308,48 @@ library ContractRegistry { return IFlareSystemsManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareSystemsManager")) - ) - ); + keccak256(abi.encode("FlareSystemsManager")) + ) + ); } - function getRewardManager() internal view returns (IRewardManager) { + function getRewardManager() + internal + view + returns (IRewardManager) + { return IRewardManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RewardManager")) - ) - ); + keccak256(abi.encode("RewardManager")) + ) + ); } - function getRelay() internal view returns (IRelay) { + function getRelay() + internal + view + returns (IRelay) + { return IRelay( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("Relay")) - ) - ); + keccak256(abi.encode("Relay")) + ) + ); } - function getWNatDelegationFee() internal view returns (IWNatDelegationFee) { + function getWNatDelegationFee() + internal + view + returns (IWNatDelegationFee) + { return IWNatDelegationFee( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("WNatDelegationFee")) - ) - ); + keccak256(abi.encode("WNatDelegationFee")) + ) + ); } function getFtsoInflationConfigurations() @@ -309,9 +360,9 @@ library ContractRegistry { return IFtsoInflationConfigurations( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoInflationConfigurations")) - ) - ); + keccak256(abi.encode("FtsoInflationConfigurations")) + ) + ); } function getFtsoRewardOffersManager() @@ -322,27 +373,35 @@ library ContractRegistry { return IFtsoRewardOffersManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRewardOffersManager")) - ) - ); + keccak256(abi.encode("FtsoRewardOffersManager")) + ) + ); } - function getFtsoFeedDecimals() internal view returns (IFtsoFeedDecimals) { + function getFtsoFeedDecimals() + internal + view + returns (IFtsoFeedDecimals) + { return IFtsoFeedDecimals( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoFeedDecimals")) - ) - ); + keccak256(abi.encode("FtsoFeedDecimals")) + ) + ); } - function getFtsoFeedPublisher() internal view returns (IFtsoFeedPublisher) { + function getFtsoFeedPublisher() + internal + view + returns (IFtsoFeedPublisher) + { return IFtsoFeedPublisher( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoFeedPublisher")) - ) - ); + keccak256(abi.encode("FtsoFeedPublisher")) + ) + ); } function getFtsoFeedIdConverter() @@ -353,9 +412,9 @@ library ContractRegistry { return IFtsoFeedIdConverter( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoFeedIdConverter")) - ) - ); + keccak256(abi.encode("FtsoFeedIdConverter")) + ) + ); } function getFastUpdateIncentiveManager() @@ -366,18 +425,22 @@ library ContractRegistry { return IFastUpdateIncentiveManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FastUpdateIncentiveManager")) - ) - ); + keccak256(abi.encode("FastUpdateIncentiveManager")) + ) + ); } - function getFastUpdater() internal view returns (IFastUpdater) { + function getFastUpdater() + internal + view + returns (IFastUpdater) + { return IFastUpdater( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FastUpdater")) - ) - ); + keccak256(abi.encode("FastUpdater")) + ) + ); } function getFastUpdatesConfiguration() @@ -388,45 +451,61 @@ library ContractRegistry { return IFastUpdatesConfiguration( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FastUpdatesConfiguration")) - ) - ); + keccak256(abi.encode("FastUpdatesConfiguration")) + ) + ); } - function getFeeCalculator() internal view returns (IFeeCalculator) { + function getFeeCalculator() + internal + view + returns (IFeeCalculator) + { return IFeeCalculator( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FeeCalculator")) - ) - ); + keccak256(abi.encode("FeeCalculator")) + ) + ); } - function getFtsoV2() internal view returns (FtsoV2Interface) { + function getFtsoV2() + internal + view + returns (FtsoV2Interface) + { return FtsoV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoV2")) - ) - ); + keccak256(abi.encode("FtsoV2")) + ) + ); } - function getTestFtsoV2() internal view returns (TestFtsoV2Interface) { + function getTestFtsoV2() + internal + view + returns (TestFtsoV2Interface) + { return TestFtsoV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoV2")) - ) - ); + keccak256(abi.encode("FtsoV2")) + ) + ); } - function getProtocolsV2() internal view returns (ProtocolsV2Interface) { + function getProtocolsV2() + internal + view + returns (ProtocolsV2Interface) + { return ProtocolsV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ProtocolsV2")) - ) - ); + keccak256(abi.encode("ProtocolsV2")) + ) + ); } function getRandomNumberV2() @@ -437,36 +516,48 @@ library ContractRegistry { return RandomNumberV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RandomNumberV2")) - ) - ); + keccak256(abi.encode("RandomNumberV2")) + ) + ); } - function getRewardsV2() internal view returns (RewardsV2Interface) { + function getRewardsV2() + internal + view + returns (RewardsV2Interface) + { return RewardsV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RewardsV2")) - ) - ); + keccak256(abi.encode("RewardsV2")) + ) + ); } - function getFdcVerification() internal view returns (IFdcVerification) { + function getFdcVerification() + internal + view + returns (IFdcVerification) + { return IFdcVerification( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcVerification")) - ) - ); + keccak256(abi.encode("FdcVerification")) + ) + ); } - function getFdcHub() internal view returns (IFdcHub) { + function getFdcHub() + internal + view + returns (IFdcHub) + { return IFdcHub( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcHub")) - ) - ); + keccak256(abi.encode("FdcHub")) + ) + ); } function getFdcRequestFeeConfigurations() @@ -477,29 +568,47 @@ library ContractRegistry { return IFdcRequestFeeConfigurations( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcRequestFeeConfigurations")) - ) - ); + keccak256(abi.encode("FdcRequestFeeConfigurations")) + ) + ); } - // Returns hardcoded unofficial deployment instances of Flare core contracts - function auxiliaryGetIJsonApiVerification() + function getAssetManagerController() internal - pure - returns (IJsonApiVerification) + view + returns (IAssetManagerController) { - return IJsonApiVerification(0x206D83e3a24523De1E43Ab56AC8f7b9b10f6ab89); + return + IAssetManagerController( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("AssetManagerController")) + ) + ); } - // Returns hardcoded unofficial deployment instances of Flare core contracts - function auxiliaryGetIWeb2JsonVerification() + function getAssetManagerFXRP() + internal + view + returns (IAssetManager) + { + return + IAssetManager( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("AssetManagerFXRP")) + ) + ); + } + + function auxiliaryGetIJsonApiVerification() internal pure - returns (IWeb2JsonVerification) + returns (IJsonApiVerification) { return - IWeb2JsonVerification(0x30DAB57c409E1e18c8B00dC351Bf568953D607B1); + IJsonApiVerification( + 0x206D83e3a24523De1E43Ab56AC8f7b9b10f6ab89 + ); } - // END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE -} +// END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE +} \ No newline at end of file diff --git a/src/coston/IAgentOwnerRegistry.sol b/src/coston/IAgentOwnerRegistry.sol new file mode 100644 index 0000000..4075ba8 --- /dev/null +++ b/src/coston/IAgentOwnerRegistry.sol @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +/** + * Agent owner management and work address management + */ +interface IAgentOwnerRegistry { + + event Whitelisted(address value); + event WhitelistingRevoked(address value); + + /** + * Agent owner's work address has been set. + */ + event WorkAddressChanged( + address indexed managementAddress, + address prevWorkAddress, + address workAddress); + + event AgentDataChanged( + address indexed managementAddress, + string name, + string description, + string iconUrl, + string termsOfUseUrl); + + error AgentNotWhitelisted(); + error WorkAddressInUse(); + + + /** + * Returns true if the address is whitelisted, false otherwise. + * @param _address address to check + */ + function isWhitelisted(address _address) external view returns (bool); + + /** + * Return agent owner's name. + * @param _managementAddress agent owner's management address + */ + function getAgentName(address _managementAddress) + external view + returns (string memory); + + /** + * Return agent owner's description. + * @param _managementAddress agent owner's management address + */ + function getAgentDescription(address _managementAddress) + external view + returns (string memory); + + /** + * Return url of the agent owner's icon. + * @param _managementAddress agent owner's management address + */ + function getAgentIconUrl(address _managementAddress) + external view + returns (string memory); + + /** + * Return url of the agent's page with terms of use. + * @param _managementAddress agent owner's management address + */ + function getAgentTermsOfUseUrl(address _managementAddress) + external view + returns (string memory); + + /** + * Get the (unique) work address for the given management address. + */ + function getWorkAddress(address _managementAddress) + external view + returns (address); + + /** + * Get the (unique) management address for the given work address. + */ + function getManagementAddress(address _workAddress) + external view + returns (address); +} \ No newline at end of file diff --git a/src/coston/IAssetManager.sol b/src/coston/IAssetManager.sol index 4bfe18a..60953d0 100644 --- a/src/coston/IAssetManager.sol +++ b/src/coston/IAssetManager.sol @@ -1,24 +1,26 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IFdcVerification.sol"; -import "@openzeppelin-contracts/utils/introspection/IERC165.sol"; -import "./diamond/interfaces/IDiamondLoupe.sol"; -import "./userInterfaces/data/AssetManagerSettings.sol"; -import "./userInterfaces/data/CollateralType.sol"; -import "./userInterfaces/data/AgentInfo.sol"; -import "./userInterfaces/data/AgentSettings.sol"; -import "./userInterfaces/data/AvailableAgentInfo.sol"; -import "./userInterfaces/data/RedemptionTicketInfo.sol"; -import "./userInterfaces/data/RedemptionRequestInfo.sol"; -import "./userInterfaces/data/CollateralReservationInfo.sol"; -import "./IAssetManagerEvents.sol"; -import "./IAgentPing.sol"; -import "./IRedemptionTimeExtension.sol"; -import "./ITransferFees.sol"; -import "./ICoreVault.sol"; -import "./ICoreVaultSettings.sol"; -import "./IAgentAlwaysAllowedMinters.sol"; +import {IConfirmedBlockHeightExists, IPayment, IAddressValidity, IReferencedPaymentNonexistence, + IBalanceDecreasingTransaction} + from ".//IFdcVerification.sol"; +import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; +import {IDiamondLoupe} from "./diamond/interfaces/IDiamondLoupe.sol"; +import {AssetManagerSettings} from "./data/AssetManagerSettings.sol"; +import {CollateralType} from "./data/CollateralType.sol"; +import {AgentInfo} from "./data/AgentInfo.sol"; +import {AgentSettings} from "./data/AgentSettings.sol"; +import {AvailableAgentInfo} from "./data/AvailableAgentInfo.sol"; +import {RedemptionTicketInfo} from "./data/RedemptionTicketInfo.sol"; +import {RedemptionRequestInfo} from "./data/RedemptionRequestInfo.sol"; +import {CollateralReservationInfo} from "./data/CollateralReservationInfo.sol"; +import {IAssetManagerEvents} from "./IAssetManagerEvents.sol"; +import {IAgentPing} from "./IAgentPing.sol"; +import {IRedemptionTimeExtension} from "./IRedemptionTimeExtension.sol"; +import {ICoreVaultClient} from "./ICoreVaultClient.sol"; +import {ICoreVaultClientSettings} from "./ICoreVaultClientSettings.sol"; +import {IAgentAlwaysAllowedMinters} from "./IAgentAlwaysAllowedMinters.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @@ -30,9 +32,8 @@ interface IAssetManager is IAssetManagerEvents, IAgentPing, IRedemptionTimeExtension, - ITransferFees, - ICoreVault, - ICoreVaultSettings, + ICoreVaultClient, + ICoreVaultClientSettings, IAgentAlwaysAllowedMinters { //////////////////////////////////////////////////////////////////////////////////// @@ -148,19 +149,6 @@ interface IAssetManager is external view returns (bool); - /** - * True if the asset manager is terminated. - * In terminated state almost all operations (minting, redeeming, liquidation) are disabled and f-assets are - * not transferable any more. The only operation still permitted is for agents to release the locked collateral - * by calling `buybackAgentCollateral`. - * An asset manager can be terminated after being paused for at least a month - * (to redeem as many f-assets as possible). - * The terminated asset manager can not be revived anymore. - */ - function terminated() - external view - returns (bool); - //////////////////////////////////////////////////////////////////////////////////// // Timekeeping for underlying chain @@ -207,20 +195,6 @@ interface IAssetManager is //////////////////////////////////////////////////////////////////////////////////// // Agent create / destroy - /** - * This method fixes the underlying address to be used by given agent owner. - * A proof of payment (can be minimal or to itself) from this address must be provided, - * with payment reference being equal to this method caller's address. - * NOTE: calling this method before `createAgentVault()` is optional on most chains, - * but is required on smart contract chains to make sure the agent is using EOA address - * (depends on setting `requireEOAAddressProof`). - * NOTE: may only be called by a whitelisted agent (management or work owner address). - * @param _payment proof of payment on the underlying chain - */ - function proveUnderlyingAddressEOA( - IPayment.Proof calldata _payment - ) external; - /** * Create an agent vault. * The agent will always be identified by `_agentVault` address. @@ -326,7 +300,7 @@ interface IAssetManager is ) external; /** - * When current pool collateral token contract (WNat) is replaced by the method setPoolCollateralType, + * When current pool collateral token contract (WNat) is replaced by the method setPoolWNatCollateralType, * pools don't switch automatically. Instead, the agent must call this method that swaps old WNat tokens for * new ones and sets it for use by the pool. * NOTE: may only be called by the agent vault owner. @@ -426,24 +400,6 @@ interface IAssetManager is address _agentVault ) external; - //////////////////////////////////////////////////////////////////////////////////// - // Terminated asset manager support - - /** - * When f-asset is terminated, an agent can burn the market price of backed f-assets with his collateral, - * to release the remaining collateral (and, formally, underlying assets). - * This method ONLY works when f-asset is terminated, which will only be done when the asset manager - * is already paused at least for a month and most f-assets are already burned and the only ones - * remaining are unrecoverable. - * NOTE: may only be called by the agent vault owner. - * NOTE: the agent (management address) receives the vault collateral and NAT is burned instead. Therefore - * this method is `payable` and the caller must provide enough NAT to cover the received vault collateral - * amount multiplied by `vaultCollateralBuyForFlareFactorBIPS`. - */ - function buybackAgentCollateral( - address _agentVault - ) external payable; - //////////////////////////////////////////////////////////////////////////////////// // Agent information @@ -455,7 +411,7 @@ interface IAssetManager is */ function getAllAgents(uint256 _start, uint256 _end) external view - returns (address[] memory _agentVaults, uint256 _totalLength); + returns (address[] memory _agents, uint256 _totalLength); /** * Return detailed info about an agent, typically needed by a minter. @@ -473,8 +429,7 @@ interface IAssetManager is * @param _agentVault agent vault address * @param _name setting name, one of: `feeBIPS`, `poolFeeShareBIPS`, `redemptionPoolFeeShareBIPS`, * `mintingVaultCollateralRatioBIPS`, `mintingPoolCollateralRatioBIPS`,`buyFAssetByAgentFactorBIPS`, - * `poolExitCollateralRatioBIPS`, `poolTopupCollateralRatioBIPS`, `poolTopupTokenPriceFactorBIPS`, - * `handshakeType` + * `poolExitCollateralRatioBIPS` */ function getAgentSetting(address _agentVault, string memory _name) external view @@ -582,7 +537,7 @@ interface IAssetManager is */ function getAvailableAgentsList(uint256 _start, uint256 _end) external view - returns (address[] memory _agentVaults, uint256 _totalLength); + returns (address[] memory _agents, uint256 _totalLength); /** * Get (a part of) the list of available agents with extra information about agents' fee, min collateral ratio @@ -604,15 +559,11 @@ interface IAssetManager is * Before paying underlying assets for minting, minter has to reserve collateral and * pay collateral reservation fee. Collateral is reserved at ratio of agent's agentMinCollateralRatio * to requested lots NAT market price. - * If the agent requires handshake, then HandshakeRequired event is emitted and - * the minter has to wait for the agent to approve or reject the reservation. If there is no response within - * the `cancelCollateralReservationAfterSeconds`, the minter can cancel the reservation and get the fee back. - * If handshake is not required, the minter receives instructions for underlying payment + * The minter receives instructions for underlying payment * (value, fee and payment reference) in event CollateralReserved. * Then the minter has to pay `value + fee` on the underlying chain. - * If the minter pays the underlying amount, the collateral reservation fee is burned and minter obtains - * f-assets. Otherwise the agent collects the collateral reservation fee. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. + * If the minter pays the underlying amount, minter obtains f-assets. + * The collateral reservation fee is split between the agent and the collateral pool. * NOTE: the owner of the agent vault must be in the AgentOwnerRegistry. * @param _agentVault agent vault address * @param _lots the number of lots for which to reserve collateral @@ -621,45 +572,14 @@ interface IAssetManager is * and increasing fee (that would mean that the minter would have to pay raised fee or forfeit * collateral reservation fee) * @param _executor the account that is allowed to execute minting (besides minter and agent) - * @param _minterUnderlyingAddresses array of minter's underlying addresses - needed only if handshake is required */ function reserveCollateral( address _agentVault, uint256 _lots, uint256 _maxMintingFeeBIPS, - address payable _executor, - string[] calldata _minterUnderlyingAddresses - ) external payable; - - /** - * Agent approves the collateral reservation request after checking the minter's identity. - * NOTE: may only be called by the agent vault owner. - * @param _collateralReservationId collateral reservation id - */ - function approveCollateralReservation( - uint256 _collateralReservationId - ) external; - - /** - * Agent rejects the collateral reservation request after checking the minter's identity. - * The collateral reservation fee is returned to the minter. - * NOTE: may only be called by the agent vault owner. - * @param _collateralReservationId collateral reservation id - */ - function rejectCollateralReservation( - uint256 _collateralReservationId - ) external; - - /** - * Minter cancels the collateral reservation request if the agent didn't respond in time. - * The collateral reservation fee is returned to the minter. - * It can only be called after `cancelCollateralReservationAfterSeconds` from the collateral reservation request. - * NOTE: may only be called by the minter. - * @param _collateralReservationId collateral reservation id - */ - function cancelCollateralReservation( - uint256 _collateralReservationId - ) external; + address payable _executor + ) external payable + returns (uint256 _collateralReservationId); /** * Return the collateral reservation fee amount that has to be passed to the `reserveCollateral` method. @@ -686,8 +606,6 @@ interface IAssetManager is /** * After obtaining proof of underlying payment, the minter calls this method to finish the minting * and collect the minted f-assets. - * NOTE: In case handshake was required, the payment must be done using only all provided addresses, - * so `sourceAddressesRoot` matches the calculated Merkle root, otherwise the proof will be rejected. * NOTE: may only be called by the minter (= creator of CR, the collateral reservation request), * the executor appointed by the minter, or the agent owner (= owner of the agent vault in CR). * @param _payment proof of the underlying payment (must contain exact `value + fee` amount and correct @@ -703,9 +621,7 @@ interface IAssetManager is * When the time for the minter to pay the underlying amount is over (i.e. the last underlying block has passed), * the agent can declare payment default. Then the agent collects the collateral reservation fee * (it goes directly to the vault), and the reserved collateral is unlocked. - * NOTE: In case handshake was required, the attestation request must be done using `checkSourceAddresses=true` - * and correct `sourceAddressesRoot`, otherwise the proof will be rejected. If there was no handshake required, - * the attestation request must be done with `checkSourceAddresses=false`. + * NOTE: The attestation request must be done with `checkSourceAddresses=false`. * NOTE: may only be called by the owner of the agent vault in the collateral reservation request. * @param _proof proof that the minter didn't pay with correct payment reference on the underlying chain * @param _collateralReservationId id of a collateral reservation created by the minter @@ -750,7 +666,7 @@ interface IAssetManager is ) external; /** - * If an agent has enough free underlying, they can mint immediatelly without any underlying payment. + * If an agent has enough free underlying, they can mint immediately without any underlying payment. * This is a one-step process, skipping collateral reservation and collateral reservation fee payment. * Moreover, the agent doesn't have to be on the publicly available agents list to self-mint. * NOTE: may only be called by the agent vault owner. @@ -777,7 +693,6 @@ interface IAssetManager is * of remaining lots. * Agent receives redemption request id and instructions for underlying payment in * RedemptionRequested event and has to pay `value - fee` and use the provided payment reference. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _lots number of lots to redeem * @param _redeemerUnderlyingAddressString the address to which the agent must transfer underlying amount * @param _executor the account that is allowed to execute redemption default (besides redeemer and agent) @@ -791,28 +706,6 @@ interface IAssetManager is ) external payable returns (uint256 _redeemedAmountUBA); - /** - * In case agent requires handshake the redemption request can be rejected by the agent. - * Any other agent can take over the redemption request. - * If no agent takes over the redemption, the redeemer can request the default payment. - * NOTE: may only be called by the owner of the agent vault in the redemption request - * @param _redemptionRequestId id of an existing redemption request - */ - function rejectRedemptionRequest( - uint256 _redemptionRequestId - ) external; - - /** - * The agent can take over the rejected redemption request - it cannot be rejected again. - * NOTE: may only be called by the owner of the agent vault - * @param _agentVault agent vault address - * @param _redemptionRequestId id of an existing redemption request - */ - function takeOverRedemptionRequest( - address _agentVault, - uint256 _redemptionRequestId - ) external; - /** * If the redeemer provides invalid address, the agent should provide the proof of address invalidity from the * Flare data connector. With this, the agent's obligations are fulfilled and they can keep the underlying. @@ -864,20 +757,6 @@ interface IAssetManager is uint256 _redemptionRequestId ) external; - /** - * If the agent rejected the redemption request and no other agent took over the redemption, - * the redeemer calls this method and receives payment in collateral (with some extra). - * The agent can also call default if the redeemer is unresponsive, to payout the redeemer and free the - * remaining collateral. - * NOTE: may only be called by the redeemer (= creator of the redemption request), - * the executor appointed by the redeemer, - * or the agent owner (= owner of the agent vault in the redemption request) - * @param _redemptionRequestId id of an existing redemption request - */ - function rejectedRedemptionPaymentDefault( - uint256 _redemptionRequestId - ) external; - /** * If the agent hasn't performed the payment, the agent can close the redemption request to free underlying funds. * It can be done immediately after the redeemer or agent calls `redemptionPaymentDefault`, @@ -975,18 +854,15 @@ interface IAssetManager is // Liquidation /** - * Checks that the agent's collateral is too low and if true, starts the agent's liquidation. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. - * NOTE: always succeeds and returns the new liquidation status. + * Checks that the agent's collateral is too low and if true, starts agent's liquidation. + * If the agent is already in liquidation, returns the timestamp when liquidation started. * @param _agentVault agent vault address - * @return _liquidationStatus 0=no liquidation, 1=CCB, 2=liquidation - * @return _liquidationStartTs if the status is LIQUIDATION, the timestamp when liquidation started; - * if the status is CCB, the timestamp when liquidation will start; otherwise 0 + * @return _liquidationStartTs timestamp when liquidation started */ function startLiquidation( address _agentVault ) external - returns (uint8 _liquidationStatus, uint256 _liquidationStartTs); + returns (uint256 _liquidationStartTs); /** * Burns up to `_amountUBA` f-assets owned by the caller and pays @@ -994,7 +870,6 @@ interface IAssetManager is * (premium depends on the liquidation state). * If the agent isn't in liquidation yet, but satisfies conditions, * automatically puts the agent in liquidation status. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _agentVault agent vault address * @param _amountUBA the amount of f-assets to liquidate * @return _liquidatedAmountUBA liquidated amount of f-asset @@ -1028,12 +903,11 @@ interface IAssetManager is * no valid payment reference exists (valid payment references are from redemption and * underlying withdrawal announcement calls). * On success, immediately triggers full agent liquidation and rewards the caller. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. - * @param _transaction proof of a transaction from the agent's underlying address + * @param _payment proof of a transaction from the agent's underlying address * @param _agentVault agent vault address */ function illegalPaymentChallenge( - IBalanceDecreasingTransaction.Proof calldata _transaction, + IBalanceDecreasingTransaction.Proof calldata _payment, address _agentVault ) external; @@ -1041,7 +915,6 @@ interface IAssetManager is * Called with proofs of two payments made from the agent's underlying address * with the same payment reference (each payment reference is valid for only one payment). * On success, immediately triggers full agent liquidation and rewards the caller. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _payment1 proof of first payment from the agent's underlying address * @param _payment2 proof of second payment from the agent's underlying address * @param _agentVault agent vault address @@ -1057,7 +930,6 @@ interface IAssetManager is * underlying free balance negative (i.e. the underlying address balance is less than * the total amount of backed f-assets). * On success, immediately triggers full agent liquidation and rewards the caller. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _payments proofs of several distinct payments from the agent's underlying address * @param _agentVault agent vault address */ diff --git a/src/coston/IAssetManagerController.sol b/src/coston/IAssetManagerController.sol new file mode 100644 index 0000000..be64480 --- /dev/null +++ b/src/coston/IAssetManagerController.sol @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {IAssetManager} from "./IAssetManager.sol"; + + +interface IAssetManagerController { + /** + * Return the list of all asset managers managed by this controller. + */ + function getAssetManagers() + external view + returns (IAssetManager[] memory); + + /** + * Check whether the asset manager is managed by this controller. + * @param _assetManager an asset manager address + */ + function assetManagerExists(address _assetManager) + external view + returns (bool); +} diff --git a/src/coston/IAssetManagerEvents.sol b/src/coston/IAssetManagerEvents.sol index 032d711..e9dd216 100644 --- a/src/coston/IAssetManagerEvents.sol +++ b/src/coston/IAssetManagerEvents.sol @@ -18,9 +18,7 @@ interface IAssetManagerEvents { uint256 mintingPoolCollateralRatioBIPS; uint256 buyFAssetByAgentFactorBIPS; uint256 poolExitCollateralRatioBIPS; - uint256 poolTopupCollateralRatioBIPS; - uint256 poolTopupTokenPriceFactorBIPS; - uint256 handshakeType; + uint256 redemptionPoolFeeShareBIPS; } /** @@ -115,18 +113,6 @@ interface IAssetManagerEvents { uint8 collateralClass, address token); - /** - * Minter reserved collateral, paid the reservation fee. Agent's collateral was reserved. - * Agent needs to approve or reject the reservation according to the minter's identity. - */ - event HandshakeRequired( - address indexed agentVault, - address indexed minter, - uint256 indexed collateralReservationId, - string[] minterUnderlyingAddresses, - uint256 valueUBA, - uint256 feeUBA); - /** * Minter reserved collateral, paid the reservation fee, and is expected to pay the underlying funds. * Agent's collateral was reserved. @@ -145,24 +131,6 @@ interface IAssetManagerEvents { address executor, uint256 executorFeeNatWei); - /** - * Agent rejected the collateral reservation request because of the minter's identity. - * Reserved collateral was released. - */ - event CollateralReservationRejected( - address indexed agentVault, - address indexed minter, - uint256 indexed collateralReservationId); - - /** - * Minter cancelled the collateral reservation request because of the agent's inactivity. - * Reserved collateral was released. - */ - event CollateralReservationCancelled( - address indexed agentVault, - address indexed minter, - uint256 indexed collateralReservationId); - /** * Minter paid underlying funds in time and received the fassets. * The agent's collateral is locked. @@ -227,34 +195,13 @@ interface IAssetManagerEvents { address executor, uint256 executorFeeNatWei); - /** - * Agent rejected the redemption request because of the redeemer's identity. - */ - event RedemptionRequestRejected( - address indexed agentVault, - address indexed redeemer, - uint64 indexed requestId, - string paymentAddress, - uint256 valueUBA); - - /** - * Agent's rejected redemption request was taken over by another agent. - */ - event RedemptionRequestTakenOver( - address indexed agentVault, - address indexed redeemer, - uint64 indexed requestId, - uint256 valueTakenOverUBA, - address newAgentVault, - uint64 newRequestId); - /** * Agent rejected the redemption payment because the redeemer's address is invalid. */ event RedemptionRejected( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, uint256 redemptionAmountUBA); /** @@ -273,7 +220,7 @@ interface IAssetManagerEvents { event RedemptionPerformed( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, bytes32 transactionHash, uint256 redemptionAmountUBA, int256 spentUnderlyingUBA); @@ -288,7 +235,7 @@ interface IAssetManagerEvents { event RedemptionDefault( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, uint256 redemptionAmountUBA, uint256 redeemedVaultCollateralWei, uint256 redeemedPoolCollateralWei); @@ -302,7 +249,7 @@ interface IAssetManagerEvents { event RedemptionPaymentBlocked( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, bytes32 transactionHash, uint256 redemptionAmountUBA, int256 spentUnderlyingUBA); @@ -314,7 +261,7 @@ interface IAssetManagerEvents { event RedemptionPaymentFailed( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, bytes32 transactionHash, int256 spentUnderlyingUBA, string failureReason); @@ -325,7 +272,7 @@ interface IAssetManagerEvents { */ event RedemptionPoolFeeMinted( address indexed agentVault, - uint64 indexed requestId, + uint256 indexed requestId, uint256 poolFeeUBA); /** @@ -379,14 +326,6 @@ interface IAssetManagerEvents { address indexed agentVault, uint256 dustUBA); - /** - * Agent entered CCB (collateral call band) due to being on the border of unhealthy. - * Agent has limited time to topup the collateral, otherwise liquidation starts. - */ - event AgentInCCB( - address indexed agentVault, - uint256 timestamp); - /** * Agent entered liquidation state due to unhealthy position. * The liquidation ends when the agent is again healthy or the agent's position is fully liquidated. @@ -434,7 +373,7 @@ interface IAssetManagerEvents { */ event UnderlyingWithdrawalAnnounced( address indexed agentVault, - uint64 indexed announcementId, + uint256 indexed announcementId, bytes32 paymentReference); /** @@ -445,7 +384,7 @@ interface IAssetManagerEvents { */ event UnderlyingWithdrawalConfirmed( address indexed agentVault, - uint64 indexed announcementId, + uint256 indexed announcementId, int256 spentUBA, bytes32 transactionHash); @@ -456,7 +395,7 @@ interface IAssetManagerEvents { */ event UnderlyingWithdrawalCancelled( address indexed agentVault, - uint64 indexed announcementId); + uint256 indexed announcementId); /** * Emitted when the agent tops up the underlying address balance. @@ -542,17 +481,15 @@ interface IAssetManagerEvents { string assetFtsoSymbol, string tokenFtsoSymbol, uint256 minCollateralRatioBIPS, - uint256 ccbMinCollateralRatioBIPS, uint256 safetyMinCollateralRatioBIPS); /** - * System defined collateral ratios for the token have changed (minimal, CCB and safety collateral ratio). + * System defined collateral ratios for the token have changed (minimal and safety collateral ratio). */ event CollateralRatiosChanged( uint8 collateralClass, address collateralToken, uint256 minCollateralRatioBIPS, - uint256 ccbMinCollateralRatioBIPS, uint256 safetyMinCollateralRatioBIPS); /** diff --git a/src/coston/IClaimSetupManager.sol b/src/coston/IClaimSetupManager.sol index 384de98..17cc70c 100644 --- a/src/coston/IClaimSetupManager.sol +++ b/src/coston/IClaimSetupManager.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IDelegationAccount.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IClaimSetupManager { diff --git a/src/coston/ICoreVault.sol b/src/coston/ICoreVaultClient.sol similarity index 90% rename from src/coston/ICoreVault.sol rename to src/coston/ICoreVaultClient.sol index d503cad..9340e57 100644 --- a/src/coston/ICoreVault.sol +++ b/src/coston/ICoreVaultClient.sol @@ -1,13 +1,13 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IFdcVerification.sol"; +import {IPayment} from ".//IFdcVerification.sol"; /** * Core vault */ -interface ICoreVault { +interface ICoreVaultClient { /** * Agent has requested transfer of (some of) their backing to the core vault. */ @@ -78,7 +78,7 @@ interface ICoreVault { * @param _amountUBA the amount to transfer to the core vault */ function transferToCoreVault(address _agentVault, uint256 _amountUBA) - external payable; + external; /** * Request that core vault transfers funds to the agent's underlying address, @@ -90,7 +90,7 @@ interface ICoreVault { * @param _agentVault the agent vault address * @param _lots number of lots (same lots as for minting and redemptions) */ - function requestReturnFromCoreVault(address _agentVault, uint64 _lots) + function requestReturnFromCoreVault(address _agentVault, uint256 _lots) external; /** @@ -118,19 +118,9 @@ interface ICoreVault { * must have been added to the `allowedDestinations` list in the core vault manager by * the governance before the redemption request. */ - function redeemFromCoreVault(uint64 _lots, string memory _redeemerUnderlyingAddress) + function redeemFromCoreVault(uint256 _lots, string memory _redeemerUnderlyingAddress) external; - /** - * Return the amount of NAT that has to be paid in `transferToCoreVault` call. - * @param _amountUBA the amount to transfer to the core vault - * @return _transferFeeNatWei the amount that has to be included as `msg.value` and is paid to the core vault - */ - function transferToCoreVaultFee( - uint256 _amountUBA - ) external view - returns (uint256 _transferFeeNatWei); - /** * Return the maximum amount that can be transferred and the minimum amount that * has to remain on the agent vault's underlying address. diff --git a/src/songbird/ICoreVaultSettings.sol b/src/coston/ICoreVaultClientSettings.sol similarity index 85% rename from src/songbird/ICoreVaultSettings.sol rename to src/coston/ICoreVaultClientSettings.sol index a43c345..c708303 100644 --- a/src/songbird/ICoreVaultSettings.sol +++ b/src/coston/ICoreVaultClientSettings.sol @@ -4,16 +4,13 @@ pragma solidity >=0.7.6 <0.9; /** * Core vault settings */ -interface ICoreVaultSettings { +interface ICoreVaultClientSettings { function setCoreVaultManager(address _coreVaultManager) external; function setCoreVaultNativeAddress(address payable _nativeAddress) external; - function setCoreVaultTransferFeeBIPS(uint256 _transferFeeBIPS) - external; - function setCoreVaultTransferTimeExtensionSeconds(uint256 _transferTimeExtensionSeconds) external; @@ -34,10 +31,6 @@ interface ICoreVaultSettings { external view returns (address); - function getCoreVaultTransferFeeBIPS() - external view - returns (uint256); - function getCoreVaultTransferTimeExtensionSeconds() external view returns (uint256); diff --git a/src/coston/IDelegationAccount.sol b/src/coston/IDelegationAccount.sol index 2093b99..815a909 100644 --- a/src/coston/IDelegationAccount.sol +++ b/src/coston/IDelegationAccount.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IClaimSetupManager.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDelegationAccount { diff --git a/src/coston/IFdcVerification.sol b/src/coston/IFdcVerification.sol index d7e51cd..b37662c 100644 --- a/src/coston/IFdcVerification.sol +++ b/src/coston/IFdcVerification.sol @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +import "./IRelay.sol"; import "./IAddressValidityVerification.sol"; import "./IBalanceDecreasingTransactionVerification.sol"; import "./IConfirmedBlockHeightExistsVerification.sol"; @@ -9,16 +10,25 @@ import "./IPaymentVerification.sol"; import "./IReferencedPaymentNonexistenceVerification.sol"; import "./IWeb2JsonVerification.sol"; - /** * FdcVerification interface. */ interface IFdcVerification is - IAddressValidityVerification, - IBalanceDecreasingTransactionVerification, - IConfirmedBlockHeightExistsVerification, - IEVMTransactionVerification, - IPaymentVerification, - IReferencedPaymentNonexistenceVerification, - IWeb2JsonVerification -{ } + IAddressValidityVerification, + IBalanceDecreasingTransactionVerification, + IConfirmedBlockHeightExistsVerification, + IEVMTransactionVerification, + IPaymentVerification, + IReferencedPaymentNonexistenceVerification, + IWeb2JsonVerification +{ + /** + * The FDC protocol id. + */ + function fdcProtocolId() external view returns (uint8 _fdcProtocolId); + + /** + * Relay contract address. + */ + function relay() external view returns (IRelay); +} diff --git a/src/coston/IFtsoManager.sol b/src/coston/IFtsoManager.sol index ed1c4c0..cfc7cc5 100644 --- a/src/coston/IFtsoManager.sol +++ b/src/coston/IFtsoManager.sol @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./ftso/interface/IIFtso.sol"; -import "./genesis/interface/IFtsoManagerGenesis.sol"; +import "./ftso/interfaces/IIFtso.sol"; +import "./genesis/interfaces/IFtsoManagerGenesis.sol"; interface IFtsoManager is IFtsoManagerGenesis { diff --git a/src/coston/IFtsoRegistry.sol b/src/coston/IFtsoRegistry.sol index f9d8c6a..46ab964 100644 --- a/src/coston/IFtsoRegistry.sol +++ b/src/coston/IFtsoRegistry.sol @@ -2,8 +2,8 @@ pragma solidity >=0.7.6 <0.9; pragma abicoder v2; -import "./ftso/interface/IIFtso.sol"; -import "./genesis/interface/IFtsoRegistryGenesis.sol"; +import "./ftso/interfaces/IIFtso.sol"; +import "./genesis/interfaces/IFtsoRegistryGenesis.sol"; interface IFtsoRegistry is IFtsoRegistryGenesis { diff --git a/src/coston/IGovernor.sol b/src/coston/IGovernor.sol index 48bdd0f..fff729f 100644 --- a/src/coston/IGovernor.sol +++ b/src/coston/IGovernor.sol @@ -1,14 +1,12 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; -/** - * Governor interface. - */ interface IGovernor { struct GovernorSettings { bool accept; - uint256 votingStartTs; + uint256 votingDelaySeconds; uint256 votingPeriodSeconds; uint256 vpBlockPeriodSeconds; uint256 thresholdConditionBIPS; @@ -18,15 +16,7 @@ interface IGovernor { } /** - * Enum describing a proposal state. - - * A proposal is: - * * `Pending` when first created, - * * `Active` when it’s being voted on, - * * `Defeated` or `Succeeded` as a result of the vote, - * * `Queued` when in the process of executing, - * * `Expired` when it times out or fails to execute upon a certain date, and - * * `Executed` when it goes live. + * @notice Enum describing a proposal state */ enum ProposalState { Pending, @@ -40,7 +30,7 @@ interface IGovernor { } /** - * Event emitted when a proposal is created. + * @notice Event emitted when a proposal is created */ event ProposalCreated( uint256 indexed proposalId, @@ -59,17 +49,17 @@ interface IGovernor { ); /** - * Event emitted when a proposal is canceled. + * @notice Event emitted when a proposal is canceled */ event ProposalCanceled(uint256 indexed proposalId); /** - * Event emitted when a proposal is executed. + * @notice Event emitted when a proposal is executed */ event ProposalExecuted(uint256 indexed proposalId); /** - * Event emitted when a vote is cast. + * @notice Event emitted when a vote is cast */ event VoteCast( address indexed voter, @@ -80,30 +70,30 @@ interface IGovernor { uint256 forVotePower, uint256 againstVotePower ); - + /** - * Cancels a proposal. - * @param _proposalId Unique identifier obtained by hashing proposal data. - * Emits a ProposalCanceled event + * @notice Cancels a proposal + * @param _proposalId Unique identifier obtained by hashing proposal data + * @notice Emits a ProposalCanceled event */ function cancel(uint256 _proposalId) external; /** - * Casts a vote on a proposal. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @return Vote power of the cast vote. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @return Vote power of the cast vote + * @notice Emits a VoteCast event */ function castVote(uint256 _proposalId, uint8 _support) external returns (uint256); /** - * Casts a vote on a proposal with a reason. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @param _reason Vote reason. - * @return Vote power of the cast vote. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal with a reason + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @param _reason Vote reason + * @return Vote power of the cast vote + * @notice Emits a VoteCast event */ function castVoteWithReason( uint256 _proposalId, @@ -112,13 +102,13 @@ interface IGovernor { ) external returns (uint256); /** - * Casts a vote on a proposal using the user cryptographic signature. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @param _v v part of the signature. - * @param _r r part of the signature. - * @param _s s part of the signature. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal using the user cryptographic signature + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @param _v v part of the signature + * @param _r r part of the signature + * @param _s s part of the signature + * @notice Emits a VoteCast event */ function castVoteBySig( uint256 _proposalId, @@ -129,84 +119,63 @@ interface IGovernor { ) external returns (uint256); /** - * Executes a successful proposal without execution parameters. - * @param _proposalId Id of the proposal. - * Emits a ProposalExecuted event. + * @notice Executes a successful proposal without execution parameters + * @param _description String description of the proposal + * @notice Emits a ProposalExecuted event */ - function execute(uint256 _proposalId) external; + function execute(string memory _description) external returns (uint256); /** - * Executes a successful proposal. - * @param _proposalId Id of the proposal. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * Emits a ProposalExecuted event. + * @notice Executes a successful proposal with execution parameters + * @param _targets Array of target addresses on which the calls are to be invoked + * @param _values Array of values with which the calls are to be invoked + * @param _calldatas Array of call data to be invoked + * @param _description String description of the proposal + * @notice Emits a ProposalExecuted event */ function execute( - uint256 _proposalId, address[] memory _targets, uint256[] memory _values, - bytes[] memory _calldatas - ) external payable; + bytes[] memory _calldatas, + string memory _description + ) external payable returns (uint256); /** - * Returns the current state of a proposal. - * @param _proposalId Id of the proposal. - * @return ProposalState enum. + * @notice Returns the current state of a proposal + * @param _proposalId Id of the proposal + * @return ProposalState enum */ function state(uint256 _proposalId) external view returns (ProposalState); /** - * Returns the vote power of a voter at a specific block number. - * @param _voter Address of the voter. - * @param _blockNumber The block number. - * @return Vote power of the voter at the block number. + * @notice Returns the vote power of a voter at a specific block number + * @param _voter Address of the voter + * @param _blockNumber The block number + * @return Vote power of the voter at the block number */ function getVotes(address _voter, uint256 _blockNumber) external view returns (uint256); /** - * Returns information if a voter has cast a vote on a specific proposal. - * @param _proposalId Id of the proposal. - * @param _voter Address of the voter. - * @return True if the voter has cast a vote on the proposal, and false otherwise. + * @notice Returns information if a voter has cast a vote on a specific proposal + * @param _proposalId Id of the proposal + * @param _voter Address of the voter + * @return True if the voter has cast a vote on the proposal, and false otherwise */ function hasVoted(uint256 _proposalId, address _voter) external view returns (bool); /** - * Returns proposal id determined by hashing proposal data. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * @param _description Description of the proposal. - * @return Proposal id. - */ - function getProposalId( - address[] memory _targets, - uint256[] memory _values, - bytes[] memory _calldatas, - string memory _description - ) external view returns (uint256); - - /** - * Returns the list of proposal ids. - */ - function getProposalIds() external view returns (uint256[] memory); - - /** - * Returns information of the specified proposal. - * @param _proposalId Id of the proposal. - * @return _proposer Address of the proposal submitter. - * @return _accept Type of the proposal - accept or reject. - * @return _votePowerBlock Block number used to determine the vote powers in voting process. - * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting. - * @return _voteEndTime End time (in seconds from epoch) of the proposal voting. - * @return _execStartTime Start time (in seconds from epoch) of the proposal execution window. - * @return _execEndTime End time (in seconds from epoch) of the proposal exectuion window. - * @return _thresholdConditionBIPS Percentage in BIPS of the total vote power required for proposal "quorum". - * @return _majorityConditionBIPS Percentage in BIPS of the proper relation between FOR and AGAINST votes. - * @return _circulatingSupply Circulating supply at votePowerBlock. - * @return _description Description of the proposal. + * @notice Returns information of the specified proposal + * @param _proposalId Id of the proposal + * @return _proposer Address of the proposal submitter + * @return _accept Type of the proposal - accept or reject + * @return _votePowerBlock Block number used to determine the vote powers in voting process + * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting + * @return _voteEndTime End time (in seconds from epoch) of the proposal voting + * @return _execStartTime Start time (in seconds from epoch) of the proposal execution window + * @return _execEndTime End time (in seconds from epoch) of the proposal exectuion window + * @return _thresholdConditionBIPS Percentage in BIPS of the total vote power required for proposal "quorum" + * @return _majorityConditionBIPS Percentage in BIPS of the proper relation between FOR and AGAINST votes + * @return _circulatingSupply Circulating supply at votePowerBlock */ function getProposalInfo( uint256 _proposalId @@ -222,20 +191,19 @@ interface IGovernor { uint256 _execEndTime, uint256 _thresholdConditionBIPS, uint256 _majorityConditionBIPS, - uint256 _circulatingSupply, - string memory _description + uint256 _circulatingSupply ); /** - * Returns votes (for, against) of the specified proposal. - * @param _proposalId Id of the proposal. - * @return _for Accumulated vote power for the proposal. - * @return _against Accumulated vote power against the proposal. + * @notice Returns votes (for, against) of the specified proposal + * @param _proposalId Id of the proposal + * @return _for Accumulated vote power for the proposal + * @return _against Accumulated vote power against the proposal */ function getProposalVotes( uint256 _proposalId ) - external view + external view returns ( uint256 _for, uint256 _against diff --git a/src/coston/IPollingFtso.sol b/src/coston/IPollingFtso.sol new file mode 100644 index 0000000..7bbf313 --- /dev/null +++ b/src/coston/IPollingFtso.sol @@ -0,0 +1,295 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IPollingFtso { + + /** + * @notice Struct holding the information about proposal properties + */ + struct Proposal { + string description; // description of the proposal + address proposer; // address of the proposer + bool canceled; // flag indicating if proposal has been canceled + uint256 voteStartTime; // start time of voting window (in seconds from epoch) + uint256 voteEndTime; // end time of voting window (in seconds from epoch) + uint256 thresholdConditionBIPS; // percentage in BIPS of the total vote power required for proposal "quorum" + uint256 majorityConditionBIPS; // percentage in BIPS of the proper relation between FOR and AGAINST votes + mapping(address => bool) isEligible; // flag if an address is eligible to cast a vote in a proposal + uint256 noOfEligibleMembers; // number of addresses that can vote in the proposal + } + + /** + * @notice Struct holding the information about proposal voting + */ + struct ProposalVoting { + uint256 againstVotePower; // accumulated vote power against the proposal + uint256 forVotePower; // accumulated vote power for the proposal + mapping(address => bool) hasVoted; // flag if a voter has cast a vote + } + + /** + * @notice Enum describing a proposal state + */ + enum ProposalState { + Canceled, + Pending, + Active, + Defeated, + Succeeded + } + + /** + * @notice Enum that determines vote (support) type + * @dev 0 = Against, 1 = For + */ + enum VoteType { + Against, + For + } + + /** + * @notice Event emitted when a proposal is created + */ + event FtsoProposalCreated( + uint256 indexed proposalId, + address proposer, + string description, + uint256 voteStartTime, + uint256 voteEndTime, + uint256 thresholdConditionBIPS, + uint256 majorityConditionBIPS, + address[] eligibleMembers + ); + + /** + * @notice Event emitted when a vote is cast + */ + event VoteCast( + address indexed voter, + uint256 indexed proposalId, + uint8 support, + uint256 forVotePower, + uint256 againstVotePower + ); + + /** + * @notice Event emitted when a proposal is canceled + */ + event ProposalCanceled(uint256 indexed proposalId); + + /** + * @notice Event emitted when parameters are set + */ + event ParametersSet( + uint256 votingDelaySeconds, + uint256 votingPeriodSeconds, + uint256 thresholdConditionBIPS, + uint256 majorityConditionBIPS, + uint256 proposalFeeValueWei, + uint256 addAfterRewardedEpochs, + uint256 addAfterNotChilledEpochs, + uint256 removeAfterNotRewardedEpochs, + uint256 removeAfterEligibleProposals, + uint256 removeAfterNonParticipatingProposals, + uint256 removeForDays + ); + + /** + * @notice Event emitted when management group member is added + */ + event ManagementGroupMemberAdded(address addedMember); + + /** + * @notice Event emitted when management group member is removed + */ + event ManagementGroupMemberRemoved(address removedMember); + + /** + * @notice Event emitted when maintainer is set + */ + event MaintainerSet(address newMaintainer); + + /** + * @notice Event emitted when proxy voter is set + */ + event ProxyVoterSet(address account, address proxyVoter); + + /** + * @notice Sets (or changes) contract's parameters. It is called after deployment of the contract + * and every time one of the parameters changes. + */ + function setParameters( + uint256 _votingDelaySeconds, + uint256 _votingPeriodSeconds, + uint256 _thresholdConditionBIPS, + uint256 _majorityConditionBIPS, + uint256 _proposalFeeValueWei, + uint256 _addAfterRewardedEpochs, + uint256 _addAfterNotChilledEpochs, + uint256 _removeAfterNotRewardedEpochs, + uint256 _removeAfterEligibleProposals, + uint256 _removeAfterNonParticipatingProposals, + uint256 _removeForDays + ) + external; + + /** + * @notice Cancels an existing proposal + * @param _proposalId Unique identifier of a proposal + * @notice Emits a ProposalCanceled event + */ + function cancel(uint256 _proposalId) external; + + /** + * @notice Creates a new proposal + * @param _description String description of the proposal + * @return _proposalId Unique identifier of the proposal + * @notice Emits a FtsoProposalCreated event + */ + function propose( + string memory _description + ) external payable returns (uint256); + + /** + * @notice Casts a vote on a proposal + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @notice Emits a VoteCast event + */ + function castVote(uint256 _proposalId, uint8 _support) external; + + /** + * @notice Changes list of management group members + * @param _providersToAdd Array of addresses to add to the list + * @param _providersToRemove Array of addresses to remove from the list + * @notice This operation can only be performed through a maintainer + * (mostly used for manually adding KYCed providers) + */ + function changeManagementGroupMembers( + address[] memory _providersToAdd, + address[] memory _providersToRemove + ) external; + + /** + * @notice Sets a proxy voter for data provider (i.e. address that can vote in his name) + * @param _proxyVoter Address to register as a proxy (use address(0) to remove proxy) + * @notice Emits a ProxyVoterSet event + */ + function setProxyVoter(address _proxyVoter) external; + + /** + * @notice Adds msg.sender to the management group + */ + function addMember() external; + + /** + * @notice Removes member from the management group + * @param _account Account to remove from the management group + */ + function removeMember(address _account) external; + + /** + * @notice Returns the current state of a proposal + * @param _proposalId Id of the proposal + * @return ProposalState enum + */ + function state(uint256 _proposalId) external view returns (ProposalState); + + /** + * @notice Returns whether a voter has cast a vote on a specific proposal + * @param _proposalId Id of the proposal + * @param _voter Address of the voter + * @return True if the voter has cast a vote on the proposal, and false otherwise + */ + function hasVoted(uint256 _proposalId, address _voter) external view returns (bool); + + /** + * @notice Returns information about the specified proposal + * @param _proposalId Id of the proposal + * @return _description Description of the proposal + * @return _proposer Address of the proposal submitter + * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting + * @return _voteEndTime End time (in seconds from epoch) of the proposal voting + * @return _thresholdConditionBIPS Total number of cast votes, as a percentage in BIPS of the + total vote power, required for the proposal to pass (quorum) + * @return _majorityConditionBIPS Number of FOR votes, as a percentage in BIPS of the + total cast votes, requires for the proposal to pass + * @return _noOfEligibleMembers Number of members that are eligible to vote in the specified proposal + */ + function getProposalInfo( + uint256 _proposalId + ) + external view + returns ( + string memory _description, + address _proposer, + uint256 _voteStartTime, + uint256 _voteEndTime, + uint256 _thresholdConditionBIPS, + uint256 _majorityConditionBIPS, + uint256 _noOfEligibleMembers + ); + + /** + * @notice Returns the description string that was supplied when the specified proposal was created + * @param _proposalId Id of the proposal + * @return _description Description of the proposal + */ + function getProposalDescription(uint256 _proposalId) external view + returns (string memory _description); + + /** + * @notice Returns id and description of the last created proposal + * @return _proposalId Id of the last proposal + * @return _description Description of the last proposal + */ + function getLastProposal() external view + returns ( uint256 _proposalId, string memory _description); + + /** + * @notice Returns number of votes for and against the specified proposal + * @param _proposalId Id of the proposal + * @return _for Accumulated vote power for the proposal + * @return _against Accumulated vote power against the proposal + */ + function getProposalVotes( + uint256 _proposalId + ) + external view + returns ( + uint256 _for, + uint256 _against + ); + + /** + * @notice Returns list of current management group members + * @return _list List of management group members + */ + function getManagementGroupMembers() external view returns (address[] memory _list); + + /** + * @notice Returns whether an account can create proposals + * @notice An address can make proposals if it is a member of the management group, + * one of their proxies or the maintainer of the contract + * @param _account Address of a queried account + * @return True if a queried account can propose, false otherwise + */ + function canPropose(address _account) external view returns (bool); + + /** + * @notice Returns whether an account can vote for a given proposal + * @param _account Address of the queried account + * @param _proposalId Id of the queried proposal + * @return True if account is eligible to vote, and false otherwise + */ + function canVote(address _account, uint256 _proposalId) external view returns (bool); + + /** + * @notice Returns whether an account is member of the management group + * @param _account Address of the queried account + * @return True if the queried account is member, false otherwise + */ + function isMember(address _account) external view returns (bool); +} diff --git a/src/coston/IPriceSubmitter.sol b/src/coston/IPriceSubmitter.sol index 781735f..1e6ebd1 100644 --- a/src/coston/IPriceSubmitter.sol +++ b/src/coston/IPriceSubmitter.sol @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./genesis/interface/IFtsoGenesis.sol"; -import "./genesis/interface/IFtsoRegistryGenesis.sol"; +import "./genesis/interfaces/IFtsoGenesis.sol"; +import "./genesis/interfaces/IFtsoRegistryGenesis.sol"; interface IPriceSubmitter { /** diff --git a/src/coston/IRNat.sol b/src/coston/IRNat.sol index b710fd2..76bf5bc 100644 --- a/src/coston/IRNat.sol +++ b/src/coston/IRNat.sol @@ -3,7 +3,7 @@ pragma solidity >=0.7.6 <0.9; import "./IRNatAccount.sol"; import "./IWNat.sol"; -import "@openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol"; +import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IRNat is IERC20Metadata { diff --git a/src/coston/IRNatAccount.sol b/src/coston/IRNatAccount.sol index d8c465d..fea1340 100644 --- a/src/coston/IRNatAccount.sol +++ b/src/coston/IRNatAccount.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IRNat.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRNatAccount { diff --git a/src/coston/ITransferFees.sol b/src/coston/ITransferFees.sol deleted file mode 100644 index bdbbb1d..0000000 --- a/src/coston/ITransferFees.sol +++ /dev/null @@ -1,115 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.7.6 <0.9; - - -/** - * FAsset transfer (trailing) fees. - */ -interface ITransferFees { - /** - * An agent has claimed their share of transfer fees. - */ - event TransferFeesClaimed( - address indexed agentVault, - address recipient, - uint256 agentClaimedUBA, - uint256 poolClaimedUBA, - uint256 remainingUnclaimedEpochs); - - /** - * Transfer fee will change at timestamp `scheduledAt`. - */ - event TransferFeeChangeScheduled( - uint256 nextTransferFeeMillionths, - uint256 scheduledAt); - - /** - * Claim FAsset transfer fees by an agent. - * NOTE: may only be called by the agent vault owner - * @param _agentVault the agent vault for which to claim - * @param _recipient the account that will receive agent's share of fasset fees - * @param _maxEpochsToClaim limit the number of epochs to claim, to avoid using too much gas - * @return _agentClaimedUBA agent's share of total claimed amount in FAsset UBA - * @return _poolClaimedUBA pool share of total claimed amount in FAsset UBA - * @return _remainingUnclaimedEpochs nonzero when _maxEpochsToClaim is smaller then the number of unclaimed epochs - */ - function claimTransferFees(address _agentVault, address _recipient, uint256 _maxEpochsToClaim) - external - returns (uint256 _agentClaimedUBA, uint256 _poolClaimedUBA, uint256 _remainingUnclaimedEpochs); - - function currentTransferFeeEpoch() - external view - returns (uint256); - - function firstClaimableTransferFeeEpoch() - external view - returns (uint256); - - function agentUnclaimedTransferFeeEpochs(address _agentVault) - external view - returns (uint256 _first, uint256 _count); - - function agentTransferFeeShare(address _agentVault, uint256 _maxEpochsToClaim) - external view - returns (uint256 _feeShareUBA); - - function agentTransferFeeShareForEpoch(address _agentVault, uint256 _epoch) - external view - returns (uint256); - - function transferFeeMillionths() - external view - returns (uint256); - - function setTransferFeeMillionths(uint256 _value, uint256 _scheduledAt) - external; - - //////////////////////////////////////////////////////////////////////////////////// - // Internal methods - - function fassetTransferFeePaid(uint256 _fee) - external; - - function initAgentsMintingHistory(address[] calldata _agentVaults) - external; - - //////////////////////////////////////////////////////////////////////////////////// - // Methods for testing and inspection - - struct TransferFeeSettings { - uint256 transferFeeMillionths; - uint256 firstEpochStartTs; - uint256 epochDuration; - uint256 maxUnexpiredEpochs; - uint256 firstClaimableEpoch; - } - - struct TransferFeeEpochData { - uint256 startTs; - uint256 endTs; - uint256 totalFees; - uint256 claimedFees; - bool claimable; - bool expired; - } - - struct TransferFeeCalculationDataForAgent { - uint256 totalFees; - uint256 cumulativeMinted; - uint256 totalCumulativeMinted; - bool claimable; - bool claimed; - } - - function transferFeeSettings() - external view - returns (TransferFeeSettings memory); - - function transferFeeEpochData(uint256 _epoch) - external view - returns (TransferFeeEpochData memory); - - function transferFeeCalculationDataForAgent(address _agentVault, uint256 _epoch) - external view - returns (TransferFeeCalculationDataForAgent memory); -} diff --git a/src/coston/IVPToken.sol b/src/coston/IVPToken.sol index c9cf5b2..21593c0 100644 --- a/src/coston/IVPToken.sol +++ b/src/coston/IVPToken.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import {IERC20} from "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IGovernanceVotePower} from "./IGovernanceVotePower.sol"; import {IVPContractEvents} from "./IVPContractEvents.sol"; diff --git a/src/coston/IVoterPreRegistry.sol b/src/coston/IVoterPreRegistry.sol index c7d09c9..6e0a524 100644 --- a/src/coston/IVoterPreRegistry.sol +++ b/src/coston/IVoterPreRegistry.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./protocol/interface/IIVoterRegistry.sol"; +import "./protocol/interfaces/IIVoterRegistry.sol"; interface IVoterPreRegistry { diff --git a/src/coston/IWNat.sol b/src/coston/IWNat.sol index ade3c7a..59cee8e 100644 --- a/src/coston/IWNat.sol +++ b/src/coston/IWNat.sol @@ -1,42 +1,34 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IVPToken.sol"; -import "./token/interface/IICleanable.sol"; - - -/** - * @title Wrapped Native token - * Accept native token deposits and mint ERC20 WNAT (wrapped native) tokens 1-1. - */ -interface IWNat is IVPToken, IICleanable { +interface IWNat { /** - * Deposit Native and mint wNat ERC20. + * @notice Deposit native token and mint WNAT ERC20. */ function deposit() external payable; /** - * Deposit Native from msg.sender and mints WNAT ERC20 to recipient address. - * @param recipient An address to receive minted WNAT. + * @notice Withdraw native token and burn WNAT ERC20. + * @param _amount The amount to withdraw. */ - function depositTo(address recipient) external payable; - + function withdraw(uint256 _amount) external; + /** - * Withdraw Native and burn WNAT ERC20. - * @param amount The amount to withdraw. + * @notice Deposit native token from msg.sender and mint WNAT ERC20. + * @param _recipient An address to receive minted WNAT. */ - function withdraw(uint256 amount) external; - + function depositTo(address _recipient) external payable; + /** - * Withdraw WNAT from an owner and send native tokens to msg.sender given an allowance. - * @param owner An address spending the Native tokens. - * @param amount The amount to spend. + * @notice Withdraw WNAT from an owner and send NAT to msg.sender given an allowance. + * @param _owner An address spending the native tokens. + * @param _amount The amount to spend. * * Requirements: * - * - `owner` must have a balance of at least `amount`. - * - the caller must have allowance for `owners`'s tokens of at least - * `amount`. + * - `_owner` must have a balance of at least `_amount`. + * - the caller must have allowance for `_owners`'s tokens of at least + * `_amount`. */ - function withdrawFrom(address owner, uint256 amount) external; + function withdrawFrom(address _owner, uint256 _amount) external; } diff --git a/src/coston/IWeb2JsonVerification.sol b/src/coston/IWeb2JsonVerification.sol index 8369e1a..d0a5d25 100644 --- a/src/coston/IWeb2JsonVerification.sol +++ b/src/coston/IWeb2JsonVerification.sol @@ -4,5 +4,5 @@ pragma solidity >=0.7.6 <0.9; import "./IWeb2Json.sol"; interface IWeb2JsonVerification { - function verifyJsonApi(IWeb2Json.Proof calldata _proof) external view returns (bool _proved); + function verifyWeb2Json(IWeb2Json.Proof calldata _proof) external view returns (bool _proved); } diff --git a/src/songbird/addressUpdater/interface/IIAddressUpdatable.sol b/src/coston/addressUpdater/interfaces/IIAddressUpdatable.sol similarity index 100% rename from src/songbird/addressUpdater/interface/IIAddressUpdatable.sol rename to src/coston/addressUpdater/interfaces/IIAddressUpdatable.sol diff --git a/src/songbird/addressUpdater/interface/IIAddressUpdater.sol b/src/coston/addressUpdater/interfaces/IIAddressUpdater.sol similarity index 100% rename from src/songbird/addressUpdater/interface/IIAddressUpdater.sol rename to src/coston/addressUpdater/interfaces/IIAddressUpdater.sol diff --git a/src/songbird/assetRegistry/interface/IIERC20WithMetadata.sol b/src/coston/assetRegistry/interfaces/IIERC20WithMetadata.sol similarity index 94% rename from src/songbird/assetRegistry/interface/IIERC20WithMetadata.sol rename to src/coston/assetRegistry/interfaces/IIERC20WithMetadata.sol index 691278b..68a9631 100644 --- a/src/songbird/assetRegistry/interface/IIERC20WithMetadata.sol +++ b/src/coston/assetRegistry/interfaces/IIERC20WithMetadata.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import { IERC20 } from "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** diff --git a/src/songbird/assetRegistry/interface/IIFlareAssetRegistry.sol b/src/coston/assetRegistry/interfaces/IIFlareAssetRegistry.sol similarity index 100% rename from src/songbird/assetRegistry/interface/IIFlareAssetRegistry.sol rename to src/coston/assetRegistry/interfaces/IIFlareAssetRegistry.sol diff --git a/src/songbird/assetRegistry/interface/IIFlareAssetRegistryProvider.sol b/src/coston/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol similarity index 100% rename from src/songbird/assetRegistry/interface/IIFlareAssetRegistryProvider.sol rename to src/coston/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol diff --git a/src/coston/customFeeds/interface/IICustomFeed.sol b/src/coston/customFeeds/interfaces/IICustomFeed.sol similarity index 100% rename from src/coston/customFeeds/interface/IICustomFeed.sol rename to src/coston/customFeeds/interfaces/IICustomFeed.sol diff --git a/src/coston2/userInterfaces/data/AgentInfo.sol b/src/coston/data/AgentInfo.sol similarity index 89% rename from src/coston2/userInterfaces/data/AgentInfo.sol rename to src/coston/data/AgentInfo.sol index cace872..d105789 100644 --- a/src/coston2/userInterfaces/data/AgentInfo.sol +++ b/src/coston/data/AgentInfo.sol @@ -1,189 +1,143 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; - +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AgentInfo { enum Status { // agent is operating normally NORMAL, - // agent in collateral call band - CCB, // liquidation due to collateral ratio - ends when agent is healthy LIQUIDATION, // illegal payment liquidation - always liquidates all and then agent must close vault FULL_LIQUIDATION, // agent announced destroy, cannot mint again; all existing mintings have been redeemed before - DESTROYING + DESTROYING, + // agent has been destroyed, cannot do anything except return info + // owner can still withdraw tokens from the vault + DESTROYED } struct Info { // Current agent's status. AgentInfo.Status status; - // Agent vault owner's management address, used for occasional administration. // Immutable. address ownerManagementAddress; - // Agent vault owner's work address, used for automatic operations. // Can be changed by a call from the owner's management address. address ownerWorkAddress; - // Agent's collateral pool address address collateralPool; - // Agent collateral pool's pool token address address collateralPoolToken; - // Underlying address as string - to be used for minting payments. // For most other purposes, you use underlyingAddressHash, which is `keccak256(underlyingAddressString)`. string underlyingAddressString; - // If true, anybody can mint against this agent. // If false, the agent can only self-mint. // Once minted, all redemption tickets go to the same (public) queue, regardless of this flag. bool publiclyAvailable; - // Current fee the agent charges for minting (paid in underlying currency). uint256 feeBIPS; - // Share of the minting fee that goes to the pool as percentage of the minting fee. // This share of fee is minted as f-assets and belongs to the pool. uint256 poolFeeShareBIPS; - // The token identifier of the agent's current vault collateral. // Token identifier can be used to call AssetManager.getCollateralType(). IERC20 vaultCollateralToken; - // Amount, set by agent, at which locked and free collateral are calculated for new mintings. // For agent's vault collateral. uint256 mintingVaultCollateralRatioBIPS; - // Amount, set by agent, at which locked and free collateral are calculated for new mintings. // For pool collateral. uint256 mintingPoolCollateralRatioBIPS; - // The maximum number of lots that the agent can mint. // This can change any moment due to minting, redemption or price changes. uint256 freeCollateralLots; - // Total amount of vault collateral in agent's vault. uint256 totalVaultCollateralWei; - // Free collateral, available for new mintings. // Note: this value doesn't tell you anything about agent being near liquidation, since it is // calculated at agentMinCollateralRatio, not minCollateralRatio. // Use collateralRatioBIPS to see whether the agent is near liquidation. uint256 freeVaultCollateralWei; - // The actual agent's collateral ratio, as it is used in liquidation. // For calculation, the system checks both FTSO prices and trusted provider's prices and uses // the ones that give higher ratio. uint256 vaultCollateralRatioBIPS; - // The token identifier of the agent's current vault collateral. // Token identifier can be used to call AssetManager.getCollateralType(). IERC20 poolWNatToken; - // Total amount of NAT collateral in agent's pool. uint256 totalPoolCollateralNATWei; - // Free NAT pool collateral (see vault collateral for details). uint256 freePoolCollateralNATWei; - // The actual pool collateral ratio (see vault collateral for details). uint256 poolCollateralRatioBIPS; - // The amount of pool tokens that belong to agent's vault. This limits the amount of possible // minting: to be able to mint, the NAT value of all backed fassets together with new ones, times // mintingPoolHoldingsRequiredBIPS, must be smaller than the agent's pool tokens amount converted to NAT. // Note: the amount of agent's pool tokens only affects minting, not liquidation. uint256 totalAgentPoolTokensWei; - // The amount of vault collateral that will be withdrawn by the agent. uint256 announcedVaultCollateralWithdrawalWei; - // The amount of pool tokens that will be withdrawn by the agent. uint256 announcedPoolTokensWithdrawalWei; - // Free agent's pool tokens. uint256 freeAgentPoolTokensWei; - // Total amount of minted f-assets. uint256 mintedUBA; - // Total amount reserved for ongoing mintings. uint256 reservedUBA; - // Total amount of ongoing redemptions. uint256 redeemingUBA; - // Total amount of ongoing redemptions that lock the pool collateral. // (In pool self-close exits, pool collateral is not locked. So the amount of locked // collateral in the pool can be less than the amount of locked vault collateral.) uint256 poolRedeemingUBA; - // Total amount of dust (unredeemable minted f-assets). // Note: dustUBA is part of mintedUBA, so the amount of redeemable f-assets is calculated as // `mintedUBA - dustUBA` uint256 dustUBA; - // Liquidation info - // If the agent is in CCB or if current liquidation started in CCB, the time agent entered CCB (otherwise 0). - uint256 ccbStartTimestamp; - // If the agent is in LIQUIDATION or FULL_LIQUIDATION, the time agent entered liquidation. - // If the agent is in CCB, the time agent will enter liquidation (in future). // If status is neither of that, returns 0. // Can be used for calculating current liquidation premium, which depends on time since liquidation started. uint256 liquidationStartTimestamp; - // When agent is in liquidation, this is the amount o FAssets that need to be liquidated to bring the agent's // position to safety. When performing liquidation, only up to this amount of FAssets will be liquidated. // If not in liquidation, this value is 0. // Since the liquidation state may need to be upgraded by, call `startLiquidation` before // `getAgentInfo` to get the value that will actually be used in liquidation. uint256 maxLiquidationAmountUBA; - // When agent is in liquidation, this is the factor (in BIPS) of the converted value of the liquidated // FAssets paid by the vault collateral. If not in liquidation, this value is 0. uint256 liquidationPaymentFactorVaultBIPS; - // When agent is in liquidation, this is the factor (in BIPS) of the converted value of the liquidated // FAssets paid by the pool collateral. If not in liquidation, this value is 0. uint256 liquidationPaymentFactorPoolBIPS; - // Total underlying balance (backing and free). int256 underlyingBalanceUBA; - // The minimum underlying balance that has to be held by the agent. Below this, agent is liquidated. uint256 requiredUnderlyingBalanceUBA; - // Underlying balance not backing anything (can be used for gas/fees or withdrawn after announcement). int256 freeUnderlyingBalanceUBA; - // Current underlying withdrawal announcement (or 0 if no announcement was made). uint256 announcedUnderlyingWithdrawalId; - // The factor set by the agent to multiply the price at which agent buys f-assets from pool // token holders on self-close exit (when requested or the redeemed amount is less than 1 lot). uint256 buyFAssetByAgentFactorBIPS; - // The minimum collateral ratio above which a staker can exit the pool // (this is CR that must be left after exit). // Must be higher than system minimum collateral ratio for pool collateral. uint256 poolExitCollateralRatioBIPS; - - // The CR below which it is possible to enter the pool at discounted rate (to prevent liquidation). - // Must be higher than system minimum collateral ratio for pool collateral. - uint256 poolTopupCollateralRatioBIPS; - - // The discount to pool token price when entering and pool CR is below pool topup CR. - uint256 poolTopupTokenPriceFactorBIPS; - - // Agent's handshake type - minting or redeeming can be rejected. - // 0 - no verification, 1 - manual verification, ... - uint256 handshakeType; + // The redemption fee share paid to the pool (as FAssets). + // In redemption dominated situations (when agent requests return from core vault to earn + // from redemption fees), pool can get some share to make it sustainable for pool users. + // NOTE: the pool fee share is locked at the redemption request time, but is charged at the redemption + // confirmation time. If agent uses all the redemption fee for transaction fees, this could make the + // agent's free underlying balance negative. + uint256 redemptionPoolFeeShareBIPS; } } diff --git a/src/coston2/userInterfaces/data/AgentSettings.sol b/src/coston/data/AgentSettings.sol similarity index 79% rename from src/coston2/userInterfaces/data/AgentSettings.sol rename to src/coston/data/AgentSettings.sol index cded4c4..98cb936 100644 --- a/src/coston2/userInterfaces/data/AgentSettings.sol +++ b/src/coston/data/AgentSettings.sol @@ -1,60 +1,48 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; - +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AgentSettings { struct Data { // The token used as vault collateral. Must be one of the tokens obtained by `getCollateralTypes()`, // with class VAULT. IERC20 vaultCollateralToken; - // The suffix to pool token name and symbol that identifies new vault's collateral pool token. // Must be unique within an asset manager. string poolTokenSuffix; - // Minting fee. Normally charged to minters for publicly available agents, but must be set // also for self-minting agents to pay part of it to collateral pool. // Fee is paid in underlying currency along with backing assets. uint256 feeBIPS; - // Share of the minting fee that goes to the pool as percentage of the minting fee. // This share of fee is minted as f-assets and belongs to the pool. uint256 poolFeeShareBIPS; - // Collateral ratio at which we calculate locked collateral and collateral available for minting. // Agent may set own value for minting collateral ratio on creation. // The value must always be greater than system minimum collateral ratio for vault collateral. // Warning: having this value near global min collateral ratio can quickly lead to liquidation for public // agents, so it is advisable to set it significantly higher. uint256 mintingVaultCollateralRatioBIPS; - // Collateral ratio at which we calculate locked collateral and collateral available for minting. // Agent may set own value for minting collateral ratio on creation. // The value must always be greater than system minimum collateral ratio for pool collateral. // Warning: having this value near global min collateral ratio can quickly lead to liquidation for public // agents, so it is advisable to set it significantly higher. uint256 mintingPoolCollateralRatioBIPS; - // The factor set by the agent to multiply the price at which agent buys f-assets from pool // token holders on self-close exit (when requested or the redeemed amount is less than 1 lot). uint256 buyFAssetByAgentFactorBIPS; - // The minimum collateral ratio above which a staker can exit the pool // (this is CR that must be left after exit). // Must be higher than system minimum collateral ratio for pool collateral. uint256 poolExitCollateralRatioBIPS; - - // The CR below which it is possible to enter the pool at discounted rate (to prevent liquidation). - // Must be higher than system minimum collateral ratio for pool collateral. - uint256 poolTopupCollateralRatioBIPS; - - // The discount to pool token price when entering and pool CR is below pool topup CR. - uint256 poolTopupTokenPriceFactorBIPS; - - // Agent's handshake type - minting or redeeming can be rejected. - // 0 - no verification, 1 - manual verification, ... - uint256 handshakeType; + // The redemption fee share paid to the pool (as FAssets). + // In redemption dominated situations (when agent requests return from core vault to earn + // from redemption fees), pool can get some share to make it sustainable for pool users. + // NOTE: the pool fee share is locked at the redemption request time, but is charged at the redemption + // confirmation time. If agent uses all the redemption fee for transaction fees, this could make the + // agent's free underlying balance negative. + uint256 redemptionPoolFeeShareBIPS; } } diff --git a/src/songbird/userInterfaces/data/AssetManagerSettings.sol b/src/coston/data/AssetManagerSettings.sol similarity index 89% rename from src/songbird/userInterfaces/data/AssetManagerSettings.sol rename to src/coston/data/AssetManagerSettings.sol index 7832317..831efbe 100644 --- a/src/songbird/userInterfaces/data/AssetManagerSettings.sol +++ b/src/coston/data/AssetManagerSettings.sol @@ -16,17 +16,17 @@ library AssetManagerSettings { address fAsset; // Factory for creating new agent vaults. - // Type: IAgentVaultFactory + // Type: IIAgentVaultFactory // timelocked address agentVaultFactory; // Factory for creating new agent collateral pools. - // Type: ICollateralPoolFactory + // Type: IICollateralPoolFactory // timelocked address collateralPoolFactory; // Factory for creating new agent collateral pool tokens. - // Type: ICollateralPoolTokenFactory + // Type: IICollateralPoolTokenFactory // timelocked address collateralPoolTokenFactory; @@ -39,7 +39,7 @@ library AssetManagerSettings { // This can be `address(0)`, in which case no whitelist checks are done. // Type: IWhitelist // timelocked - address whitelist; + address __whitelist; // only storage placeholder // If set, the owner address registry contains a list of allowed agent owner's // management addresses and mappings from management to work address. @@ -52,8 +52,7 @@ library AssetManagerSettings { // changed via address updater address fdcVerification; - // The address where burned NAt is sent. - // (E.g. collateral reservation fee is burned on successful minting.) + // The address where burned NAT is sent. // immutable address payable burnAddress; @@ -107,12 +106,12 @@ library AssetManagerSettings { uint64 lotSizeAMG; // The percentage of minted f-assets that the agent must hold in his underlying address. - uint16 minUnderlyingBackingBIPS; + uint16 __minUnderlyingBackingBIPS; // only storage placeholder // for some chains (e.g. Ethereum) we require that agent proves that underlying address is an EOA address // this must be done by presenting a payment proof from that address // immutable - bool requireEOAAddressProof; + bool __requireEOAAddressProof; // only storage placeholder // Maximum minted amount of the f-asset. // rate-limited @@ -149,7 +148,7 @@ library AssetManagerSettings { // This is the part of redemption factor paid from agent's pool collateral. // rate-limited - uint32 redemptionDefaultFactorPoolBIPS; + uint32 __redemptionDefaultFactorPoolBIPS; // only storage placeholder // If the agent or redeemer becomes unresponsive, we still need payment or non-payment confirmations // to be presented eventually to properly track agent's underlying balance. @@ -189,7 +188,7 @@ library AssetManagerSettings { // Agent can remain in CCB for this much time, after that liquidation starts automatically. // rate-limited - uint64 ccbTimeSeconds; + uint64 __ccbTimeSeconds; // only storage placeholder // Amount of seconds (typically 1 day) that the payment/non-payment proofs must be available. // This setting is used in `unstickMinting` and `finishRedemptionWithoutPayment` to prove that the time when @@ -204,23 +203,22 @@ library AssetManagerSettings { // Ratio at which the agents can buy back their collateral when f-asset is terminated. // Typically a bit more than 1 to incentivize agents to buy f-assets and self-close instead. // immutable - uint64 buybackCollateralFactorBIPS; + uint64 __buybackCollateralFactorBIPS; // only storage placeholder // Minimum time that has to pass between underlying withdrawal announcement and the confirmation. // Any value is ok, but higher values give more security against multiple announcement attack by a miner. // Shouldn't be much bigger than Flare data connector response time, so that payments can be confirmed without // extra wait. Should be smaller than confirmationByOthersAfterSeconds (e.g. less than 1 hour). // rate-limited - uint64 announcedUnderlyingConfirmationMinSeconds; + uint64 __announcedUnderlyingConfirmationMinSeconds; // Minimum time from the moment token is deprecated to when it becomes invalid and agents still using // it as vault collateral get liquidated. // timelocked uint64 tokenInvalidationTimeMinSeconds; - // On some rare occasions (stuck minting, locked fassets after termination), the agent has to unlock - // collateral. For this, part of collateral corresponding to FTSO asset value is burned and the rest - // is released. + // On some rare occasions (stuck minting), the agent has to unlock collateral. + // For this, part of collateral corresponding to FTSO asset value is burned and the rest is released. // However, we cannot burn typical vault collateral (stablecoins), so the agent must buy them for NAT // at FTSO price multiplied with this factor (should be a bit above 1) and then we burn the NATs. // timelocked @@ -239,10 +237,10 @@ library AssetManagerSettings { // rate-limited uint64 agentMintingCRChangeTimelockSeconds; - // Amount of seconds that have to pass between agent-set settings for pool exit and topup - // (exit CR, topup CR, topup bonus) change announcement and execution. + // Amount of seconds that have to pass between agent-set settings for pool exit collateral ratio + // change announcement and execution. // rate-limited - uint64 poolExitAndTopupChangeTimelockSeconds; + uint64 poolExitCRChangeTimelockSeconds; // Amount of seconds that an agent is allowed to execute an update once it is allowed. // rate-limited @@ -283,31 +281,31 @@ library AssetManagerSettings { // The amount of time after which the collateral reservation can be cancelled if the // handshake is not completed. // rate-limited - uint64 cancelCollateralReservationAfterSeconds; + uint64 __cancelCollateralReservationAfterSeconds; // only storage placeholder // The amount of collateral reservation fee returned to the minter in case of rejection or cancellation. // Expressed in BIPS, e.g. 9500 for factor of 0.95, max 10000 for factor of 1.0. // rate-limited - uint16 rejectOrCancelCollateralReservationReturnFactorBIPS; + uint16 __rejectOrCancelCollateralReservationReturnFactorBIPS; // only storage placeholder // Time window inside which the agent can reject the redemption request. // rate-limited - uint64 rejectRedemptionRequestWindowSeconds; + uint64 __rejectRedemptionRequestWindowSeconds; // only storage placeholder // Time window inside which the agent can take over the redemption request from another agent // that has rejected it. // rate-limited - uint64 takeOverRedemptionRequestWindowSeconds; + uint64 __takeOverRedemptionRequestWindowSeconds; // only storage placeholder // On redemption rejection, without take over, redeemer is compensated with // redemption value recalculated in flare/sgb times redemption failure factor. // Expressed in BIPS, e.g. 12000 for factor of 1.2. // This is the part of factor paid from agent's vault collateral. // rate-limited - uint32 rejectedRedemptionDefaultFactorVaultCollateralBIPS; + uint32 __rejectedRedemptionDefaultFactorVaultCollateralBIPS; // only storage placeholder // This is the part of rejected redemption factor paid from agent's pool collateral. // rate-limited - uint32 rejectedRedemptionDefaultFactorPoolBIPS; + uint32 __rejectedRedemptionDefaultFactorPoolBIPS; // only storage placeholder } } diff --git a/src/coston2/userInterfaces/data/AvailableAgentInfo.sol b/src/coston/data/AvailableAgentInfo.sol similarity index 95% rename from src/coston2/userInterfaces/data/AvailableAgentInfo.sol rename to src/coston/data/AvailableAgentInfo.sol index 0d90a67..29510f1 100644 --- a/src/coston2/userInterfaces/data/AvailableAgentInfo.sol +++ b/src/coston/data/AvailableAgentInfo.sol @@ -1,31 +1,24 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./AgentInfo.sol"; - +import {AgentInfo} from "./AgentInfo.sol"; library AvailableAgentInfo { struct Data { // Agent vault address. address agentVault; - // The management address of the agent vault's owner. address ownerManagementAddress; - // Agent's minting fee in BIPS. uint256 feeBIPS; - // Minimum agent vault collateral ratio needed for minting. uint256 mintingVaultCollateralRatioBIPS; - // Minimum pool collateral ratio needed for minting. uint256 mintingPoolCollateralRatioBIPS; - // The number of lots that can be minted by this agent. // Note: the value is only informative since it can can change at any time // due to price changes, reservation, minting, redemption, or even lot size change. uint256 freeCollateralLots; - // The agent status, as for getAgentInfo(). AgentInfo.Status status; } diff --git a/src/songbird/userInterfaces/data/CollateralReservationInfo.sol b/src/coston/data/CollateralReservationInfo.sol similarity index 75% rename from src/songbird/userInterfaces/data/CollateralReservationInfo.sol rename to src/coston/data/CollateralReservationInfo.sol index 348bdba..65c3595 100644 --- a/src/songbird/userInterfaces/data/CollateralReservationInfo.sol +++ b/src/coston/data/CollateralReservationInfo.sol @@ -3,6 +3,13 @@ pragma solidity >=0.7.6 <0.9; library CollateralReservationInfo { + enum Status { + ACTIVE, // the minting process hasn't finished yet + SUCCESSFUL, // the payment has been confirmed and the FAssets minted + DEFAULTED, // the payment has defaulted and the agent received the collateral reservation fee + EXPIRED // the confirmation time has expired and the agent called unstickMinting + } + struct Data { // The id used for executing or defaulting the minting. uint64 collateralReservationId; @@ -30,10 +37,10 @@ library CollateralReservationInfo { // Part of the fee is goes to the pool and the rest to the agent vault as WNAT. uint128 reservationFeeNatWei; - // Proportion of the mintingFeeUBA and reservationFeeNatWei that belogs to the collateral pool. + // Proportion of the mintingFeeUBA and reservationFeeNatWei that belongs to the collateral pool. uint16 poolFeeShareBIPS; - // The underlying block (approximate - as known by the asset manager) when the reservation occured. + // The underlying block (approximate - as known by the asset manager) when the reservation occurred. uint64 firstUnderlyingBlock; // The last underlying block and timestamp for redemption payment. Redemption is defaulted if @@ -45,14 +52,10 @@ library CollateralReservationInfo { // (Only minter, agent or executor may execute the minting.) address executor; - // The fee in NAT that the executor receives if they successfuly execute the minting. + // The fee in NAT that the executor receives if they successfully execute the minting. uint256 executorFeeNatWei; - // If non-zero, the agent has started the handshake process. - uint64 handshakeStartTimestamp; - - // Merkle root of the list of addresses from which the minter is going to deposit the underlying assets - // (only needed when handshake is enabled for the agent). - bytes32 sourceAddressesRoot; + // If the minting process has finished, indication of success/default. Otherwise ACTIVE. + CollateralReservationInfo.Status status; } } diff --git a/src/coston2/userInterfaces/data/CollateralType.sol b/src/coston/data/CollateralType.sol similarity index 85% rename from src/coston2/userInterfaces/data/CollateralType.sol rename to src/coston/data/CollateralType.sol index 2220965..711b4a1 100644 --- a/src/coston2/userInterfaces/data/CollateralType.sol +++ b/src/coston/data/CollateralType.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library CollateralType { @@ -45,11 +45,6 @@ library CollateralType { // Minimum collateral ratio for healthy agents. uint256 minCollateralRatioBIPS; - // Minimum collateral ratio for agent in CCB (Collateral call band). - // If the agent's collateral ratio is less than this, skip the CCB and go straight to liquidation. - // A bit smaller than minCollateralRatioBIPS. - uint256 ccbMinCollateralRatioBIPS; - // Minimum collateral ratio required to get agent out of liquidation. // Will always be greater than minCollateralRatioBIPS. uint256 safetyMinCollateralRatioBIPS; diff --git a/src/coston2/userInterfaces/data/RedemptionRequestInfo.sol b/src/coston/data/RedemptionRequestInfo.sol similarity index 77% rename from src/coston2/userInterfaces/data/RedemptionRequestInfo.sol rename to src/coston/data/RedemptionRequestInfo.sol index 83793a3..e850ec1 100644 --- a/src/coston2/userInterfaces/data/RedemptionRequestInfo.sol +++ b/src/coston/data/RedemptionRequestInfo.sol @@ -4,8 +4,13 @@ pragma solidity >=0.7.6 <0.9; library RedemptionRequestInfo { enum Status { - ACTIVE, - DEFAULTED + ACTIVE, // waiting for confirmation/default + DEFAULTED_UNCONFIRMED, // default called, failed or late payment can still be confirmed + // final statuses - there can be no valid payment for this redemption anymore + SUCCESSFUL, // successful payment confirmed + DEFAULTED_FAILED, // payment failed (default was paid) + BLOCKED, // payment blocked + REJECTED // redemption request rejected due to invalid redeemer's address } struct Data { @@ -39,7 +44,7 @@ library RedemptionRequestInfo { // and goes to the collateral pool. uint16 poolFeeShareBIPS; - // The underlying block (approximate - as known by the asset manager) when the request occured. + // The underlying block (approximate - as known by the asset manager) when the request occurred. uint64 firstUnderlyingBlock; // The last underlying block and timestamp for redemption payment. Redemption is defaulted if @@ -47,7 +52,7 @@ library RedemptionRequestInfo { uint64 lastUnderlyingBlock; uint64 lastUnderlyingTimestamp; - // The native (Flare/Songbird) chain timstamp when the request occured. + // The native (Flare/Songbird) chain timestamp when the request occurred. uint64 timestamp; // True if redemption was created by a selfCloseExit on the collateral pool. @@ -60,13 +65,7 @@ library RedemptionRequestInfo { // (Only redeemer, agent or executor may execute the default.) address executor; - // The fee in NAT that the executor receives if they successfuly call default. + // The fee in NAT that the executor receives if they successfully call default. uint256 executorFeeNatWei; - - // If non-zero, request was rejected in handshake process. - uint64 rejectionTimestamp; - - // If non-zero, handshake-rejected request was taken over by another agent. - uint64 takeOverTimestamp; } } diff --git a/src/coston/userInterfaces/data/RedemptionTicketInfo.sol b/src/coston/data/RedemptionTicketInfo.sol similarity index 100% rename from src/coston/userInterfaces/data/RedemptionTicketInfo.sol rename to src/coston/data/RedemptionTicketInfo.sol diff --git a/src/coston/fdc/interface/ITypeTemplate.sol b/src/coston/fdc/interfaces/ITypeTemplate.sol similarity index 100% rename from src/coston/fdc/interface/ITypeTemplate.sol rename to src/coston/fdc/interfaces/ITypeTemplate.sol diff --git a/src/coston/fdc/interface/ITypeTemplateVerification.sol b/src/coston/fdc/interfaces/ITypeTemplateVerification.sol similarity index 100% rename from src/coston/fdc/interface/ITypeTemplateVerification.sol rename to src/coston/fdc/interfaces/ITypeTemplateVerification.sol diff --git a/src/coston/fscV1/interface/IIFastUpdaterView.sol b/src/coston/fscV1/interfaces/IIFastUpdaterView.sol similarity index 100% rename from src/coston/fscV1/interface/IIFastUpdaterView.sol rename to src/coston/fscV1/interfaces/IIFastUpdaterView.sol diff --git a/src/coston/fscV1/interface/IIFtsoManagerProxy.sol b/src/coston/fscV1/interfaces/IIFtsoManagerProxy.sol similarity index 100% rename from src/coston/fscV1/interface/IIFtsoManagerProxy.sol rename to src/coston/fscV1/interfaces/IIFtsoManagerProxy.sol diff --git a/src/coston2/ftso/interface/IIFtso.sol b/src/coston/ftso/interfaces/IIFtso.sol similarity index 98% rename from src/coston2/ftso/interface/IIFtso.sol rename to src/coston/ftso/interfaces/IIFtso.sol index e2beb8f..d93d935 100644 --- a/src/coston2/ftso/interface/IIFtso.sol +++ b/src/coston/ftso/interfaces/IIFtso.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "../../genesis/interface/IFtsoGenesis.sol"; +import "../../genesis/interfaces/IFtsoGenesis.sol"; import "../../IFtso.sol"; -import "../../token/interface/IIVPToken.sol"; +import "../../token/interfaces/IIVPToken.sol"; interface IIFtso is IFtso, IFtsoGenesis { diff --git a/src/coston/ftso/interface/IIFtsoFeedPublisher.sol b/src/coston/ftso/interfaces/IIFtsoFeedPublisher.sol similarity index 100% rename from src/coston/ftso/interface/IIFtsoFeedPublisher.sol rename to src/coston/ftso/interfaces/IIFtsoFeedPublisher.sol diff --git a/src/songbird/ftso/interface/IIFtsoManager.sol b/src/coston/ftso/interfaces/IIFtsoManager.sol similarity index 95% rename from src/songbird/ftso/interface/IIFtsoManager.sol rename to src/coston/ftso/interfaces/IIFtsoManager.sol index 6ca69ee..b11605f 100644 --- a/src/songbird/ftso/interface/IIFtsoManager.sol +++ b/src/coston/ftso/interfaces/IIFtsoManager.sol @@ -2,10 +2,10 @@ pragma solidity >=0.7.6 <0.9; pragma abicoder v2; -import "../../ftso/interface/IIFtso.sol"; +import "../../ftso/interfaces/IIFtso.sol"; import "../../IFtsoManager.sol"; -import "../../genesis/interface/IFlareDaemonize.sol"; -import "../../token/interface/IIVPToken.sol"; +import "../../genesis/interfaces/IFlareDaemonize.sol"; +import "../../token/interfaces/IIVPToken.sol"; interface IIFtsoManager is IFtsoManager, IFlareDaemonize { diff --git a/src/songbird/ftso/interface/IIFtsoManagerV1.sol b/src/coston/ftso/interfaces/IIFtsoManagerV1.sol similarity index 100% rename from src/songbird/ftso/interface/IIFtsoManagerV1.sol rename to src/coston/ftso/interfaces/IIFtsoManagerV1.sol diff --git a/src/coston/genesis/interface/IFlareDaemonize.sol b/src/coston/genesis/interfaces/IFlareDaemonize.sol similarity index 100% rename from src/coston/genesis/interface/IFlareDaemonize.sol rename to src/coston/genesis/interfaces/IFlareDaemonize.sol diff --git a/src/coston/genesis/interface/IFtsoGenesis.sol b/src/coston/genesis/interfaces/IFtsoGenesis.sol similarity index 100% rename from src/coston/genesis/interface/IFtsoGenesis.sol rename to src/coston/genesis/interfaces/IFtsoGenesis.sol diff --git a/src/coston/genesis/interface/IFtsoManagerGenesis.sol b/src/coston/genesis/interfaces/IFtsoManagerGenesis.sol similarity index 100% rename from src/coston/genesis/interface/IFtsoManagerGenesis.sol rename to src/coston/genesis/interfaces/IFtsoManagerGenesis.sol diff --git a/src/coston/genesis/interface/IFtsoRegistryGenesis.sol b/src/coston/genesis/interfaces/IFtsoRegistryGenesis.sol similarity index 100% rename from src/coston/genesis/interface/IFtsoRegistryGenesis.sol rename to src/coston/genesis/interfaces/IFtsoRegistryGenesis.sol diff --git a/src/songbird/genesis/interface/IIPriceSubmitter.sol b/src/coston/genesis/interfaces/IIPriceSubmitter.sol similarity index 100% rename from src/songbird/genesis/interface/IIPriceSubmitter.sol rename to src/coston/genesis/interfaces/IIPriceSubmitter.sol diff --git a/src/songbird/genesis/interface/IInflationGenesis.sol b/src/coston/genesis/interfaces/IInflationGenesis.sol similarity index 100% rename from src/songbird/genesis/interface/IInflationGenesis.sol rename to src/coston/genesis/interfaces/IInflationGenesis.sol diff --git a/src/songbird/governance/interface/IIGovernorProposer.sol b/src/coston/governance/interfaces/IIGovernorProposer.sol similarity index 100% rename from src/songbird/governance/interface/IIGovernorProposer.sol rename to src/coston/governance/interfaces/IIGovernorProposer.sol diff --git a/src/songbird/governance/interface/IIPollingFoundation.sol b/src/coston/governance/interfaces/IIPollingFoundation.sol similarity index 100% rename from src/songbird/governance/interface/IIPollingFoundation.sol rename to src/coston/governance/interfaces/IIPollingFoundation.sol diff --git a/src/coston/governance/interface/IIPollingManagementGroup.sol b/src/coston/governance/interfaces/IIPollingManagementGroup.sol similarity index 100% rename from src/coston/governance/interface/IIPollingManagementGroup.sol rename to src/coston/governance/interfaces/IIPollingManagementGroup.sol diff --git a/src/songbird/inflation/interface/IIInflationAllocation.sol b/src/coston/inflation/interfaces/IIInflationAllocation.sol similarity index 100% rename from src/songbird/inflation/interface/IIInflationAllocation.sol rename to src/coston/inflation/interfaces/IIInflationAllocation.sol diff --git a/src/songbird/inflation/interface/IIInflationReceiver.sol b/src/coston/inflation/interfaces/IIInflationReceiver.sol similarity index 100% rename from src/songbird/inflation/interface/IIInflationReceiver.sol rename to src/coston/inflation/interfaces/IIInflationReceiver.sol diff --git a/src/songbird/inflation/interface/IIInflationReceiverV1.sol b/src/coston/inflation/interfaces/IIInflationReceiverV1.sol similarity index 100% rename from src/songbird/inflation/interface/IIInflationReceiverV1.sol rename to src/coston/inflation/interfaces/IIInflationReceiverV1.sol diff --git a/src/songbird/inflation/interface/IIInflationV1.sol b/src/coston/inflation/interfaces/IIInflationV1.sol similarity index 100% rename from src/songbird/inflation/interface/IIInflationV1.sol rename to src/coston/inflation/interfaces/IIInflationV1.sol diff --git a/src/songbird/inflation/interface/IIPreInflationCalculation.sol b/src/coston/inflation/interfaces/IIPreInflationCalculation.sol similarity index 100% rename from src/songbird/inflation/interface/IIPreInflationCalculation.sol rename to src/coston/inflation/interfaces/IIPreInflationCalculation.sol diff --git a/src/songbird/inflation/interface/IISupply.sol b/src/coston/inflation/interfaces/IISupply.sol similarity index 100% rename from src/songbird/inflation/interface/IISupply.sol rename to src/coston/inflation/interfaces/IISupply.sol diff --git a/src/songbird/mockXAsset/interface/ICollateralizable.sol b/src/coston/mockXAsset/interfaces/ICollateralizable.sol similarity index 100% rename from src/songbird/mockXAsset/interface/ICollateralizable.sol rename to src/coston/mockXAsset/interfaces/ICollateralizable.sol diff --git a/src/coston/protocol/interface/IIClaimSetupManager.sol b/src/coston/protocol/interfaces/IIClaimSetupManager.sol similarity index 100% rename from src/coston/protocol/interface/IIClaimSetupManager.sol rename to src/coston/protocol/interfaces/IIClaimSetupManager.sol diff --git a/src/coston/protocol/interface/IICleanupBlockNumberManager.sol b/src/coston/protocol/interfaces/IICleanupBlockNumberManager.sol similarity index 100% rename from src/coston/protocol/interface/IICleanupBlockNumberManager.sol rename to src/coston/protocol/interfaces/IICleanupBlockNumberManager.sol diff --git a/src/coston/protocol/interface/IIEntityManager.sol b/src/coston/protocol/interfaces/IIEntityManager.sol similarity index 100% rename from src/coston/protocol/interface/IIEntityManager.sol rename to src/coston/protocol/interfaces/IIEntityManager.sol diff --git a/src/coston/protocol/interface/IIFlareSystemsCalculator.sol b/src/coston/protocol/interfaces/IIFlareSystemsCalculator.sol similarity index 100% rename from src/coston/protocol/interface/IIFlareSystemsCalculator.sol rename to src/coston/protocol/interfaces/IIFlareSystemsCalculator.sol diff --git a/src/coston/protocol/interface/IIFlareSystemsManager.sol b/src/coston/protocol/interfaces/IIFlareSystemsManager.sol similarity index 100% rename from src/coston/protocol/interface/IIFlareSystemsManager.sol rename to src/coston/protocol/interfaces/IIFlareSystemsManager.sol diff --git a/src/coston/protocol/interface/IINodePossessionVerifier.sol b/src/coston/protocol/interfaces/IINodePossessionVerifier.sol similarity index 100% rename from src/coston/protocol/interface/IINodePossessionVerifier.sol rename to src/coston/protocol/interfaces/IINodePossessionVerifier.sol diff --git a/src/coston/protocol/interface/IIPublicKeyVerifier.sol b/src/coston/protocol/interfaces/IIPublicKeyVerifier.sol similarity index 100% rename from src/coston/protocol/interface/IIPublicKeyVerifier.sol rename to src/coston/protocol/interfaces/IIPublicKeyVerifier.sol diff --git a/src/coston/protocol/interface/IIRelay.sol b/src/coston/protocol/interfaces/IIRelay.sol similarity index 100% rename from src/coston/protocol/interface/IIRelay.sol rename to src/coston/protocol/interfaces/IIRelay.sol diff --git a/src/coston/protocol/interface/IIRewardEpochSwitchoverTrigger.sol b/src/coston/protocol/interfaces/IIRewardEpochSwitchoverTrigger.sol similarity index 100% rename from src/coston/protocol/interface/IIRewardEpochSwitchoverTrigger.sol rename to src/coston/protocol/interfaces/IIRewardEpochSwitchoverTrigger.sol diff --git a/src/coston/protocol/interface/IIRewardManager.sol b/src/coston/protocol/interfaces/IIRewardManager.sol similarity index 100% rename from src/coston/protocol/interface/IIRewardManager.sol rename to src/coston/protocol/interfaces/IIRewardManager.sol diff --git a/src/coston/protocol/interface/IISubmission.sol b/src/coston/protocol/interfaces/IISubmission.sol similarity index 100% rename from src/coston/protocol/interface/IISubmission.sol rename to src/coston/protocol/interfaces/IISubmission.sol diff --git a/src/coston/protocol/interface/IIVoterRegistrationTrigger.sol b/src/coston/protocol/interfaces/IIVoterRegistrationTrigger.sol similarity index 100% rename from src/coston/protocol/interface/IIVoterRegistrationTrigger.sol rename to src/coston/protocol/interfaces/IIVoterRegistrationTrigger.sol diff --git a/src/coston/protocol/interface/IIVoterRegistry.sol b/src/coston/protocol/interfaces/IIVoterRegistry.sol similarity index 100% rename from src/coston/protocol/interface/IIVoterRegistry.sol rename to src/coston/protocol/interfaces/IIVoterRegistry.sol diff --git a/src/coston/rNat/interface/IIRNat.sol b/src/coston/rNat/interfaces/IIRNat.sol similarity index 100% rename from src/coston/rNat/interface/IIRNat.sol rename to src/coston/rNat/interfaces/IIRNat.sol diff --git a/src/flare/rNat/interface/IIRNatAccount.sol b/src/coston/rNat/interfaces/IIRNatAccount.sol similarity index 98% rename from src/flare/rNat/interface/IIRNatAccount.sol rename to src/coston/rNat/interfaces/IIRNatAccount.sol index 0a7d05e..017902d 100644 --- a/src/flare/rNat/interface/IIRNatAccount.sol +++ b/src/coston/rNat/interfaces/IIRNatAccount.sol @@ -3,7 +3,7 @@ pragma solidity >=0.7.6 <0.9; import "../../IRNatAccount.sol"; -import "../../protocol/interface/IIClaimSetupManager.sol"; +import "../../protocol/interfaces/IIClaimSetupManager.sol"; interface IIRNatAccount is IRNatAccount { diff --git a/src/coston/token/interface/IICleanable.sol b/src/coston/token/interfaces/IICleanable.sol similarity index 100% rename from src/coston/token/interface/IICleanable.sol rename to src/coston/token/interfaces/IICleanable.sol diff --git a/src/coston/token/interface/IIGovernanceVotePower.sol b/src/coston/token/interfaces/IIGovernanceVotePower.sol similarity index 100% rename from src/coston/token/interface/IIGovernanceVotePower.sol rename to src/coston/token/interfaces/IIGovernanceVotePower.sol diff --git a/src/coston/token/interface/IIVPContract.sol b/src/coston/token/interfaces/IIVPContract.sol similarity index 100% rename from src/coston/token/interface/IIVPContract.sol rename to src/coston/token/interfaces/IIVPContract.sol diff --git a/src/coston/token/interface/IIVPToken.sol b/src/coston/token/interfaces/IIVPToken.sol similarity index 100% rename from src/coston/token/interface/IIVPToken.sol rename to src/coston/token/interfaces/IIVPToken.sol diff --git a/src/songbird/tokenPools/interface/IIFtsoRewardManager.sol b/src/coston/tokenPools/interfaces/IIFtsoRewardManager.sol similarity index 94% rename from src/songbird/tokenPools/interface/IIFtsoRewardManager.sol rename to src/coston/tokenPools/interfaces/IIFtsoRewardManager.sol index cd5bf48..f7907a3 100644 --- a/src/songbird/tokenPools/interface/IIFtsoRewardManager.sol +++ b/src/coston/tokenPools/interfaces/IIFtsoRewardManager.sol @@ -2,8 +2,8 @@ pragma solidity >=0.7.6 <0.9; import "../../IFtsoRewardManager.sol"; -import "../interface/IITokenPool.sol"; -import "../../inflation/interface/IIInflationReceiverV1.sol"; +import "../interfaces/IITokenPool.sol"; +import "../../inflation/interfaces/IIInflationReceiverV1.sol"; interface IIFtsoRewardManager is IFtsoRewardManager, IIInflationReceiverV1, IITokenPool { diff --git a/src/songbird/tokenPools/interface/IITokenPool.sol b/src/coston/tokenPools/interfaces/IITokenPool.sol similarity index 100% rename from src/songbird/tokenPools/interface/IITokenPool.sol rename to src/coston/tokenPools/interfaces/IITokenPool.sol diff --git a/src/songbird/utils/interface/IIFtsoRegistry.sol b/src/coston/utils/interfaces/IIFtsoRegistry.sol similarity index 87% rename from src/songbird/utils/interface/IIFtsoRegistry.sol rename to src/coston/utils/interfaces/IIFtsoRegistry.sol index 1c9c6e6..82d239a 100644 --- a/src/songbird/utils/interface/IIFtsoRegistry.sol +++ b/src/coston/utils/interfaces/IIFtsoRegistry.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; pragma abicoder v2; -import "../../ftso/interface/IIFtso.sol"; +import "../../ftso/interfaces/IIFtso.sol"; import "../../IFtsoRegistry.sol"; diff --git a/src/songbird/utils/interface/IIFtsoRegistryV1.sol b/src/coston/utils/interfaces/IIFtsoRegistryV1.sol similarity index 93% rename from src/songbird/utils/interface/IIFtsoRegistryV1.sol rename to src/coston/utils/interfaces/IIFtsoRegistryV1.sol index 4f75ee0..f44303e 100644 --- a/src/songbird/utils/interface/IIFtsoRegistryV1.sol +++ b/src/coston/utils/interfaces/IIFtsoRegistryV1.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; pragma abicoder v2; -import "../../ftso/interface/IIFtsoManager.sol"; +import "../../ftso/interfaces/IIFtsoManager.sol"; interface IIFtsoRegistryV1 { diff --git a/src/songbird/utils/interface/IIRandomProvider.sol b/src/coston/utils/interfaces/IIRandomProvider.sol similarity index 100% rename from src/songbird/utils/interface/IIRandomProvider.sol rename to src/coston/utils/interfaces/IIRandomProvider.sol diff --git a/src/songbird/utils/interface/IIVoterWhitelister.sol b/src/coston/utils/interfaces/IIVoterWhitelister.sol similarity index 100% rename from src/songbird/utils/interface/IIVoterWhitelister.sol rename to src/coston/utils/interfaces/IIVoterWhitelister.sol diff --git a/src/songbird/utils/interface/IUpdateValidators.sol b/src/coston/utils/interfaces/IUpdateValidators.sol similarity index 100% rename from src/songbird/utils/interface/IUpdateValidators.sol rename to src/coston/utils/interfaces/IUpdateValidators.sol diff --git a/src/coston2/ContractRegistry.sol b/src/coston2/ContractRegistry.sol index 6484fa2..ab24b92 100644 --- a/src/coston2/ContractRegistry.sol +++ b/src/coston2/ContractRegistry.sol @@ -1,56 +1,48 @@ // SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; +pragma solidity ^0.8.25; -import {IFlareContractRegistry} from "./IFlareContractRegistry.sol"; - -// Auto generated imports +import { IFlareContractRegistry } from "./IFlareContractRegistry.sol"; // AUTO GENERATED - DO NOT EDIT BELOW THIS LINE -import {IPriceSubmitter} from "./IPriceSubmitter.sol"; -import {IGovernanceSettings} from "./IGovernanceSettings.sol"; -import {IFtsoRewardManager} from "./IFtsoRewardManager.sol"; -import {IFtsoRegistry} from "./IFtsoRegistry.sol"; -import {IVoterWhitelister} from "./IVoterWhitelister.sol"; -import {IDistributionToDelegators} from "./IDistributionToDelegators.sol"; -import {IFtsoManager} from "./IFtsoManager.sol"; -import {IWNat} from "./IWNat.sol"; -import {IGovernanceVotePower} from "./IGovernanceVotePower.sol"; -import {IClaimSetupManager} from "./IClaimSetupManager.sol"; -import {IGenericRewardManager} from "./IGenericRewardManager.sol"; -import {IFlareAssetRegistry} from "./IFlareAssetRegistry.sol"; -import {IValidatorRegistry} from "./IValidatorRegistry.sol"; -import {IFlareContractRegistry} from "./IFlareContractRegistry.sol"; -import {IAddressBinder} from "./IAddressBinder.sol"; -import {IPChainStakeMirror} from "./IPChainStakeMirror.sol"; -import {IPChainStakeMirrorVerifier} from "./IPChainStakeMirrorVerifier.sol"; -import {IPChainStakeMirrorMultiSigVoting} from "./IPChainStakeMirrorMultiSigVoting.sol"; -import {ISubmission} from "./ISubmission.sol"; -import {IEntityManager} from "./IEntityManager.sol"; -import {IVoterRegistry} from "./IVoterRegistry.sol"; -import {IFlareSystemsCalculator} from "./IFlareSystemsCalculator.sol"; -import {IFlareSystemsManager} from "./IFlareSystemsManager.sol"; -import {IRewardManager} from "./IRewardManager.sol"; -import {IRelay} from "./IRelay.sol"; -import {IWNatDelegationFee} from "./IWNatDelegationFee.sol"; -import {IFtsoInflationConfigurations} from "./IFtsoInflationConfigurations.sol"; -import {IFtsoRewardOffersManager} from "./IFtsoRewardOffersManager.sol"; -import {IFtsoFeedDecimals} from "./IFtsoFeedDecimals.sol"; -import {IFtsoFeedPublisher} from "./IFtsoFeedPublisher.sol"; -import {IFtsoFeedIdConverter} from "./IFtsoFeedIdConverter.sol"; -import {IFastUpdateIncentiveManager} from "./IFastUpdateIncentiveManager.sol"; -import {IFastUpdater} from "./IFastUpdater.sol"; -import {IFastUpdatesConfiguration} from "./IFastUpdatesConfiguration.sol"; -import {IRNat} from "./IRNat.sol"; -import {IFeeCalculator} from "./IFeeCalculator.sol"; -import {FtsoV2Interface} from "./FtsoV2Interface.sol"; -import {TestFtsoV2Interface} from "./TestFtsoV2Interface.sol"; -import {ProtocolsV2Interface} from "./ProtocolsV2Interface.sol"; -import {RandomNumberV2Interface} from "./RandomNumberV2Interface.sol"; -import {RewardsV2Interface} from "./RewardsV2Interface.sol"; -import {IFdcVerification} from "./IFdcVerification.sol"; -import {IFdcHub} from "./IFdcHub.sol"; -import {IFdcRequestFeeConfigurations} from "./IFdcRequestFeeConfigurations.sol"; -import {IJsonApiVerification} from "./IJsonApiVerification.sol"; -import {IWeb2JsonVerification} from "./IWeb2JsonVerification.sol"; +import { IPriceSubmitter } from "./IPriceSubmitter.sol"; +import { IGovernanceSettings } from "./IGovernanceSettings.sol"; +import { IFtsoRewardManager } from "./IFtsoRewardManager.sol"; +import { IFtsoRegistry } from "./IFtsoRegistry.sol"; +import { IVoterWhitelister } from "./IVoterWhitelister.sol"; +import { IFtsoManager } from "./IFtsoManager.sol"; +import { IWNat } from "./IWNat.sol"; +import { IGovernanceVotePower } from "./IGovernanceVotePower.sol"; +import { IClaimSetupManager } from "./IClaimSetupManager.sol"; +import { IFlareAssetRegistry } from "./IFlareAssetRegistry.sol"; +import { IFlareContractRegistry } from "./IFlareContractRegistry.sol"; +import { ISubmission } from "./ISubmission.sol"; +import { IEntityManager } from "./IEntityManager.sol"; +import { IVoterRegistry } from "./IVoterRegistry.sol"; +import { IFlareSystemsCalculator } from "./IFlareSystemsCalculator.sol"; +import { IFlareSystemsManager } from "./IFlareSystemsManager.sol"; +import { IRewardManager } from "./IRewardManager.sol"; +import { IRelay } from "./IRelay.sol"; +import { IWNatDelegationFee } from "./IWNatDelegationFee.sol"; +import { IFtsoInflationConfigurations } from "./IFtsoInflationConfigurations.sol"; +import { IFtsoRewardOffersManager } from "./IFtsoRewardOffersManager.sol"; +import { IFtsoFeedDecimals } from "./IFtsoFeedDecimals.sol"; +import { IFtsoFeedPublisher } from "./IFtsoFeedPublisher.sol"; +import { IFtsoFeedIdConverter } from "./IFtsoFeedIdConverter.sol"; +import { IFastUpdateIncentiveManager } from "./IFastUpdateIncentiveManager.sol"; +import { IFastUpdater } from "./IFastUpdater.sol"; +import { IFastUpdatesConfiguration } from "./IFastUpdatesConfiguration.sol"; +import { IFeeCalculator } from "./IFeeCalculator.sol"; +import { FtsoV2Interface } from "./FtsoV2Interface.sol"; +import { TestFtsoV2Interface } from "./TestFtsoV2Interface.sol"; +import { ProtocolsV2Interface } from "./ProtocolsV2Interface.sol"; +import { RandomNumberV2Interface } from "./RandomNumberV2Interface.sol"; +import { RewardsV2Interface } from "./RewardsV2Interface.sol"; +import { IFdcVerification } from "./IFdcVerification.sol"; +import { IFdcHub } from "./IFdcHub.sol"; +import { IFdcRequestFeeConfigurations } from "./IFdcRequestFeeConfigurations.sol"; +import { IAssetManagerController } from "./IAssetManagerController.sol"; +import { IAssetManager } from "./IAssetManager.sol"; +import { IJsonApiVerification } from "./IJsonApiVerification.sol"; +import { IGenericRewardManager } from "./IGenericRewardManager.sol"; // END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE // Library is intended to be used inline, so the strings are all memory allocated (instead of calldata) @@ -113,14 +105,18 @@ library ContractRegistry { } // Nice typed getters for all the important contracts - // AUTO GENERATED - DO NOT EDIT BELOW THIS LINE - function getPriceSubmitter() internal view returns (IPriceSubmitter) { +// AUTO GENERATED - DO NOT EDIT BELOW THIS LINE + function getPriceSubmitter() + internal + view + returns (IPriceSubmitter) + { return IPriceSubmitter( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PriceSubmitter")) - ) - ); + keccak256(abi.encode("PriceSubmitter")) + ) + ); } function getGovernanceSettings() @@ -131,67 +127,74 @@ library ContractRegistry { return IGovernanceSettings( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("GovernanceSettings")) - ) - ); + keccak256(abi.encode("GovernanceSettings")) + ) + ); } - function getFtsoRewardManager() internal view returns (IFtsoRewardManager) { + function getFtsoRewardManager() + internal + view + returns (IFtsoRewardManager) + { return IFtsoRewardManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRewardManager")) - ) - ); + keccak256(abi.encode("FtsoRewardManager")) + ) + ); } - function getFtsoRegistry() internal view returns (IFtsoRegistry) { + function getFtsoRegistry() + internal + view + returns (IFtsoRegistry) + { return IFtsoRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRegistry")) - ) - ); + keccak256(abi.encode("FtsoRegistry")) + ) + ); } - function getVoterWhitelister() internal view returns (IVoterWhitelister) { + function getVoterWhitelister() + internal + view + returns (IVoterWhitelister) + { return IVoterWhitelister( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("VoterWhitelister")) - ) - ); + keccak256(abi.encode("VoterWhitelister")) + ) + ); } - function getDistributionToDelegators() + function getFtsoManager() internal view - returns (IDistributionToDelegators) + returns (IFtsoManager) { - return - IDistributionToDelegators( - FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("DistributionToDelegators")) - ) - ); - } - - function getFtsoManager() internal view returns (IFtsoManager) { return IFtsoManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoManager")) - ) - ); + keccak256(abi.encode("FtsoManager")) + ) + ); } - function getWNat() internal view returns (IWNat) { + function getWNat() + internal + view + returns (IWNat) + { return IWNat( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("WNat")) - ) - ); + keccak256(abi.encode("WNat")) + ) + ); } function getGovernanceVotePower() @@ -202,31 +205,22 @@ library ContractRegistry { return IGovernanceVotePower( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("GovernanceVotePower")) - ) - ); + keccak256(abi.encode("GovernanceVotePower")) + ) + ); } - function getClaimSetupManager() internal view returns (IClaimSetupManager) { - return - IClaimSetupManager( - FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ClaimSetupManager")) - ) - ); - } - - function getValidatorRewardManager() + function getClaimSetupManager() internal view - returns (IGenericRewardManager) + returns (IClaimSetupManager) { return - IGenericRewardManager( + IClaimSetupManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ValidatorRewardManager")) - ) - ); + keccak256(abi.encode("ClaimSetupManager")) + ) + ); } function getFlareAssetRegistry() @@ -237,18 +231,9 @@ library ContractRegistry { return IFlareAssetRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareAssetRegistry")) - ) - ); - } - - function getValidatorRegistry() internal view returns (IValidatorRegistry) { - return - IValidatorRegistry( - FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ValidatorRegistry")) - ) - ); + keccak256(abi.encode("FlareAssetRegistry")) + ) + ); } function getFlareContractRegistry() @@ -259,80 +244,48 @@ library ContractRegistry { return IFlareContractRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareContractRegistry")) - ) - ); - } - - function getAddressBinder() internal view returns (IAddressBinder) { - return - IAddressBinder( - FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("AddressBinder")) - ) - ); + keccak256(abi.encode("FlareContractRegistry")) + ) + ); } - function getPChainStakeMirror() internal view returns (IPChainStakeMirror) { - return - IPChainStakeMirror( - FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PChainStakeMirror")) - ) - ); - } - - function getPChainStakeMirrorVerifier() + function getSubmission() internal view - returns (IPChainStakeMirrorVerifier) + returns (ISubmission) { return - IPChainStakeMirrorVerifier( + ISubmission( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PChainStakeMirrorVerifier")) - ) - ); + keccak256(abi.encode("Submission")) + ) + ); } - function getPChainStakeMirrorMultiSigVoting() + function getEntityManager() internal view - returns (IPChainStakeMirrorMultiSigVoting) + returns (IEntityManager) { - return - IPChainStakeMirrorMultiSigVoting( - FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PChainStakeMirrorMultiSigVoting")) - ) - ); - } - - function getSubmission() internal view returns (ISubmission) { - return - ISubmission( - FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("Submission")) - ) - ); - } - - function getEntityManager() internal view returns (IEntityManager) { return IEntityManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("EntityManager")) - ) - ); + keccak256(abi.encode("EntityManager")) + ) + ); } - function getVoterRegistry() internal view returns (IVoterRegistry) { + function getVoterRegistry() + internal + view + returns (IVoterRegistry) + { return IVoterRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("VoterRegistry")) - ) - ); + keccak256(abi.encode("VoterRegistry")) + ) + ); } function getFlareSystemsCalculator() @@ -343,9 +296,9 @@ library ContractRegistry { return IFlareSystemsCalculator( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareSystemsCalculator")) - ) - ); + keccak256(abi.encode("FlareSystemsCalculator")) + ) + ); } function getFlareSystemsManager() @@ -356,36 +309,48 @@ library ContractRegistry { return IFlareSystemsManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareSystemsManager")) - ) - ); + keccak256(abi.encode("FlareSystemsManager")) + ) + ); } - function getRewardManager() internal view returns (IRewardManager) { + function getRewardManager() + internal + view + returns (IRewardManager) + { return IRewardManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RewardManager")) - ) - ); + keccak256(abi.encode("RewardManager")) + ) + ); } - function getRelay() internal view returns (IRelay) { + function getRelay() + internal + view + returns (IRelay) + { return IRelay( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("Relay")) - ) - ); + keccak256(abi.encode("Relay")) + ) + ); } - function getWNatDelegationFee() internal view returns (IWNatDelegationFee) { + function getWNatDelegationFee() + internal + view + returns (IWNatDelegationFee) + { return IWNatDelegationFee( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("WNatDelegationFee")) - ) - ); + keccak256(abi.encode("WNatDelegationFee")) + ) + ); } function getFtsoInflationConfigurations() @@ -396,9 +361,9 @@ library ContractRegistry { return IFtsoInflationConfigurations( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoInflationConfigurations")) - ) - ); + keccak256(abi.encode("FtsoInflationConfigurations")) + ) + ); } function getFtsoRewardOffersManager() @@ -409,27 +374,35 @@ library ContractRegistry { return IFtsoRewardOffersManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRewardOffersManager")) - ) - ); + keccak256(abi.encode("FtsoRewardOffersManager")) + ) + ); } - function getFtsoFeedDecimals() internal view returns (IFtsoFeedDecimals) { + function getFtsoFeedDecimals() + internal + view + returns (IFtsoFeedDecimals) + { return IFtsoFeedDecimals( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoFeedDecimals")) - ) - ); + keccak256(abi.encode("FtsoFeedDecimals")) + ) + ); } - function getFtsoFeedPublisher() internal view returns (IFtsoFeedPublisher) { + function getFtsoFeedPublisher() + internal + view + returns (IFtsoFeedPublisher) + { return IFtsoFeedPublisher( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoFeedPublisher")) - ) - ); + keccak256(abi.encode("FtsoFeedPublisher")) + ) + ); } function getFtsoFeedIdConverter() @@ -440,9 +413,9 @@ library ContractRegistry { return IFtsoFeedIdConverter( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoFeedIdConverter")) - ) - ); + keccak256(abi.encode("FtsoFeedIdConverter")) + ) + ); } function getFastUpdateIncentiveManager() @@ -453,18 +426,22 @@ library ContractRegistry { return IFastUpdateIncentiveManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FastUpdateIncentiveManager")) - ) - ); + keccak256(abi.encode("FastUpdateIncentiveManager")) + ) + ); } - function getFastUpdater() internal view returns (IFastUpdater) { + function getFastUpdater() + internal + view + returns (IFastUpdater) + { return IFastUpdater( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FastUpdater")) - ) - ); + keccak256(abi.encode("FastUpdater")) + ) + ); } function getFastUpdatesConfiguration() @@ -475,54 +452,61 @@ library ContractRegistry { return IFastUpdatesConfiguration( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FastUpdatesConfiguration")) - ) - ); - } - - function getRNat() internal view returns (IRNat) { - return - IRNat( - FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RNat")) - ) - ); + keccak256(abi.encode("FastUpdatesConfiguration")) + ) + ); } - function getFeeCalculator() internal view returns (IFeeCalculator) { + function getFeeCalculator() + internal + view + returns (IFeeCalculator) + { return IFeeCalculator( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FeeCalculator")) - ) - ); + keccak256(abi.encode("FeeCalculator")) + ) + ); } - function getFtsoV2() internal view returns (FtsoV2Interface) { + function getFtsoV2() + internal + view + returns (FtsoV2Interface) + { return FtsoV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoV2")) - ) - ); + keccak256(abi.encode("FtsoV2")) + ) + ); } - function getTestFtsoV2() internal view returns (TestFtsoV2Interface) { + function getTestFtsoV2() + internal + view + returns (TestFtsoV2Interface) + { return TestFtsoV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoV2")) - ) - ); + keccak256(abi.encode("FtsoV2")) + ) + ); } - function getProtocolsV2() internal view returns (ProtocolsV2Interface) { + function getProtocolsV2() + internal + view + returns (ProtocolsV2Interface) + { return ProtocolsV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ProtocolsV2")) - ) - ); + keccak256(abi.encode("ProtocolsV2")) + ) + ); } function getRandomNumberV2() @@ -533,36 +517,48 @@ library ContractRegistry { return RandomNumberV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RandomNumberV2")) - ) - ); + keccak256(abi.encode("RandomNumberV2")) + ) + ); } - function getRewardsV2() internal view returns (RewardsV2Interface) { + function getRewardsV2() + internal + view + returns (RewardsV2Interface) + { return RewardsV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RewardsV2")) - ) - ); + keccak256(abi.encode("RewardsV2")) + ) + ); } - function getFdcVerification() internal view returns (IFdcVerification) { + function getFdcVerification() + internal + view + returns (IFdcVerification) + { return IFdcVerification( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcVerification")) - ) - ); + keccak256(abi.encode("FdcVerification")) + ) + ); } - function getFdcHub() internal view returns (IFdcHub) { + function getFdcHub() + internal + view + returns (IFdcHub) + { return IFdcHub( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcHub")) - ) - ); + keccak256(abi.encode("FdcHub")) + ) + ); } function getFdcRequestFeeConfigurations() @@ -573,29 +569,60 @@ library ContractRegistry { return IFdcRequestFeeConfigurations( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcRequestFeeConfigurations")) - ) - ); + keccak256(abi.encode("FdcRequestFeeConfigurations")) + ) + ); + } + + function getAssetManagerController() + internal + view + returns (IAssetManagerController) + { + return + IAssetManagerController( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("AssetManagerController")) + ) + ); + } + + function getAssetManagerFXRP() + internal + view + returns (IAssetManager) + { + return + IAssetManager( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("AssetManagerFXRP")) + ) + ); } - // Returns hardcoded unofficial deployment instances of Flare core contracts function auxiliaryGetIJsonApiVerification() internal pure returns (IJsonApiVerification) { - return IJsonApiVerification(0x07ad8508C9173DC845817472Ca0484035AbFA3c8); + return + IJsonApiVerification( + 0x07ad8508C9173DC845817472Ca0484035AbFA3c8 + ); } - // Returns hardcoded unofficial deployment instances of Flare core contracts - function auxiliaryGetIWeb2JsonVerification() + function getValidatorRewardManager() internal - pure - returns (IWeb2JsonVerification) + view + returns (IGenericRewardManager) { return - IWeb2JsonVerification(0x906507E0B64bcD494Db73bd0459d1C667e14B933); + IGenericRewardManager( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("ValidatorRewardManager")) + ) + ); } - // END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE -} +// END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE +} \ No newline at end of file diff --git a/src/coston2/IAgentOwnerRegistry.sol b/src/coston2/IAgentOwnerRegistry.sol new file mode 100644 index 0000000..4075ba8 --- /dev/null +++ b/src/coston2/IAgentOwnerRegistry.sol @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +/** + * Agent owner management and work address management + */ +interface IAgentOwnerRegistry { + + event Whitelisted(address value); + event WhitelistingRevoked(address value); + + /** + * Agent owner's work address has been set. + */ + event WorkAddressChanged( + address indexed managementAddress, + address prevWorkAddress, + address workAddress); + + event AgentDataChanged( + address indexed managementAddress, + string name, + string description, + string iconUrl, + string termsOfUseUrl); + + error AgentNotWhitelisted(); + error WorkAddressInUse(); + + + /** + * Returns true if the address is whitelisted, false otherwise. + * @param _address address to check + */ + function isWhitelisted(address _address) external view returns (bool); + + /** + * Return agent owner's name. + * @param _managementAddress agent owner's management address + */ + function getAgentName(address _managementAddress) + external view + returns (string memory); + + /** + * Return agent owner's description. + * @param _managementAddress agent owner's management address + */ + function getAgentDescription(address _managementAddress) + external view + returns (string memory); + + /** + * Return url of the agent owner's icon. + * @param _managementAddress agent owner's management address + */ + function getAgentIconUrl(address _managementAddress) + external view + returns (string memory); + + /** + * Return url of the agent's page with terms of use. + * @param _managementAddress agent owner's management address + */ + function getAgentTermsOfUseUrl(address _managementAddress) + external view + returns (string memory); + + /** + * Get the (unique) work address for the given management address. + */ + function getWorkAddress(address _managementAddress) + external view + returns (address); + + /** + * Get the (unique) management address for the given work address. + */ + function getManagementAddress(address _workAddress) + external view + returns (address); +} \ No newline at end of file diff --git a/src/coston2/IAssetManager.sol b/src/coston2/IAssetManager.sol index 4bfe18a..60953d0 100644 --- a/src/coston2/IAssetManager.sol +++ b/src/coston2/IAssetManager.sol @@ -1,24 +1,26 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IFdcVerification.sol"; -import "@openzeppelin-contracts/utils/introspection/IERC165.sol"; -import "./diamond/interfaces/IDiamondLoupe.sol"; -import "./userInterfaces/data/AssetManagerSettings.sol"; -import "./userInterfaces/data/CollateralType.sol"; -import "./userInterfaces/data/AgentInfo.sol"; -import "./userInterfaces/data/AgentSettings.sol"; -import "./userInterfaces/data/AvailableAgentInfo.sol"; -import "./userInterfaces/data/RedemptionTicketInfo.sol"; -import "./userInterfaces/data/RedemptionRequestInfo.sol"; -import "./userInterfaces/data/CollateralReservationInfo.sol"; -import "./IAssetManagerEvents.sol"; -import "./IAgentPing.sol"; -import "./IRedemptionTimeExtension.sol"; -import "./ITransferFees.sol"; -import "./ICoreVault.sol"; -import "./ICoreVaultSettings.sol"; -import "./IAgentAlwaysAllowedMinters.sol"; +import {IConfirmedBlockHeightExists, IPayment, IAddressValidity, IReferencedPaymentNonexistence, + IBalanceDecreasingTransaction} + from ".//IFdcVerification.sol"; +import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; +import {IDiamondLoupe} from "./diamond/interfaces/IDiamondLoupe.sol"; +import {AssetManagerSettings} from "./data/AssetManagerSettings.sol"; +import {CollateralType} from "./data/CollateralType.sol"; +import {AgentInfo} from "./data/AgentInfo.sol"; +import {AgentSettings} from "./data/AgentSettings.sol"; +import {AvailableAgentInfo} from "./data/AvailableAgentInfo.sol"; +import {RedemptionTicketInfo} from "./data/RedemptionTicketInfo.sol"; +import {RedemptionRequestInfo} from "./data/RedemptionRequestInfo.sol"; +import {CollateralReservationInfo} from "./data/CollateralReservationInfo.sol"; +import {IAssetManagerEvents} from "./IAssetManagerEvents.sol"; +import {IAgentPing} from "./IAgentPing.sol"; +import {IRedemptionTimeExtension} from "./IRedemptionTimeExtension.sol"; +import {ICoreVaultClient} from "./ICoreVaultClient.sol"; +import {ICoreVaultClientSettings} from "./ICoreVaultClientSettings.sol"; +import {IAgentAlwaysAllowedMinters} from "./IAgentAlwaysAllowedMinters.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @@ -30,9 +32,8 @@ interface IAssetManager is IAssetManagerEvents, IAgentPing, IRedemptionTimeExtension, - ITransferFees, - ICoreVault, - ICoreVaultSettings, + ICoreVaultClient, + ICoreVaultClientSettings, IAgentAlwaysAllowedMinters { //////////////////////////////////////////////////////////////////////////////////// @@ -148,19 +149,6 @@ interface IAssetManager is external view returns (bool); - /** - * True if the asset manager is terminated. - * In terminated state almost all operations (minting, redeeming, liquidation) are disabled and f-assets are - * not transferable any more. The only operation still permitted is for agents to release the locked collateral - * by calling `buybackAgentCollateral`. - * An asset manager can be terminated after being paused for at least a month - * (to redeem as many f-assets as possible). - * The terminated asset manager can not be revived anymore. - */ - function terminated() - external view - returns (bool); - //////////////////////////////////////////////////////////////////////////////////// // Timekeeping for underlying chain @@ -207,20 +195,6 @@ interface IAssetManager is //////////////////////////////////////////////////////////////////////////////////// // Agent create / destroy - /** - * This method fixes the underlying address to be used by given agent owner. - * A proof of payment (can be minimal or to itself) from this address must be provided, - * with payment reference being equal to this method caller's address. - * NOTE: calling this method before `createAgentVault()` is optional on most chains, - * but is required on smart contract chains to make sure the agent is using EOA address - * (depends on setting `requireEOAAddressProof`). - * NOTE: may only be called by a whitelisted agent (management or work owner address). - * @param _payment proof of payment on the underlying chain - */ - function proveUnderlyingAddressEOA( - IPayment.Proof calldata _payment - ) external; - /** * Create an agent vault. * The agent will always be identified by `_agentVault` address. @@ -326,7 +300,7 @@ interface IAssetManager is ) external; /** - * When current pool collateral token contract (WNat) is replaced by the method setPoolCollateralType, + * When current pool collateral token contract (WNat) is replaced by the method setPoolWNatCollateralType, * pools don't switch automatically. Instead, the agent must call this method that swaps old WNat tokens for * new ones and sets it for use by the pool. * NOTE: may only be called by the agent vault owner. @@ -426,24 +400,6 @@ interface IAssetManager is address _agentVault ) external; - //////////////////////////////////////////////////////////////////////////////////// - // Terminated asset manager support - - /** - * When f-asset is terminated, an agent can burn the market price of backed f-assets with his collateral, - * to release the remaining collateral (and, formally, underlying assets). - * This method ONLY works when f-asset is terminated, which will only be done when the asset manager - * is already paused at least for a month and most f-assets are already burned and the only ones - * remaining are unrecoverable. - * NOTE: may only be called by the agent vault owner. - * NOTE: the agent (management address) receives the vault collateral and NAT is burned instead. Therefore - * this method is `payable` and the caller must provide enough NAT to cover the received vault collateral - * amount multiplied by `vaultCollateralBuyForFlareFactorBIPS`. - */ - function buybackAgentCollateral( - address _agentVault - ) external payable; - //////////////////////////////////////////////////////////////////////////////////// // Agent information @@ -455,7 +411,7 @@ interface IAssetManager is */ function getAllAgents(uint256 _start, uint256 _end) external view - returns (address[] memory _agentVaults, uint256 _totalLength); + returns (address[] memory _agents, uint256 _totalLength); /** * Return detailed info about an agent, typically needed by a minter. @@ -473,8 +429,7 @@ interface IAssetManager is * @param _agentVault agent vault address * @param _name setting name, one of: `feeBIPS`, `poolFeeShareBIPS`, `redemptionPoolFeeShareBIPS`, * `mintingVaultCollateralRatioBIPS`, `mintingPoolCollateralRatioBIPS`,`buyFAssetByAgentFactorBIPS`, - * `poolExitCollateralRatioBIPS`, `poolTopupCollateralRatioBIPS`, `poolTopupTokenPriceFactorBIPS`, - * `handshakeType` + * `poolExitCollateralRatioBIPS` */ function getAgentSetting(address _agentVault, string memory _name) external view @@ -582,7 +537,7 @@ interface IAssetManager is */ function getAvailableAgentsList(uint256 _start, uint256 _end) external view - returns (address[] memory _agentVaults, uint256 _totalLength); + returns (address[] memory _agents, uint256 _totalLength); /** * Get (a part of) the list of available agents with extra information about agents' fee, min collateral ratio @@ -604,15 +559,11 @@ interface IAssetManager is * Before paying underlying assets for minting, minter has to reserve collateral and * pay collateral reservation fee. Collateral is reserved at ratio of agent's agentMinCollateralRatio * to requested lots NAT market price. - * If the agent requires handshake, then HandshakeRequired event is emitted and - * the minter has to wait for the agent to approve or reject the reservation. If there is no response within - * the `cancelCollateralReservationAfterSeconds`, the minter can cancel the reservation and get the fee back. - * If handshake is not required, the minter receives instructions for underlying payment + * The minter receives instructions for underlying payment * (value, fee and payment reference) in event CollateralReserved. * Then the minter has to pay `value + fee` on the underlying chain. - * If the minter pays the underlying amount, the collateral reservation fee is burned and minter obtains - * f-assets. Otherwise the agent collects the collateral reservation fee. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. + * If the minter pays the underlying amount, minter obtains f-assets. + * The collateral reservation fee is split between the agent and the collateral pool. * NOTE: the owner of the agent vault must be in the AgentOwnerRegistry. * @param _agentVault agent vault address * @param _lots the number of lots for which to reserve collateral @@ -621,45 +572,14 @@ interface IAssetManager is * and increasing fee (that would mean that the minter would have to pay raised fee or forfeit * collateral reservation fee) * @param _executor the account that is allowed to execute minting (besides minter and agent) - * @param _minterUnderlyingAddresses array of minter's underlying addresses - needed only if handshake is required */ function reserveCollateral( address _agentVault, uint256 _lots, uint256 _maxMintingFeeBIPS, - address payable _executor, - string[] calldata _minterUnderlyingAddresses - ) external payable; - - /** - * Agent approves the collateral reservation request after checking the minter's identity. - * NOTE: may only be called by the agent vault owner. - * @param _collateralReservationId collateral reservation id - */ - function approveCollateralReservation( - uint256 _collateralReservationId - ) external; - - /** - * Agent rejects the collateral reservation request after checking the minter's identity. - * The collateral reservation fee is returned to the minter. - * NOTE: may only be called by the agent vault owner. - * @param _collateralReservationId collateral reservation id - */ - function rejectCollateralReservation( - uint256 _collateralReservationId - ) external; - - /** - * Minter cancels the collateral reservation request if the agent didn't respond in time. - * The collateral reservation fee is returned to the minter. - * It can only be called after `cancelCollateralReservationAfterSeconds` from the collateral reservation request. - * NOTE: may only be called by the minter. - * @param _collateralReservationId collateral reservation id - */ - function cancelCollateralReservation( - uint256 _collateralReservationId - ) external; + address payable _executor + ) external payable + returns (uint256 _collateralReservationId); /** * Return the collateral reservation fee amount that has to be passed to the `reserveCollateral` method. @@ -686,8 +606,6 @@ interface IAssetManager is /** * After obtaining proof of underlying payment, the minter calls this method to finish the minting * and collect the minted f-assets. - * NOTE: In case handshake was required, the payment must be done using only all provided addresses, - * so `sourceAddressesRoot` matches the calculated Merkle root, otherwise the proof will be rejected. * NOTE: may only be called by the minter (= creator of CR, the collateral reservation request), * the executor appointed by the minter, or the agent owner (= owner of the agent vault in CR). * @param _payment proof of the underlying payment (must contain exact `value + fee` amount and correct @@ -703,9 +621,7 @@ interface IAssetManager is * When the time for the minter to pay the underlying amount is over (i.e. the last underlying block has passed), * the agent can declare payment default. Then the agent collects the collateral reservation fee * (it goes directly to the vault), and the reserved collateral is unlocked. - * NOTE: In case handshake was required, the attestation request must be done using `checkSourceAddresses=true` - * and correct `sourceAddressesRoot`, otherwise the proof will be rejected. If there was no handshake required, - * the attestation request must be done with `checkSourceAddresses=false`. + * NOTE: The attestation request must be done with `checkSourceAddresses=false`. * NOTE: may only be called by the owner of the agent vault in the collateral reservation request. * @param _proof proof that the minter didn't pay with correct payment reference on the underlying chain * @param _collateralReservationId id of a collateral reservation created by the minter @@ -750,7 +666,7 @@ interface IAssetManager is ) external; /** - * If an agent has enough free underlying, they can mint immediatelly without any underlying payment. + * If an agent has enough free underlying, they can mint immediately without any underlying payment. * This is a one-step process, skipping collateral reservation and collateral reservation fee payment. * Moreover, the agent doesn't have to be on the publicly available agents list to self-mint. * NOTE: may only be called by the agent vault owner. @@ -777,7 +693,6 @@ interface IAssetManager is * of remaining lots. * Agent receives redemption request id and instructions for underlying payment in * RedemptionRequested event and has to pay `value - fee` and use the provided payment reference. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _lots number of lots to redeem * @param _redeemerUnderlyingAddressString the address to which the agent must transfer underlying amount * @param _executor the account that is allowed to execute redemption default (besides redeemer and agent) @@ -791,28 +706,6 @@ interface IAssetManager is ) external payable returns (uint256 _redeemedAmountUBA); - /** - * In case agent requires handshake the redemption request can be rejected by the agent. - * Any other agent can take over the redemption request. - * If no agent takes over the redemption, the redeemer can request the default payment. - * NOTE: may only be called by the owner of the agent vault in the redemption request - * @param _redemptionRequestId id of an existing redemption request - */ - function rejectRedemptionRequest( - uint256 _redemptionRequestId - ) external; - - /** - * The agent can take over the rejected redemption request - it cannot be rejected again. - * NOTE: may only be called by the owner of the agent vault - * @param _agentVault agent vault address - * @param _redemptionRequestId id of an existing redemption request - */ - function takeOverRedemptionRequest( - address _agentVault, - uint256 _redemptionRequestId - ) external; - /** * If the redeemer provides invalid address, the agent should provide the proof of address invalidity from the * Flare data connector. With this, the agent's obligations are fulfilled and they can keep the underlying. @@ -864,20 +757,6 @@ interface IAssetManager is uint256 _redemptionRequestId ) external; - /** - * If the agent rejected the redemption request and no other agent took over the redemption, - * the redeemer calls this method and receives payment in collateral (with some extra). - * The agent can also call default if the redeemer is unresponsive, to payout the redeemer and free the - * remaining collateral. - * NOTE: may only be called by the redeemer (= creator of the redemption request), - * the executor appointed by the redeemer, - * or the agent owner (= owner of the agent vault in the redemption request) - * @param _redemptionRequestId id of an existing redemption request - */ - function rejectedRedemptionPaymentDefault( - uint256 _redemptionRequestId - ) external; - /** * If the agent hasn't performed the payment, the agent can close the redemption request to free underlying funds. * It can be done immediately after the redeemer or agent calls `redemptionPaymentDefault`, @@ -975,18 +854,15 @@ interface IAssetManager is // Liquidation /** - * Checks that the agent's collateral is too low and if true, starts the agent's liquidation. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. - * NOTE: always succeeds and returns the new liquidation status. + * Checks that the agent's collateral is too low and if true, starts agent's liquidation. + * If the agent is already in liquidation, returns the timestamp when liquidation started. * @param _agentVault agent vault address - * @return _liquidationStatus 0=no liquidation, 1=CCB, 2=liquidation - * @return _liquidationStartTs if the status is LIQUIDATION, the timestamp when liquidation started; - * if the status is CCB, the timestamp when liquidation will start; otherwise 0 + * @return _liquidationStartTs timestamp when liquidation started */ function startLiquidation( address _agentVault ) external - returns (uint8 _liquidationStatus, uint256 _liquidationStartTs); + returns (uint256 _liquidationStartTs); /** * Burns up to `_amountUBA` f-assets owned by the caller and pays @@ -994,7 +870,6 @@ interface IAssetManager is * (premium depends on the liquidation state). * If the agent isn't in liquidation yet, but satisfies conditions, * automatically puts the agent in liquidation status. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _agentVault agent vault address * @param _amountUBA the amount of f-assets to liquidate * @return _liquidatedAmountUBA liquidated amount of f-asset @@ -1028,12 +903,11 @@ interface IAssetManager is * no valid payment reference exists (valid payment references are from redemption and * underlying withdrawal announcement calls). * On success, immediately triggers full agent liquidation and rewards the caller. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. - * @param _transaction proof of a transaction from the agent's underlying address + * @param _payment proof of a transaction from the agent's underlying address * @param _agentVault agent vault address */ function illegalPaymentChallenge( - IBalanceDecreasingTransaction.Proof calldata _transaction, + IBalanceDecreasingTransaction.Proof calldata _payment, address _agentVault ) external; @@ -1041,7 +915,6 @@ interface IAssetManager is * Called with proofs of two payments made from the agent's underlying address * with the same payment reference (each payment reference is valid for only one payment). * On success, immediately triggers full agent liquidation and rewards the caller. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _payment1 proof of first payment from the agent's underlying address * @param _payment2 proof of second payment from the agent's underlying address * @param _agentVault agent vault address @@ -1057,7 +930,6 @@ interface IAssetManager is * underlying free balance negative (i.e. the underlying address balance is less than * the total amount of backed f-assets). * On success, immediately triggers full agent liquidation and rewards the caller. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _payments proofs of several distinct payments from the agent's underlying address * @param _agentVault agent vault address */ diff --git a/src/coston2/IAssetManagerController.sol b/src/coston2/IAssetManagerController.sol new file mode 100644 index 0000000..be64480 --- /dev/null +++ b/src/coston2/IAssetManagerController.sol @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {IAssetManager} from "./IAssetManager.sol"; + + +interface IAssetManagerController { + /** + * Return the list of all asset managers managed by this controller. + */ + function getAssetManagers() + external view + returns (IAssetManager[] memory); + + /** + * Check whether the asset manager is managed by this controller. + * @param _assetManager an asset manager address + */ + function assetManagerExists(address _assetManager) + external view + returns (bool); +} diff --git a/src/coston2/IAssetManagerEvents.sol b/src/coston2/IAssetManagerEvents.sol index 032d711..e9dd216 100644 --- a/src/coston2/IAssetManagerEvents.sol +++ b/src/coston2/IAssetManagerEvents.sol @@ -18,9 +18,7 @@ interface IAssetManagerEvents { uint256 mintingPoolCollateralRatioBIPS; uint256 buyFAssetByAgentFactorBIPS; uint256 poolExitCollateralRatioBIPS; - uint256 poolTopupCollateralRatioBIPS; - uint256 poolTopupTokenPriceFactorBIPS; - uint256 handshakeType; + uint256 redemptionPoolFeeShareBIPS; } /** @@ -115,18 +113,6 @@ interface IAssetManagerEvents { uint8 collateralClass, address token); - /** - * Minter reserved collateral, paid the reservation fee. Agent's collateral was reserved. - * Agent needs to approve or reject the reservation according to the minter's identity. - */ - event HandshakeRequired( - address indexed agentVault, - address indexed minter, - uint256 indexed collateralReservationId, - string[] minterUnderlyingAddresses, - uint256 valueUBA, - uint256 feeUBA); - /** * Minter reserved collateral, paid the reservation fee, and is expected to pay the underlying funds. * Agent's collateral was reserved. @@ -145,24 +131,6 @@ interface IAssetManagerEvents { address executor, uint256 executorFeeNatWei); - /** - * Agent rejected the collateral reservation request because of the minter's identity. - * Reserved collateral was released. - */ - event CollateralReservationRejected( - address indexed agentVault, - address indexed minter, - uint256 indexed collateralReservationId); - - /** - * Minter cancelled the collateral reservation request because of the agent's inactivity. - * Reserved collateral was released. - */ - event CollateralReservationCancelled( - address indexed agentVault, - address indexed minter, - uint256 indexed collateralReservationId); - /** * Minter paid underlying funds in time and received the fassets. * The agent's collateral is locked. @@ -227,34 +195,13 @@ interface IAssetManagerEvents { address executor, uint256 executorFeeNatWei); - /** - * Agent rejected the redemption request because of the redeemer's identity. - */ - event RedemptionRequestRejected( - address indexed agentVault, - address indexed redeemer, - uint64 indexed requestId, - string paymentAddress, - uint256 valueUBA); - - /** - * Agent's rejected redemption request was taken over by another agent. - */ - event RedemptionRequestTakenOver( - address indexed agentVault, - address indexed redeemer, - uint64 indexed requestId, - uint256 valueTakenOverUBA, - address newAgentVault, - uint64 newRequestId); - /** * Agent rejected the redemption payment because the redeemer's address is invalid. */ event RedemptionRejected( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, uint256 redemptionAmountUBA); /** @@ -273,7 +220,7 @@ interface IAssetManagerEvents { event RedemptionPerformed( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, bytes32 transactionHash, uint256 redemptionAmountUBA, int256 spentUnderlyingUBA); @@ -288,7 +235,7 @@ interface IAssetManagerEvents { event RedemptionDefault( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, uint256 redemptionAmountUBA, uint256 redeemedVaultCollateralWei, uint256 redeemedPoolCollateralWei); @@ -302,7 +249,7 @@ interface IAssetManagerEvents { event RedemptionPaymentBlocked( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, bytes32 transactionHash, uint256 redemptionAmountUBA, int256 spentUnderlyingUBA); @@ -314,7 +261,7 @@ interface IAssetManagerEvents { event RedemptionPaymentFailed( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, bytes32 transactionHash, int256 spentUnderlyingUBA, string failureReason); @@ -325,7 +272,7 @@ interface IAssetManagerEvents { */ event RedemptionPoolFeeMinted( address indexed agentVault, - uint64 indexed requestId, + uint256 indexed requestId, uint256 poolFeeUBA); /** @@ -379,14 +326,6 @@ interface IAssetManagerEvents { address indexed agentVault, uint256 dustUBA); - /** - * Agent entered CCB (collateral call band) due to being on the border of unhealthy. - * Agent has limited time to topup the collateral, otherwise liquidation starts. - */ - event AgentInCCB( - address indexed agentVault, - uint256 timestamp); - /** * Agent entered liquidation state due to unhealthy position. * The liquidation ends when the agent is again healthy or the agent's position is fully liquidated. @@ -434,7 +373,7 @@ interface IAssetManagerEvents { */ event UnderlyingWithdrawalAnnounced( address indexed agentVault, - uint64 indexed announcementId, + uint256 indexed announcementId, bytes32 paymentReference); /** @@ -445,7 +384,7 @@ interface IAssetManagerEvents { */ event UnderlyingWithdrawalConfirmed( address indexed agentVault, - uint64 indexed announcementId, + uint256 indexed announcementId, int256 spentUBA, bytes32 transactionHash); @@ -456,7 +395,7 @@ interface IAssetManagerEvents { */ event UnderlyingWithdrawalCancelled( address indexed agentVault, - uint64 indexed announcementId); + uint256 indexed announcementId); /** * Emitted when the agent tops up the underlying address balance. @@ -542,17 +481,15 @@ interface IAssetManagerEvents { string assetFtsoSymbol, string tokenFtsoSymbol, uint256 minCollateralRatioBIPS, - uint256 ccbMinCollateralRatioBIPS, uint256 safetyMinCollateralRatioBIPS); /** - * System defined collateral ratios for the token have changed (minimal, CCB and safety collateral ratio). + * System defined collateral ratios for the token have changed (minimal and safety collateral ratio). */ event CollateralRatiosChanged( uint8 collateralClass, address collateralToken, uint256 minCollateralRatioBIPS, - uint256 ccbMinCollateralRatioBIPS, uint256 safetyMinCollateralRatioBIPS); /** diff --git a/src/coston2/IClaimSetupManager.sol b/src/coston2/IClaimSetupManager.sol index 384de98..17cc70c 100644 --- a/src/coston2/IClaimSetupManager.sol +++ b/src/coston2/IClaimSetupManager.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IDelegationAccount.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IClaimSetupManager { diff --git a/src/songbird/ICoreVault.sol b/src/coston2/ICoreVaultClient.sol similarity index 90% rename from src/songbird/ICoreVault.sol rename to src/coston2/ICoreVaultClient.sol index d503cad..9340e57 100644 --- a/src/songbird/ICoreVault.sol +++ b/src/coston2/ICoreVaultClient.sol @@ -1,13 +1,13 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IFdcVerification.sol"; +import {IPayment} from ".//IFdcVerification.sol"; /** * Core vault */ -interface ICoreVault { +interface ICoreVaultClient { /** * Agent has requested transfer of (some of) their backing to the core vault. */ @@ -78,7 +78,7 @@ interface ICoreVault { * @param _amountUBA the amount to transfer to the core vault */ function transferToCoreVault(address _agentVault, uint256 _amountUBA) - external payable; + external; /** * Request that core vault transfers funds to the agent's underlying address, @@ -90,7 +90,7 @@ interface ICoreVault { * @param _agentVault the agent vault address * @param _lots number of lots (same lots as for minting and redemptions) */ - function requestReturnFromCoreVault(address _agentVault, uint64 _lots) + function requestReturnFromCoreVault(address _agentVault, uint256 _lots) external; /** @@ -118,19 +118,9 @@ interface ICoreVault { * must have been added to the `allowedDestinations` list in the core vault manager by * the governance before the redemption request. */ - function redeemFromCoreVault(uint64 _lots, string memory _redeemerUnderlyingAddress) + function redeemFromCoreVault(uint256 _lots, string memory _redeemerUnderlyingAddress) external; - /** - * Return the amount of NAT that has to be paid in `transferToCoreVault` call. - * @param _amountUBA the amount to transfer to the core vault - * @return _transferFeeNatWei the amount that has to be included as `msg.value` and is paid to the core vault - */ - function transferToCoreVaultFee( - uint256 _amountUBA - ) external view - returns (uint256 _transferFeeNatWei); - /** * Return the maximum amount that can be transferred and the minimum amount that * has to remain on the agent vault's underlying address. diff --git a/src/coston/ICoreVaultSettings.sol b/src/coston2/ICoreVaultClientSettings.sol similarity index 85% rename from src/coston/ICoreVaultSettings.sol rename to src/coston2/ICoreVaultClientSettings.sol index a43c345..c708303 100644 --- a/src/coston/ICoreVaultSettings.sol +++ b/src/coston2/ICoreVaultClientSettings.sol @@ -4,16 +4,13 @@ pragma solidity >=0.7.6 <0.9; /** * Core vault settings */ -interface ICoreVaultSettings { +interface ICoreVaultClientSettings { function setCoreVaultManager(address _coreVaultManager) external; function setCoreVaultNativeAddress(address payable _nativeAddress) external; - function setCoreVaultTransferFeeBIPS(uint256 _transferFeeBIPS) - external; - function setCoreVaultTransferTimeExtensionSeconds(uint256 _transferTimeExtensionSeconds) external; @@ -34,10 +31,6 @@ interface ICoreVaultSettings { external view returns (address); - function getCoreVaultTransferFeeBIPS() - external view - returns (uint256); - function getCoreVaultTransferTimeExtensionSeconds() external view returns (uint256); diff --git a/src/coston2/IDelegationAccount.sol b/src/coston2/IDelegationAccount.sol index 2093b99..815a909 100644 --- a/src/coston2/IDelegationAccount.sol +++ b/src/coston2/IDelegationAccount.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IClaimSetupManager.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDelegationAccount { diff --git a/src/coston2/IFdcVerification.sol b/src/coston2/IFdcVerification.sol index d7e51cd..b37662c 100644 --- a/src/coston2/IFdcVerification.sol +++ b/src/coston2/IFdcVerification.sol @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +import "./IRelay.sol"; import "./IAddressValidityVerification.sol"; import "./IBalanceDecreasingTransactionVerification.sol"; import "./IConfirmedBlockHeightExistsVerification.sol"; @@ -9,16 +10,25 @@ import "./IPaymentVerification.sol"; import "./IReferencedPaymentNonexistenceVerification.sol"; import "./IWeb2JsonVerification.sol"; - /** * FdcVerification interface. */ interface IFdcVerification is - IAddressValidityVerification, - IBalanceDecreasingTransactionVerification, - IConfirmedBlockHeightExistsVerification, - IEVMTransactionVerification, - IPaymentVerification, - IReferencedPaymentNonexistenceVerification, - IWeb2JsonVerification -{ } + IAddressValidityVerification, + IBalanceDecreasingTransactionVerification, + IConfirmedBlockHeightExistsVerification, + IEVMTransactionVerification, + IPaymentVerification, + IReferencedPaymentNonexistenceVerification, + IWeb2JsonVerification +{ + /** + * The FDC protocol id. + */ + function fdcProtocolId() external view returns (uint8 _fdcProtocolId); + + /** + * Relay contract address. + */ + function relay() external view returns (IRelay); +} diff --git a/src/coston2/IFtsoManager.sol b/src/coston2/IFtsoManager.sol index ed1c4c0..cfc7cc5 100644 --- a/src/coston2/IFtsoManager.sol +++ b/src/coston2/IFtsoManager.sol @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./ftso/interface/IIFtso.sol"; -import "./genesis/interface/IFtsoManagerGenesis.sol"; +import "./ftso/interfaces/IIFtso.sol"; +import "./genesis/interfaces/IFtsoManagerGenesis.sol"; interface IFtsoManager is IFtsoManagerGenesis { diff --git a/src/coston2/IFtsoRegistry.sol b/src/coston2/IFtsoRegistry.sol index f9d8c6a..46ab964 100644 --- a/src/coston2/IFtsoRegistry.sol +++ b/src/coston2/IFtsoRegistry.sol @@ -2,8 +2,8 @@ pragma solidity >=0.7.6 <0.9; pragma abicoder v2; -import "./ftso/interface/IIFtso.sol"; -import "./genesis/interface/IFtsoRegistryGenesis.sol"; +import "./ftso/interfaces/IIFtso.sol"; +import "./genesis/interfaces/IFtsoRegistryGenesis.sol"; interface IFtsoRegistry is IFtsoRegistryGenesis { diff --git a/src/coston2/IGovernor.sol b/src/coston2/IGovernor.sol index 48bdd0f..fff729f 100644 --- a/src/coston2/IGovernor.sol +++ b/src/coston2/IGovernor.sol @@ -1,14 +1,12 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; -/** - * Governor interface. - */ interface IGovernor { struct GovernorSettings { bool accept; - uint256 votingStartTs; + uint256 votingDelaySeconds; uint256 votingPeriodSeconds; uint256 vpBlockPeriodSeconds; uint256 thresholdConditionBIPS; @@ -18,15 +16,7 @@ interface IGovernor { } /** - * Enum describing a proposal state. - - * A proposal is: - * * `Pending` when first created, - * * `Active` when it’s being voted on, - * * `Defeated` or `Succeeded` as a result of the vote, - * * `Queued` when in the process of executing, - * * `Expired` when it times out or fails to execute upon a certain date, and - * * `Executed` when it goes live. + * @notice Enum describing a proposal state */ enum ProposalState { Pending, @@ -40,7 +30,7 @@ interface IGovernor { } /** - * Event emitted when a proposal is created. + * @notice Event emitted when a proposal is created */ event ProposalCreated( uint256 indexed proposalId, @@ -59,17 +49,17 @@ interface IGovernor { ); /** - * Event emitted when a proposal is canceled. + * @notice Event emitted when a proposal is canceled */ event ProposalCanceled(uint256 indexed proposalId); /** - * Event emitted when a proposal is executed. + * @notice Event emitted when a proposal is executed */ event ProposalExecuted(uint256 indexed proposalId); /** - * Event emitted when a vote is cast. + * @notice Event emitted when a vote is cast */ event VoteCast( address indexed voter, @@ -80,30 +70,30 @@ interface IGovernor { uint256 forVotePower, uint256 againstVotePower ); - + /** - * Cancels a proposal. - * @param _proposalId Unique identifier obtained by hashing proposal data. - * Emits a ProposalCanceled event + * @notice Cancels a proposal + * @param _proposalId Unique identifier obtained by hashing proposal data + * @notice Emits a ProposalCanceled event */ function cancel(uint256 _proposalId) external; /** - * Casts a vote on a proposal. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @return Vote power of the cast vote. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @return Vote power of the cast vote + * @notice Emits a VoteCast event */ function castVote(uint256 _proposalId, uint8 _support) external returns (uint256); /** - * Casts a vote on a proposal with a reason. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @param _reason Vote reason. - * @return Vote power of the cast vote. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal with a reason + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @param _reason Vote reason + * @return Vote power of the cast vote + * @notice Emits a VoteCast event */ function castVoteWithReason( uint256 _proposalId, @@ -112,13 +102,13 @@ interface IGovernor { ) external returns (uint256); /** - * Casts a vote on a proposal using the user cryptographic signature. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @param _v v part of the signature. - * @param _r r part of the signature. - * @param _s s part of the signature. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal using the user cryptographic signature + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @param _v v part of the signature + * @param _r r part of the signature + * @param _s s part of the signature + * @notice Emits a VoteCast event */ function castVoteBySig( uint256 _proposalId, @@ -129,84 +119,63 @@ interface IGovernor { ) external returns (uint256); /** - * Executes a successful proposal without execution parameters. - * @param _proposalId Id of the proposal. - * Emits a ProposalExecuted event. + * @notice Executes a successful proposal without execution parameters + * @param _description String description of the proposal + * @notice Emits a ProposalExecuted event */ - function execute(uint256 _proposalId) external; + function execute(string memory _description) external returns (uint256); /** - * Executes a successful proposal. - * @param _proposalId Id of the proposal. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * Emits a ProposalExecuted event. + * @notice Executes a successful proposal with execution parameters + * @param _targets Array of target addresses on which the calls are to be invoked + * @param _values Array of values with which the calls are to be invoked + * @param _calldatas Array of call data to be invoked + * @param _description String description of the proposal + * @notice Emits a ProposalExecuted event */ function execute( - uint256 _proposalId, address[] memory _targets, uint256[] memory _values, - bytes[] memory _calldatas - ) external payable; + bytes[] memory _calldatas, + string memory _description + ) external payable returns (uint256); /** - * Returns the current state of a proposal. - * @param _proposalId Id of the proposal. - * @return ProposalState enum. + * @notice Returns the current state of a proposal + * @param _proposalId Id of the proposal + * @return ProposalState enum */ function state(uint256 _proposalId) external view returns (ProposalState); /** - * Returns the vote power of a voter at a specific block number. - * @param _voter Address of the voter. - * @param _blockNumber The block number. - * @return Vote power of the voter at the block number. + * @notice Returns the vote power of a voter at a specific block number + * @param _voter Address of the voter + * @param _blockNumber The block number + * @return Vote power of the voter at the block number */ function getVotes(address _voter, uint256 _blockNumber) external view returns (uint256); /** - * Returns information if a voter has cast a vote on a specific proposal. - * @param _proposalId Id of the proposal. - * @param _voter Address of the voter. - * @return True if the voter has cast a vote on the proposal, and false otherwise. + * @notice Returns information if a voter has cast a vote on a specific proposal + * @param _proposalId Id of the proposal + * @param _voter Address of the voter + * @return True if the voter has cast a vote on the proposal, and false otherwise */ function hasVoted(uint256 _proposalId, address _voter) external view returns (bool); /** - * Returns proposal id determined by hashing proposal data. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * @param _description Description of the proposal. - * @return Proposal id. - */ - function getProposalId( - address[] memory _targets, - uint256[] memory _values, - bytes[] memory _calldatas, - string memory _description - ) external view returns (uint256); - - /** - * Returns the list of proposal ids. - */ - function getProposalIds() external view returns (uint256[] memory); - - /** - * Returns information of the specified proposal. - * @param _proposalId Id of the proposal. - * @return _proposer Address of the proposal submitter. - * @return _accept Type of the proposal - accept or reject. - * @return _votePowerBlock Block number used to determine the vote powers in voting process. - * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting. - * @return _voteEndTime End time (in seconds from epoch) of the proposal voting. - * @return _execStartTime Start time (in seconds from epoch) of the proposal execution window. - * @return _execEndTime End time (in seconds from epoch) of the proposal exectuion window. - * @return _thresholdConditionBIPS Percentage in BIPS of the total vote power required for proposal "quorum". - * @return _majorityConditionBIPS Percentage in BIPS of the proper relation between FOR and AGAINST votes. - * @return _circulatingSupply Circulating supply at votePowerBlock. - * @return _description Description of the proposal. + * @notice Returns information of the specified proposal + * @param _proposalId Id of the proposal + * @return _proposer Address of the proposal submitter + * @return _accept Type of the proposal - accept or reject + * @return _votePowerBlock Block number used to determine the vote powers in voting process + * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting + * @return _voteEndTime End time (in seconds from epoch) of the proposal voting + * @return _execStartTime Start time (in seconds from epoch) of the proposal execution window + * @return _execEndTime End time (in seconds from epoch) of the proposal exectuion window + * @return _thresholdConditionBIPS Percentage in BIPS of the total vote power required for proposal "quorum" + * @return _majorityConditionBIPS Percentage in BIPS of the proper relation between FOR and AGAINST votes + * @return _circulatingSupply Circulating supply at votePowerBlock */ function getProposalInfo( uint256 _proposalId @@ -222,20 +191,19 @@ interface IGovernor { uint256 _execEndTime, uint256 _thresholdConditionBIPS, uint256 _majorityConditionBIPS, - uint256 _circulatingSupply, - string memory _description + uint256 _circulatingSupply ); /** - * Returns votes (for, against) of the specified proposal. - * @param _proposalId Id of the proposal. - * @return _for Accumulated vote power for the proposal. - * @return _against Accumulated vote power against the proposal. + * @notice Returns votes (for, against) of the specified proposal + * @param _proposalId Id of the proposal + * @return _for Accumulated vote power for the proposal + * @return _against Accumulated vote power against the proposal */ function getProposalVotes( uint256 _proposalId ) - external view + external view returns ( uint256 _for, uint256 _against diff --git a/src/coston2/IPollingFtso.sol b/src/coston2/IPollingFtso.sol new file mode 100644 index 0000000..7bbf313 --- /dev/null +++ b/src/coston2/IPollingFtso.sol @@ -0,0 +1,295 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IPollingFtso { + + /** + * @notice Struct holding the information about proposal properties + */ + struct Proposal { + string description; // description of the proposal + address proposer; // address of the proposer + bool canceled; // flag indicating if proposal has been canceled + uint256 voteStartTime; // start time of voting window (in seconds from epoch) + uint256 voteEndTime; // end time of voting window (in seconds from epoch) + uint256 thresholdConditionBIPS; // percentage in BIPS of the total vote power required for proposal "quorum" + uint256 majorityConditionBIPS; // percentage in BIPS of the proper relation between FOR and AGAINST votes + mapping(address => bool) isEligible; // flag if an address is eligible to cast a vote in a proposal + uint256 noOfEligibleMembers; // number of addresses that can vote in the proposal + } + + /** + * @notice Struct holding the information about proposal voting + */ + struct ProposalVoting { + uint256 againstVotePower; // accumulated vote power against the proposal + uint256 forVotePower; // accumulated vote power for the proposal + mapping(address => bool) hasVoted; // flag if a voter has cast a vote + } + + /** + * @notice Enum describing a proposal state + */ + enum ProposalState { + Canceled, + Pending, + Active, + Defeated, + Succeeded + } + + /** + * @notice Enum that determines vote (support) type + * @dev 0 = Against, 1 = For + */ + enum VoteType { + Against, + For + } + + /** + * @notice Event emitted when a proposal is created + */ + event FtsoProposalCreated( + uint256 indexed proposalId, + address proposer, + string description, + uint256 voteStartTime, + uint256 voteEndTime, + uint256 thresholdConditionBIPS, + uint256 majorityConditionBIPS, + address[] eligibleMembers + ); + + /** + * @notice Event emitted when a vote is cast + */ + event VoteCast( + address indexed voter, + uint256 indexed proposalId, + uint8 support, + uint256 forVotePower, + uint256 againstVotePower + ); + + /** + * @notice Event emitted when a proposal is canceled + */ + event ProposalCanceled(uint256 indexed proposalId); + + /** + * @notice Event emitted when parameters are set + */ + event ParametersSet( + uint256 votingDelaySeconds, + uint256 votingPeriodSeconds, + uint256 thresholdConditionBIPS, + uint256 majorityConditionBIPS, + uint256 proposalFeeValueWei, + uint256 addAfterRewardedEpochs, + uint256 addAfterNotChilledEpochs, + uint256 removeAfterNotRewardedEpochs, + uint256 removeAfterEligibleProposals, + uint256 removeAfterNonParticipatingProposals, + uint256 removeForDays + ); + + /** + * @notice Event emitted when management group member is added + */ + event ManagementGroupMemberAdded(address addedMember); + + /** + * @notice Event emitted when management group member is removed + */ + event ManagementGroupMemberRemoved(address removedMember); + + /** + * @notice Event emitted when maintainer is set + */ + event MaintainerSet(address newMaintainer); + + /** + * @notice Event emitted when proxy voter is set + */ + event ProxyVoterSet(address account, address proxyVoter); + + /** + * @notice Sets (or changes) contract's parameters. It is called after deployment of the contract + * and every time one of the parameters changes. + */ + function setParameters( + uint256 _votingDelaySeconds, + uint256 _votingPeriodSeconds, + uint256 _thresholdConditionBIPS, + uint256 _majorityConditionBIPS, + uint256 _proposalFeeValueWei, + uint256 _addAfterRewardedEpochs, + uint256 _addAfterNotChilledEpochs, + uint256 _removeAfterNotRewardedEpochs, + uint256 _removeAfterEligibleProposals, + uint256 _removeAfterNonParticipatingProposals, + uint256 _removeForDays + ) + external; + + /** + * @notice Cancels an existing proposal + * @param _proposalId Unique identifier of a proposal + * @notice Emits a ProposalCanceled event + */ + function cancel(uint256 _proposalId) external; + + /** + * @notice Creates a new proposal + * @param _description String description of the proposal + * @return _proposalId Unique identifier of the proposal + * @notice Emits a FtsoProposalCreated event + */ + function propose( + string memory _description + ) external payable returns (uint256); + + /** + * @notice Casts a vote on a proposal + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @notice Emits a VoteCast event + */ + function castVote(uint256 _proposalId, uint8 _support) external; + + /** + * @notice Changes list of management group members + * @param _providersToAdd Array of addresses to add to the list + * @param _providersToRemove Array of addresses to remove from the list + * @notice This operation can only be performed through a maintainer + * (mostly used for manually adding KYCed providers) + */ + function changeManagementGroupMembers( + address[] memory _providersToAdd, + address[] memory _providersToRemove + ) external; + + /** + * @notice Sets a proxy voter for data provider (i.e. address that can vote in his name) + * @param _proxyVoter Address to register as a proxy (use address(0) to remove proxy) + * @notice Emits a ProxyVoterSet event + */ + function setProxyVoter(address _proxyVoter) external; + + /** + * @notice Adds msg.sender to the management group + */ + function addMember() external; + + /** + * @notice Removes member from the management group + * @param _account Account to remove from the management group + */ + function removeMember(address _account) external; + + /** + * @notice Returns the current state of a proposal + * @param _proposalId Id of the proposal + * @return ProposalState enum + */ + function state(uint256 _proposalId) external view returns (ProposalState); + + /** + * @notice Returns whether a voter has cast a vote on a specific proposal + * @param _proposalId Id of the proposal + * @param _voter Address of the voter + * @return True if the voter has cast a vote on the proposal, and false otherwise + */ + function hasVoted(uint256 _proposalId, address _voter) external view returns (bool); + + /** + * @notice Returns information about the specified proposal + * @param _proposalId Id of the proposal + * @return _description Description of the proposal + * @return _proposer Address of the proposal submitter + * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting + * @return _voteEndTime End time (in seconds from epoch) of the proposal voting + * @return _thresholdConditionBIPS Total number of cast votes, as a percentage in BIPS of the + total vote power, required for the proposal to pass (quorum) + * @return _majorityConditionBIPS Number of FOR votes, as a percentage in BIPS of the + total cast votes, requires for the proposal to pass + * @return _noOfEligibleMembers Number of members that are eligible to vote in the specified proposal + */ + function getProposalInfo( + uint256 _proposalId + ) + external view + returns ( + string memory _description, + address _proposer, + uint256 _voteStartTime, + uint256 _voteEndTime, + uint256 _thresholdConditionBIPS, + uint256 _majorityConditionBIPS, + uint256 _noOfEligibleMembers + ); + + /** + * @notice Returns the description string that was supplied when the specified proposal was created + * @param _proposalId Id of the proposal + * @return _description Description of the proposal + */ + function getProposalDescription(uint256 _proposalId) external view + returns (string memory _description); + + /** + * @notice Returns id and description of the last created proposal + * @return _proposalId Id of the last proposal + * @return _description Description of the last proposal + */ + function getLastProposal() external view + returns ( uint256 _proposalId, string memory _description); + + /** + * @notice Returns number of votes for and against the specified proposal + * @param _proposalId Id of the proposal + * @return _for Accumulated vote power for the proposal + * @return _against Accumulated vote power against the proposal + */ + function getProposalVotes( + uint256 _proposalId + ) + external view + returns ( + uint256 _for, + uint256 _against + ); + + /** + * @notice Returns list of current management group members + * @return _list List of management group members + */ + function getManagementGroupMembers() external view returns (address[] memory _list); + + /** + * @notice Returns whether an account can create proposals + * @notice An address can make proposals if it is a member of the management group, + * one of their proxies or the maintainer of the contract + * @param _account Address of a queried account + * @return True if a queried account can propose, false otherwise + */ + function canPropose(address _account) external view returns (bool); + + /** + * @notice Returns whether an account can vote for a given proposal + * @param _account Address of the queried account + * @param _proposalId Id of the queried proposal + * @return True if account is eligible to vote, and false otherwise + */ + function canVote(address _account, uint256 _proposalId) external view returns (bool); + + /** + * @notice Returns whether an account is member of the management group + * @param _account Address of the queried account + * @return True if the queried account is member, false otherwise + */ + function isMember(address _account) external view returns (bool); +} diff --git a/src/coston2/IPriceSubmitter.sol b/src/coston2/IPriceSubmitter.sol index 54ebf98..4fbbf35 100644 --- a/src/coston2/IPriceSubmitter.sol +++ b/src/coston2/IPriceSubmitter.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./genesis/interface/IFtsoGenesis.sol"; -import "./genesis/interface/IFtsoRegistryGenesis.sol"; -import "./genesis/interface/IFtsoManagerGenesis.sol"; +import "./genesis/interfaces/IFtsoGenesis.sol"; +import "./genesis/interfaces/IFtsoRegistryGenesis.sol"; +import "./genesis/interfaces/IFtsoManagerGenesis.sol"; interface IPriceSubmitter { /** diff --git a/src/coston2/IRNat.sol b/src/coston2/IRNat.sol index b710fd2..76bf5bc 100644 --- a/src/coston2/IRNat.sol +++ b/src/coston2/IRNat.sol @@ -3,7 +3,7 @@ pragma solidity >=0.7.6 <0.9; import "./IRNatAccount.sol"; import "./IWNat.sol"; -import "@openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol"; +import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IRNat is IERC20Metadata { diff --git a/src/coston2/IRNatAccount.sol b/src/coston2/IRNatAccount.sol index d8c465d..fea1340 100644 --- a/src/coston2/IRNatAccount.sol +++ b/src/coston2/IRNatAccount.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IRNat.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRNatAccount { diff --git a/src/coston2/ITransferFees.sol b/src/coston2/ITransferFees.sol deleted file mode 100644 index bdbbb1d..0000000 --- a/src/coston2/ITransferFees.sol +++ /dev/null @@ -1,115 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.7.6 <0.9; - - -/** - * FAsset transfer (trailing) fees. - */ -interface ITransferFees { - /** - * An agent has claimed their share of transfer fees. - */ - event TransferFeesClaimed( - address indexed agentVault, - address recipient, - uint256 agentClaimedUBA, - uint256 poolClaimedUBA, - uint256 remainingUnclaimedEpochs); - - /** - * Transfer fee will change at timestamp `scheduledAt`. - */ - event TransferFeeChangeScheduled( - uint256 nextTransferFeeMillionths, - uint256 scheduledAt); - - /** - * Claim FAsset transfer fees by an agent. - * NOTE: may only be called by the agent vault owner - * @param _agentVault the agent vault for which to claim - * @param _recipient the account that will receive agent's share of fasset fees - * @param _maxEpochsToClaim limit the number of epochs to claim, to avoid using too much gas - * @return _agentClaimedUBA agent's share of total claimed amount in FAsset UBA - * @return _poolClaimedUBA pool share of total claimed amount in FAsset UBA - * @return _remainingUnclaimedEpochs nonzero when _maxEpochsToClaim is smaller then the number of unclaimed epochs - */ - function claimTransferFees(address _agentVault, address _recipient, uint256 _maxEpochsToClaim) - external - returns (uint256 _agentClaimedUBA, uint256 _poolClaimedUBA, uint256 _remainingUnclaimedEpochs); - - function currentTransferFeeEpoch() - external view - returns (uint256); - - function firstClaimableTransferFeeEpoch() - external view - returns (uint256); - - function agentUnclaimedTransferFeeEpochs(address _agentVault) - external view - returns (uint256 _first, uint256 _count); - - function agentTransferFeeShare(address _agentVault, uint256 _maxEpochsToClaim) - external view - returns (uint256 _feeShareUBA); - - function agentTransferFeeShareForEpoch(address _agentVault, uint256 _epoch) - external view - returns (uint256); - - function transferFeeMillionths() - external view - returns (uint256); - - function setTransferFeeMillionths(uint256 _value, uint256 _scheduledAt) - external; - - //////////////////////////////////////////////////////////////////////////////////// - // Internal methods - - function fassetTransferFeePaid(uint256 _fee) - external; - - function initAgentsMintingHistory(address[] calldata _agentVaults) - external; - - //////////////////////////////////////////////////////////////////////////////////// - // Methods for testing and inspection - - struct TransferFeeSettings { - uint256 transferFeeMillionths; - uint256 firstEpochStartTs; - uint256 epochDuration; - uint256 maxUnexpiredEpochs; - uint256 firstClaimableEpoch; - } - - struct TransferFeeEpochData { - uint256 startTs; - uint256 endTs; - uint256 totalFees; - uint256 claimedFees; - bool claimable; - bool expired; - } - - struct TransferFeeCalculationDataForAgent { - uint256 totalFees; - uint256 cumulativeMinted; - uint256 totalCumulativeMinted; - bool claimable; - bool claimed; - } - - function transferFeeSettings() - external view - returns (TransferFeeSettings memory); - - function transferFeeEpochData(uint256 _epoch) - external view - returns (TransferFeeEpochData memory); - - function transferFeeCalculationDataForAgent(address _agentVault, uint256 _epoch) - external view - returns (TransferFeeCalculationDataForAgent memory); -} diff --git a/src/coston2/IVPToken.sol b/src/coston2/IVPToken.sol index 4ff0be0..f874698 100644 --- a/src/coston2/IVPToken.sol +++ b/src/coston2/IVPToken.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import {IERC20} from "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IGovernanceVotePower} from "./IGovernanceVotePower.sol"; import {IVPContractEvents} from "./IVPContractEvents.sol"; diff --git a/src/coston2/IVoterPreRegistry.sol b/src/coston2/IVoterPreRegistry.sol index c7d09c9..6e0a524 100644 --- a/src/coston2/IVoterPreRegistry.sol +++ b/src/coston2/IVoterPreRegistry.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./protocol/interface/IIVoterRegistry.sol"; +import "./protocol/interfaces/IIVoterRegistry.sol"; interface IVoterPreRegistry { diff --git a/src/coston2/IWNat.sol b/src/coston2/IWNat.sol index ade3c7a..59cee8e 100644 --- a/src/coston2/IWNat.sol +++ b/src/coston2/IWNat.sol @@ -1,42 +1,34 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IVPToken.sol"; -import "./token/interface/IICleanable.sol"; - - -/** - * @title Wrapped Native token - * Accept native token deposits and mint ERC20 WNAT (wrapped native) tokens 1-1. - */ -interface IWNat is IVPToken, IICleanable { +interface IWNat { /** - * Deposit Native and mint wNat ERC20. + * @notice Deposit native token and mint WNAT ERC20. */ function deposit() external payable; /** - * Deposit Native from msg.sender and mints WNAT ERC20 to recipient address. - * @param recipient An address to receive minted WNAT. + * @notice Withdraw native token and burn WNAT ERC20. + * @param _amount The amount to withdraw. */ - function depositTo(address recipient) external payable; - + function withdraw(uint256 _amount) external; + /** - * Withdraw Native and burn WNAT ERC20. - * @param amount The amount to withdraw. + * @notice Deposit native token from msg.sender and mint WNAT ERC20. + * @param _recipient An address to receive minted WNAT. */ - function withdraw(uint256 amount) external; - + function depositTo(address _recipient) external payable; + /** - * Withdraw WNAT from an owner and send native tokens to msg.sender given an allowance. - * @param owner An address spending the Native tokens. - * @param amount The amount to spend. + * @notice Withdraw WNAT from an owner and send NAT to msg.sender given an allowance. + * @param _owner An address spending the native tokens. + * @param _amount The amount to spend. * * Requirements: * - * - `owner` must have a balance of at least `amount`. - * - the caller must have allowance for `owners`'s tokens of at least - * `amount`. + * - `_owner` must have a balance of at least `_amount`. + * - the caller must have allowance for `_owners`'s tokens of at least + * `_amount`. */ - function withdrawFrom(address owner, uint256 amount) external; + function withdrawFrom(address _owner, uint256 _amount) external; } diff --git a/src/coston2/IWeb2JsonVerification.sol b/src/coston2/IWeb2JsonVerification.sol index 8369e1a..d0a5d25 100644 --- a/src/coston2/IWeb2JsonVerification.sol +++ b/src/coston2/IWeb2JsonVerification.sol @@ -4,5 +4,5 @@ pragma solidity >=0.7.6 <0.9; import "./IWeb2Json.sol"; interface IWeb2JsonVerification { - function verifyJsonApi(IWeb2Json.Proof calldata _proof) external view returns (bool _proved); + function verifyWeb2Json(IWeb2Json.Proof calldata _proof) external view returns (bool _proved); } diff --git a/src/coston2/addressUpdater/interfaces/IIAddressUpdatable.sol b/src/coston2/addressUpdater/interfaces/IIAddressUpdatable.sol new file mode 100644 index 0000000..e8bd84e --- /dev/null +++ b/src/coston2/addressUpdater/interfaces/IIAddressUpdatable.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IIAddressUpdatable { + /** + * @notice Updates contract addresses - should be called only from AddressUpdater contract + * @param _contractNameHashes list of keccak256(abi.encode(...)) contract names + * @param _contractAddresses list of contract addresses corresponding to the contract names + */ + function updateContractAddresses( + bytes32[] memory _contractNameHashes, + address[] memory _contractAddresses + ) external; +} diff --git a/src/coston2/addressUpdater/interfaces/IIAddressUpdater.sol b/src/coston2/addressUpdater/interfaces/IIAddressUpdater.sol new file mode 100644 index 0000000..9973368 --- /dev/null +++ b/src/coston2/addressUpdater/interfaces/IIAddressUpdater.sol @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IIAddressUpdater { + + /** + * @notice Returns all contract names and corresponding addresses + */ + function getContractNamesAndAddresses() external view returns( + string[] memory _contractNames, + address[] memory _contractAddresses + ); + + /** + * @notice Returns contract address for the given name - might be address(0) + * @param _name name of the contract + */ + function getContractAddress(string calldata _name) external view returns(address); + + /** + * @notice Returns contract address for the given name hash - might be address(0) + * @param _nameHash hash of the contract name (keccak256(abi.encode(name)) + */ + function getContractAddressByHash(bytes32 _nameHash) external view returns(address); + + /** + * @notice Returns contract addresses for the given names - might be address(0) + * @param _names names of the contracts + */ + function getContractAddresses(string[] calldata _names) external view returns(address[] memory); + + /** + * @notice Returns contract addresses for the given name hashes - might be address(0) + * @param _nameHashes hashes of the contract names (keccak256(abi.encode(name)) + */ + function getContractAddressesByHash(bytes32[] calldata _nameHashes) external view returns(address[] memory); +} diff --git a/src/coston2/assetRegistry/interfaces/IIERC20WithMetadata.sol b/src/coston2/assetRegistry/interfaces/IIERC20WithMetadata.sol new file mode 100644 index 0000000..68a9631 --- /dev/null +++ b/src/coston2/assetRegistry/interfaces/IIERC20WithMetadata.sol @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + + +/** + * The methods of this interface are optional in ERC20 standard, so they are left out of IERC20 interface. + * However, any sane implementation includes them, and they are mandatory for the tokens in FlareAssetRegistry. + */ +interface IIERC20WithMetadata is IERC20 { + /** + * Returns the name of the token. + */ + function name() external view returns (string memory); + + /** + * Returns the symbol of the token, usually a shorter version of the name. + */ + function symbol() external view returns (string memory); + + /** + * Returns the number of decimals used to get its user representation. + * For example, if `decimals` equals `2`, a balance of `505` tokens should + * be displayed to a user as `5,05` (`505 / 10 ** 2`). + * + * Tokens usually opt for a value of 18, imitating the relationship between + * Ether and Wei. + * + * NOTE: This information is only used for _display_ purposes: the methods + * of the contract should always work with the smallest unit (e.g. wei). + */ + function decimals() external view returns (uint8); +} diff --git a/src/coston2/assetRegistry/interfaces/IIFlareAssetRegistry.sol b/src/coston2/assetRegistry/interfaces/IIFlareAssetRegistry.sol new file mode 100644 index 0000000..daa0284 --- /dev/null +++ b/src/coston2/assetRegistry/interfaces/IIFlareAssetRegistry.sol @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../IFlareAssetRegistry.sol"; + + +interface IIFlareAssetRegistry is IFlareAssetRegistry { + /** + * Allows a provider contract to register assets. + * @param _provider address of the provider (a contract implementing IIFlareAssetRegistryProvider) + * @param _registerAssets if true, all the assets held by the provider are immediately registered; + * should usually be true, but can be false to avoid unbounded work in some cases + * @dev Only governance can call. + */ + function registerProvider(address _provider, bool _registerAssets) external; + + /** + * Remove the provider contract from known providers (e.g. when a new version of the provider is deployed, the + * old one will be removed). + * @param _provider address of the provider (a contract implementing IIFlareAssetRegistryProvider) + * @param _unregisterAssets if true, all the assets belonging to the provider are automatically unregistered; + * should usually be true, but can be false to avoid unbounded work in some cases - in this case, + * all the assets must be unregistered before calling this method + * @dev Only governance can call. + */ + function unregisterProvider(address _provider, bool _unregisterAssets) external; + + /** + * Unregisters and re-registers all the assets belonging to the given provider. + * @param _provider address of the provider (a contract implementing IIFlareAssetRegistryProvider) + * @dev Only governance can call (without timelock). + */ + function refreshProviderAssets(address _provider) external; + + /** + * Register a new asset. + * @param _token address of the asset (a contract implementing IERC20 interface with implemented symbol()) + * @dev Can only be called by a registered provider. + */ + function registerAsset(address _token) external; + + /** + * Unregister an asset. + * @param _token address of the asset (a contract implementing IERC20 interface with implemented symbol()) + * @dev Can only be called by the provider which registered the token. + */ + function unregisterAsset(address _token) external; +} diff --git a/src/coston2/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol b/src/coston2/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol new file mode 100644 index 0000000..6d9cde2 --- /dev/null +++ b/src/coston2/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IIFlareAssetRegistryProvider { + /** + * Returns a unique hash identifying this provider and its assets. + */ + function assetType() external view returns (bytes32); + + /** + * @notice Returns the addresses of all Flare Assets + */ + function allAssets() external view returns (address[] memory); + + /** + * @notice Returns a generic asset attribute value. + * @param _token The token's address + * @param _nameHash attributes name's hash + * @return _defined true if the attribute is defined for this token + * @return _value attribute value, may have to be cast into some other type + */ + function getAttribute(address _token, bytes32 _nameHash) external view returns (bool _defined, bytes32 _value); + +} diff --git a/src/coston2/customFeeds/interface/IICustomFeed.sol b/src/coston2/customFeeds/interfaces/IICustomFeed.sol similarity index 100% rename from src/coston2/customFeeds/interface/IICustomFeed.sol rename to src/coston2/customFeeds/interfaces/IICustomFeed.sol diff --git a/src/coston/userInterfaces/data/AgentInfo.sol b/src/coston2/data/AgentInfo.sol similarity index 89% rename from src/coston/userInterfaces/data/AgentInfo.sol rename to src/coston2/data/AgentInfo.sol index cace872..d105789 100644 --- a/src/coston/userInterfaces/data/AgentInfo.sol +++ b/src/coston2/data/AgentInfo.sol @@ -1,189 +1,143 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; - +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AgentInfo { enum Status { // agent is operating normally NORMAL, - // agent in collateral call band - CCB, // liquidation due to collateral ratio - ends when agent is healthy LIQUIDATION, // illegal payment liquidation - always liquidates all and then agent must close vault FULL_LIQUIDATION, // agent announced destroy, cannot mint again; all existing mintings have been redeemed before - DESTROYING + DESTROYING, + // agent has been destroyed, cannot do anything except return info + // owner can still withdraw tokens from the vault + DESTROYED } struct Info { // Current agent's status. AgentInfo.Status status; - // Agent vault owner's management address, used for occasional administration. // Immutable. address ownerManagementAddress; - // Agent vault owner's work address, used for automatic operations. // Can be changed by a call from the owner's management address. address ownerWorkAddress; - // Agent's collateral pool address address collateralPool; - // Agent collateral pool's pool token address address collateralPoolToken; - // Underlying address as string - to be used for minting payments. // For most other purposes, you use underlyingAddressHash, which is `keccak256(underlyingAddressString)`. string underlyingAddressString; - // If true, anybody can mint against this agent. // If false, the agent can only self-mint. // Once minted, all redemption tickets go to the same (public) queue, regardless of this flag. bool publiclyAvailable; - // Current fee the agent charges for minting (paid in underlying currency). uint256 feeBIPS; - // Share of the minting fee that goes to the pool as percentage of the minting fee. // This share of fee is minted as f-assets and belongs to the pool. uint256 poolFeeShareBIPS; - // The token identifier of the agent's current vault collateral. // Token identifier can be used to call AssetManager.getCollateralType(). IERC20 vaultCollateralToken; - // Amount, set by agent, at which locked and free collateral are calculated for new mintings. // For agent's vault collateral. uint256 mintingVaultCollateralRatioBIPS; - // Amount, set by agent, at which locked and free collateral are calculated for new mintings. // For pool collateral. uint256 mintingPoolCollateralRatioBIPS; - // The maximum number of lots that the agent can mint. // This can change any moment due to minting, redemption or price changes. uint256 freeCollateralLots; - // Total amount of vault collateral in agent's vault. uint256 totalVaultCollateralWei; - // Free collateral, available for new mintings. // Note: this value doesn't tell you anything about agent being near liquidation, since it is // calculated at agentMinCollateralRatio, not minCollateralRatio. // Use collateralRatioBIPS to see whether the agent is near liquidation. uint256 freeVaultCollateralWei; - // The actual agent's collateral ratio, as it is used in liquidation. // For calculation, the system checks both FTSO prices and trusted provider's prices and uses // the ones that give higher ratio. uint256 vaultCollateralRatioBIPS; - // The token identifier of the agent's current vault collateral. // Token identifier can be used to call AssetManager.getCollateralType(). IERC20 poolWNatToken; - // Total amount of NAT collateral in agent's pool. uint256 totalPoolCollateralNATWei; - // Free NAT pool collateral (see vault collateral for details). uint256 freePoolCollateralNATWei; - // The actual pool collateral ratio (see vault collateral for details). uint256 poolCollateralRatioBIPS; - // The amount of pool tokens that belong to agent's vault. This limits the amount of possible // minting: to be able to mint, the NAT value of all backed fassets together with new ones, times // mintingPoolHoldingsRequiredBIPS, must be smaller than the agent's pool tokens amount converted to NAT. // Note: the amount of agent's pool tokens only affects minting, not liquidation. uint256 totalAgentPoolTokensWei; - // The amount of vault collateral that will be withdrawn by the agent. uint256 announcedVaultCollateralWithdrawalWei; - // The amount of pool tokens that will be withdrawn by the agent. uint256 announcedPoolTokensWithdrawalWei; - // Free agent's pool tokens. uint256 freeAgentPoolTokensWei; - // Total amount of minted f-assets. uint256 mintedUBA; - // Total amount reserved for ongoing mintings. uint256 reservedUBA; - // Total amount of ongoing redemptions. uint256 redeemingUBA; - // Total amount of ongoing redemptions that lock the pool collateral. // (In pool self-close exits, pool collateral is not locked. So the amount of locked // collateral in the pool can be less than the amount of locked vault collateral.) uint256 poolRedeemingUBA; - // Total amount of dust (unredeemable minted f-assets). // Note: dustUBA is part of mintedUBA, so the amount of redeemable f-assets is calculated as // `mintedUBA - dustUBA` uint256 dustUBA; - // Liquidation info - // If the agent is in CCB or if current liquidation started in CCB, the time agent entered CCB (otherwise 0). - uint256 ccbStartTimestamp; - // If the agent is in LIQUIDATION or FULL_LIQUIDATION, the time agent entered liquidation. - // If the agent is in CCB, the time agent will enter liquidation (in future). // If status is neither of that, returns 0. // Can be used for calculating current liquidation premium, which depends on time since liquidation started. uint256 liquidationStartTimestamp; - // When agent is in liquidation, this is the amount o FAssets that need to be liquidated to bring the agent's // position to safety. When performing liquidation, only up to this amount of FAssets will be liquidated. // If not in liquidation, this value is 0. // Since the liquidation state may need to be upgraded by, call `startLiquidation` before // `getAgentInfo` to get the value that will actually be used in liquidation. uint256 maxLiquidationAmountUBA; - // When agent is in liquidation, this is the factor (in BIPS) of the converted value of the liquidated // FAssets paid by the vault collateral. If not in liquidation, this value is 0. uint256 liquidationPaymentFactorVaultBIPS; - // When agent is in liquidation, this is the factor (in BIPS) of the converted value of the liquidated // FAssets paid by the pool collateral. If not in liquidation, this value is 0. uint256 liquidationPaymentFactorPoolBIPS; - // Total underlying balance (backing and free). int256 underlyingBalanceUBA; - // The minimum underlying balance that has to be held by the agent. Below this, agent is liquidated. uint256 requiredUnderlyingBalanceUBA; - // Underlying balance not backing anything (can be used for gas/fees or withdrawn after announcement). int256 freeUnderlyingBalanceUBA; - // Current underlying withdrawal announcement (or 0 if no announcement was made). uint256 announcedUnderlyingWithdrawalId; - // The factor set by the agent to multiply the price at which agent buys f-assets from pool // token holders on self-close exit (when requested or the redeemed amount is less than 1 lot). uint256 buyFAssetByAgentFactorBIPS; - // The minimum collateral ratio above which a staker can exit the pool // (this is CR that must be left after exit). // Must be higher than system minimum collateral ratio for pool collateral. uint256 poolExitCollateralRatioBIPS; - - // The CR below which it is possible to enter the pool at discounted rate (to prevent liquidation). - // Must be higher than system minimum collateral ratio for pool collateral. - uint256 poolTopupCollateralRatioBIPS; - - // The discount to pool token price when entering and pool CR is below pool topup CR. - uint256 poolTopupTokenPriceFactorBIPS; - - // Agent's handshake type - minting or redeeming can be rejected. - // 0 - no verification, 1 - manual verification, ... - uint256 handshakeType; + // The redemption fee share paid to the pool (as FAssets). + // In redemption dominated situations (when agent requests return from core vault to earn + // from redemption fees), pool can get some share to make it sustainable for pool users. + // NOTE: the pool fee share is locked at the redemption request time, but is charged at the redemption + // confirmation time. If agent uses all the redemption fee for transaction fees, this could make the + // agent's free underlying balance negative. + uint256 redemptionPoolFeeShareBIPS; } } diff --git a/src/songbird/userInterfaces/data/AgentSettings.sol b/src/coston2/data/AgentSettings.sol similarity index 79% rename from src/songbird/userInterfaces/data/AgentSettings.sol rename to src/coston2/data/AgentSettings.sol index cded4c4..98cb936 100644 --- a/src/songbird/userInterfaces/data/AgentSettings.sol +++ b/src/coston2/data/AgentSettings.sol @@ -1,60 +1,48 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; - +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AgentSettings { struct Data { // The token used as vault collateral. Must be one of the tokens obtained by `getCollateralTypes()`, // with class VAULT. IERC20 vaultCollateralToken; - // The suffix to pool token name and symbol that identifies new vault's collateral pool token. // Must be unique within an asset manager. string poolTokenSuffix; - // Minting fee. Normally charged to minters for publicly available agents, but must be set // also for self-minting agents to pay part of it to collateral pool. // Fee is paid in underlying currency along with backing assets. uint256 feeBIPS; - // Share of the minting fee that goes to the pool as percentage of the minting fee. // This share of fee is minted as f-assets and belongs to the pool. uint256 poolFeeShareBIPS; - // Collateral ratio at which we calculate locked collateral and collateral available for minting. // Agent may set own value for minting collateral ratio on creation. // The value must always be greater than system minimum collateral ratio for vault collateral. // Warning: having this value near global min collateral ratio can quickly lead to liquidation for public // agents, so it is advisable to set it significantly higher. uint256 mintingVaultCollateralRatioBIPS; - // Collateral ratio at which we calculate locked collateral and collateral available for minting. // Agent may set own value for minting collateral ratio on creation. // The value must always be greater than system minimum collateral ratio for pool collateral. // Warning: having this value near global min collateral ratio can quickly lead to liquidation for public // agents, so it is advisable to set it significantly higher. uint256 mintingPoolCollateralRatioBIPS; - // The factor set by the agent to multiply the price at which agent buys f-assets from pool // token holders on self-close exit (when requested or the redeemed amount is less than 1 lot). uint256 buyFAssetByAgentFactorBIPS; - // The minimum collateral ratio above which a staker can exit the pool // (this is CR that must be left after exit). // Must be higher than system minimum collateral ratio for pool collateral. uint256 poolExitCollateralRatioBIPS; - - // The CR below which it is possible to enter the pool at discounted rate (to prevent liquidation). - // Must be higher than system minimum collateral ratio for pool collateral. - uint256 poolTopupCollateralRatioBIPS; - - // The discount to pool token price when entering and pool CR is below pool topup CR. - uint256 poolTopupTokenPriceFactorBIPS; - - // Agent's handshake type - minting or redeeming can be rejected. - // 0 - no verification, 1 - manual verification, ... - uint256 handshakeType; + // The redemption fee share paid to the pool (as FAssets). + // In redemption dominated situations (when agent requests return from core vault to earn + // from redemption fees), pool can get some share to make it sustainable for pool users. + // NOTE: the pool fee share is locked at the redemption request time, but is charged at the redemption + // confirmation time. If agent uses all the redemption fee for transaction fees, this could make the + // agent's free underlying balance negative. + uint256 redemptionPoolFeeShareBIPS; } } diff --git a/src/coston/userInterfaces/data/AssetManagerSettings.sol b/src/coston2/data/AssetManagerSettings.sol similarity index 89% rename from src/coston/userInterfaces/data/AssetManagerSettings.sol rename to src/coston2/data/AssetManagerSettings.sol index 7832317..831efbe 100644 --- a/src/coston/userInterfaces/data/AssetManagerSettings.sol +++ b/src/coston2/data/AssetManagerSettings.sol @@ -16,17 +16,17 @@ library AssetManagerSettings { address fAsset; // Factory for creating new agent vaults. - // Type: IAgentVaultFactory + // Type: IIAgentVaultFactory // timelocked address agentVaultFactory; // Factory for creating new agent collateral pools. - // Type: ICollateralPoolFactory + // Type: IICollateralPoolFactory // timelocked address collateralPoolFactory; // Factory for creating new agent collateral pool tokens. - // Type: ICollateralPoolTokenFactory + // Type: IICollateralPoolTokenFactory // timelocked address collateralPoolTokenFactory; @@ -39,7 +39,7 @@ library AssetManagerSettings { // This can be `address(0)`, in which case no whitelist checks are done. // Type: IWhitelist // timelocked - address whitelist; + address __whitelist; // only storage placeholder // If set, the owner address registry contains a list of allowed agent owner's // management addresses and mappings from management to work address. @@ -52,8 +52,7 @@ library AssetManagerSettings { // changed via address updater address fdcVerification; - // The address where burned NAt is sent. - // (E.g. collateral reservation fee is burned on successful minting.) + // The address where burned NAT is sent. // immutable address payable burnAddress; @@ -107,12 +106,12 @@ library AssetManagerSettings { uint64 lotSizeAMG; // The percentage of minted f-assets that the agent must hold in his underlying address. - uint16 minUnderlyingBackingBIPS; + uint16 __minUnderlyingBackingBIPS; // only storage placeholder // for some chains (e.g. Ethereum) we require that agent proves that underlying address is an EOA address // this must be done by presenting a payment proof from that address // immutable - bool requireEOAAddressProof; + bool __requireEOAAddressProof; // only storage placeholder // Maximum minted amount of the f-asset. // rate-limited @@ -149,7 +148,7 @@ library AssetManagerSettings { // This is the part of redemption factor paid from agent's pool collateral. // rate-limited - uint32 redemptionDefaultFactorPoolBIPS; + uint32 __redemptionDefaultFactorPoolBIPS; // only storage placeholder // If the agent or redeemer becomes unresponsive, we still need payment or non-payment confirmations // to be presented eventually to properly track agent's underlying balance. @@ -189,7 +188,7 @@ library AssetManagerSettings { // Agent can remain in CCB for this much time, after that liquidation starts automatically. // rate-limited - uint64 ccbTimeSeconds; + uint64 __ccbTimeSeconds; // only storage placeholder // Amount of seconds (typically 1 day) that the payment/non-payment proofs must be available. // This setting is used in `unstickMinting` and `finishRedemptionWithoutPayment` to prove that the time when @@ -204,23 +203,22 @@ library AssetManagerSettings { // Ratio at which the agents can buy back their collateral when f-asset is terminated. // Typically a bit more than 1 to incentivize agents to buy f-assets and self-close instead. // immutable - uint64 buybackCollateralFactorBIPS; + uint64 __buybackCollateralFactorBIPS; // only storage placeholder // Minimum time that has to pass between underlying withdrawal announcement and the confirmation. // Any value is ok, but higher values give more security against multiple announcement attack by a miner. // Shouldn't be much bigger than Flare data connector response time, so that payments can be confirmed without // extra wait. Should be smaller than confirmationByOthersAfterSeconds (e.g. less than 1 hour). // rate-limited - uint64 announcedUnderlyingConfirmationMinSeconds; + uint64 __announcedUnderlyingConfirmationMinSeconds; // Minimum time from the moment token is deprecated to when it becomes invalid and agents still using // it as vault collateral get liquidated. // timelocked uint64 tokenInvalidationTimeMinSeconds; - // On some rare occasions (stuck minting, locked fassets after termination), the agent has to unlock - // collateral. For this, part of collateral corresponding to FTSO asset value is burned and the rest - // is released. + // On some rare occasions (stuck minting), the agent has to unlock collateral. + // For this, part of collateral corresponding to FTSO asset value is burned and the rest is released. // However, we cannot burn typical vault collateral (stablecoins), so the agent must buy them for NAT // at FTSO price multiplied with this factor (should be a bit above 1) and then we burn the NATs. // timelocked @@ -239,10 +237,10 @@ library AssetManagerSettings { // rate-limited uint64 agentMintingCRChangeTimelockSeconds; - // Amount of seconds that have to pass between agent-set settings for pool exit and topup - // (exit CR, topup CR, topup bonus) change announcement and execution. + // Amount of seconds that have to pass between agent-set settings for pool exit collateral ratio + // change announcement and execution. // rate-limited - uint64 poolExitAndTopupChangeTimelockSeconds; + uint64 poolExitCRChangeTimelockSeconds; // Amount of seconds that an agent is allowed to execute an update once it is allowed. // rate-limited @@ -283,31 +281,31 @@ library AssetManagerSettings { // The amount of time after which the collateral reservation can be cancelled if the // handshake is not completed. // rate-limited - uint64 cancelCollateralReservationAfterSeconds; + uint64 __cancelCollateralReservationAfterSeconds; // only storage placeholder // The amount of collateral reservation fee returned to the minter in case of rejection or cancellation. // Expressed in BIPS, e.g. 9500 for factor of 0.95, max 10000 for factor of 1.0. // rate-limited - uint16 rejectOrCancelCollateralReservationReturnFactorBIPS; + uint16 __rejectOrCancelCollateralReservationReturnFactorBIPS; // only storage placeholder // Time window inside which the agent can reject the redemption request. // rate-limited - uint64 rejectRedemptionRequestWindowSeconds; + uint64 __rejectRedemptionRequestWindowSeconds; // only storage placeholder // Time window inside which the agent can take over the redemption request from another agent // that has rejected it. // rate-limited - uint64 takeOverRedemptionRequestWindowSeconds; + uint64 __takeOverRedemptionRequestWindowSeconds; // only storage placeholder // On redemption rejection, without take over, redeemer is compensated with // redemption value recalculated in flare/sgb times redemption failure factor. // Expressed in BIPS, e.g. 12000 for factor of 1.2. // This is the part of factor paid from agent's vault collateral. // rate-limited - uint32 rejectedRedemptionDefaultFactorVaultCollateralBIPS; + uint32 __rejectedRedemptionDefaultFactorVaultCollateralBIPS; // only storage placeholder // This is the part of rejected redemption factor paid from agent's pool collateral. // rate-limited - uint32 rejectedRedemptionDefaultFactorPoolBIPS; + uint32 __rejectedRedemptionDefaultFactorPoolBIPS; // only storage placeholder } } diff --git a/src/coston/userInterfaces/data/AvailableAgentInfo.sol b/src/coston2/data/AvailableAgentInfo.sol similarity index 95% rename from src/coston/userInterfaces/data/AvailableAgentInfo.sol rename to src/coston2/data/AvailableAgentInfo.sol index 0d90a67..29510f1 100644 --- a/src/coston/userInterfaces/data/AvailableAgentInfo.sol +++ b/src/coston2/data/AvailableAgentInfo.sol @@ -1,31 +1,24 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./AgentInfo.sol"; - +import {AgentInfo} from "./AgentInfo.sol"; library AvailableAgentInfo { struct Data { // Agent vault address. address agentVault; - // The management address of the agent vault's owner. address ownerManagementAddress; - // Agent's minting fee in BIPS. uint256 feeBIPS; - // Minimum agent vault collateral ratio needed for minting. uint256 mintingVaultCollateralRatioBIPS; - // Minimum pool collateral ratio needed for minting. uint256 mintingPoolCollateralRatioBIPS; - // The number of lots that can be minted by this agent. // Note: the value is only informative since it can can change at any time // due to price changes, reservation, minting, redemption, or even lot size change. uint256 freeCollateralLots; - // The agent status, as for getAgentInfo(). AgentInfo.Status status; } diff --git a/src/coston/userInterfaces/data/CollateralReservationInfo.sol b/src/coston2/data/CollateralReservationInfo.sol similarity index 75% rename from src/coston/userInterfaces/data/CollateralReservationInfo.sol rename to src/coston2/data/CollateralReservationInfo.sol index 348bdba..65c3595 100644 --- a/src/coston/userInterfaces/data/CollateralReservationInfo.sol +++ b/src/coston2/data/CollateralReservationInfo.sol @@ -3,6 +3,13 @@ pragma solidity >=0.7.6 <0.9; library CollateralReservationInfo { + enum Status { + ACTIVE, // the minting process hasn't finished yet + SUCCESSFUL, // the payment has been confirmed and the FAssets minted + DEFAULTED, // the payment has defaulted and the agent received the collateral reservation fee + EXPIRED // the confirmation time has expired and the agent called unstickMinting + } + struct Data { // The id used for executing or defaulting the minting. uint64 collateralReservationId; @@ -30,10 +37,10 @@ library CollateralReservationInfo { // Part of the fee is goes to the pool and the rest to the agent vault as WNAT. uint128 reservationFeeNatWei; - // Proportion of the mintingFeeUBA and reservationFeeNatWei that belogs to the collateral pool. + // Proportion of the mintingFeeUBA and reservationFeeNatWei that belongs to the collateral pool. uint16 poolFeeShareBIPS; - // The underlying block (approximate - as known by the asset manager) when the reservation occured. + // The underlying block (approximate - as known by the asset manager) when the reservation occurred. uint64 firstUnderlyingBlock; // The last underlying block and timestamp for redemption payment. Redemption is defaulted if @@ -45,14 +52,10 @@ library CollateralReservationInfo { // (Only minter, agent or executor may execute the minting.) address executor; - // The fee in NAT that the executor receives if they successfuly execute the minting. + // The fee in NAT that the executor receives if they successfully execute the minting. uint256 executorFeeNatWei; - // If non-zero, the agent has started the handshake process. - uint64 handshakeStartTimestamp; - - // Merkle root of the list of addresses from which the minter is going to deposit the underlying assets - // (only needed when handshake is enabled for the agent). - bytes32 sourceAddressesRoot; + // If the minting process has finished, indication of success/default. Otherwise ACTIVE. + CollateralReservationInfo.Status status; } } diff --git a/src/songbird/userInterfaces/data/CollateralType.sol b/src/coston2/data/CollateralType.sol similarity index 85% rename from src/songbird/userInterfaces/data/CollateralType.sol rename to src/coston2/data/CollateralType.sol index 2220965..711b4a1 100644 --- a/src/songbird/userInterfaces/data/CollateralType.sol +++ b/src/coston2/data/CollateralType.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library CollateralType { @@ -45,11 +45,6 @@ library CollateralType { // Minimum collateral ratio for healthy agents. uint256 minCollateralRatioBIPS; - // Minimum collateral ratio for agent in CCB (Collateral call band). - // If the agent's collateral ratio is less than this, skip the CCB and go straight to liquidation. - // A bit smaller than minCollateralRatioBIPS. - uint256 ccbMinCollateralRatioBIPS; - // Minimum collateral ratio required to get agent out of liquidation. // Will always be greater than minCollateralRatioBIPS. uint256 safetyMinCollateralRatioBIPS; diff --git a/src/songbird/userInterfaces/data/RedemptionRequestInfo.sol b/src/coston2/data/RedemptionRequestInfo.sol similarity index 77% rename from src/songbird/userInterfaces/data/RedemptionRequestInfo.sol rename to src/coston2/data/RedemptionRequestInfo.sol index 83793a3..e850ec1 100644 --- a/src/songbird/userInterfaces/data/RedemptionRequestInfo.sol +++ b/src/coston2/data/RedemptionRequestInfo.sol @@ -4,8 +4,13 @@ pragma solidity >=0.7.6 <0.9; library RedemptionRequestInfo { enum Status { - ACTIVE, - DEFAULTED + ACTIVE, // waiting for confirmation/default + DEFAULTED_UNCONFIRMED, // default called, failed or late payment can still be confirmed + // final statuses - there can be no valid payment for this redemption anymore + SUCCESSFUL, // successful payment confirmed + DEFAULTED_FAILED, // payment failed (default was paid) + BLOCKED, // payment blocked + REJECTED // redemption request rejected due to invalid redeemer's address } struct Data { @@ -39,7 +44,7 @@ library RedemptionRequestInfo { // and goes to the collateral pool. uint16 poolFeeShareBIPS; - // The underlying block (approximate - as known by the asset manager) when the request occured. + // The underlying block (approximate - as known by the asset manager) when the request occurred. uint64 firstUnderlyingBlock; // The last underlying block and timestamp for redemption payment. Redemption is defaulted if @@ -47,7 +52,7 @@ library RedemptionRequestInfo { uint64 lastUnderlyingBlock; uint64 lastUnderlyingTimestamp; - // The native (Flare/Songbird) chain timstamp when the request occured. + // The native (Flare/Songbird) chain timestamp when the request occurred. uint64 timestamp; // True if redemption was created by a selfCloseExit on the collateral pool. @@ -60,13 +65,7 @@ library RedemptionRequestInfo { // (Only redeemer, agent or executor may execute the default.) address executor; - // The fee in NAT that the executor receives if they successfuly call default. + // The fee in NAT that the executor receives if they successfully call default. uint256 executorFeeNatWei; - - // If non-zero, request was rejected in handshake process. - uint64 rejectionTimestamp; - - // If non-zero, handshake-rejected request was taken over by another agent. - uint64 takeOverTimestamp; } } diff --git a/src/coston2/userInterfaces/data/RedemptionTicketInfo.sol b/src/coston2/data/RedemptionTicketInfo.sol similarity index 100% rename from src/coston2/userInterfaces/data/RedemptionTicketInfo.sol rename to src/coston2/data/RedemptionTicketInfo.sol diff --git a/src/coston2/fdc/interface/ITypeTemplate.sol b/src/coston2/fdc/interfaces/ITypeTemplate.sol similarity index 100% rename from src/coston2/fdc/interface/ITypeTemplate.sol rename to src/coston2/fdc/interfaces/ITypeTemplate.sol diff --git a/src/coston2/fdc/interface/ITypeTemplateVerification.sol b/src/coston2/fdc/interfaces/ITypeTemplateVerification.sol similarity index 100% rename from src/coston2/fdc/interface/ITypeTemplateVerification.sol rename to src/coston2/fdc/interfaces/ITypeTemplateVerification.sol diff --git a/src/coston2/fscV1/interface/IIFastUpdaterView.sol b/src/coston2/fscV1/interfaces/IIFastUpdaterView.sol similarity index 100% rename from src/coston2/fscV1/interface/IIFastUpdaterView.sol rename to src/coston2/fscV1/interfaces/IIFastUpdaterView.sol diff --git a/src/coston2/fscV1/interface/IIFtsoManagerProxy.sol b/src/coston2/fscV1/interfaces/IIFtsoManagerProxy.sol similarity index 100% rename from src/coston2/fscV1/interface/IIFtsoManagerProxy.sol rename to src/coston2/fscV1/interfaces/IIFtsoManagerProxy.sol diff --git a/src/flare/ftso/interface/IIFtso.sol b/src/coston2/ftso/interfaces/IIFtso.sol similarity index 98% rename from src/flare/ftso/interface/IIFtso.sol rename to src/coston2/ftso/interfaces/IIFtso.sol index e2beb8f..d93d935 100644 --- a/src/flare/ftso/interface/IIFtso.sol +++ b/src/coston2/ftso/interfaces/IIFtso.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "../../genesis/interface/IFtsoGenesis.sol"; +import "../../genesis/interfaces/IFtsoGenesis.sol"; import "../../IFtso.sol"; -import "../../token/interface/IIVPToken.sol"; +import "../../token/interfaces/IIVPToken.sol"; interface IIFtso is IFtso, IFtsoGenesis { diff --git a/src/coston2/ftso/interface/IIFtsoFeedPublisher.sol b/src/coston2/ftso/interfaces/IIFtsoFeedPublisher.sol similarity index 100% rename from src/coston2/ftso/interface/IIFtsoFeedPublisher.sol rename to src/coston2/ftso/interfaces/IIFtsoFeedPublisher.sol diff --git a/src/coston2/ftso/interfaces/IIFtsoManager.sol b/src/coston2/ftso/interfaces/IIFtsoManager.sol new file mode 100644 index 0000000..b11605f --- /dev/null +++ b/src/coston2/ftso/interfaces/IIFtsoManager.sol @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../ftso/interfaces/IIFtso.sol"; +import "../../IFtsoManager.sol"; +import "../../genesis/interfaces/IFlareDaemonize.sol"; +import "../../token/interfaces/IIVPToken.sol"; + + +interface IIFtsoManager is IFtsoManager, IFlareDaemonize { + + struct RewardEpochData { + uint256 votepowerBlock; + uint256 startBlock; + uint256 startTimestamp; + } + + event ClosingExpiredRewardEpochFailed(uint256 rewardEpoch); + event CleanupBlockNumberManagerFailedForBlock(uint256 blockNumber); + event UpdatingActiveValidatorsTriggerFailed(uint256 rewardEpoch); + event FtsoDeactivationFailed(IIFtso ftso); + event ChillingNonrevealingDataProvidersFailed(); + + function activate() external; + + function setInitialRewardData( + uint256 _nextRewardEpochToExpire, + uint256 _rewardEpochsLength, + uint256 _currentRewardEpochEnds + ) external; + + function setGovernanceParameters( + uint256 _updateTs, + uint256 _maxVotePowerNatThresholdFraction, + uint256 _maxVotePowerAssetThresholdFraction, + uint256 _lowAssetUSDThreshold, + uint256 _highAssetUSDThreshold, + uint256 _highAssetTurnoutThresholdBIPS, + uint256 _lowNatTurnoutThresholdBIPS, + uint256 _elasticBandRewardBIPS, + uint256 _rewardExpiryOffsetSeconds, + address[] memory _trustedAddresses + ) external; + + + function addFtso(IIFtso _ftso) external; + + function addFtsosBulk(IIFtso[] memory _ftsos) external; + + function removeFtso(IIFtso _ftso) external; + + function replaceFtso( + IIFtso _ftsoToAdd, + bool copyCurrentPrice, + bool copyAssetOrAssetFtsos + ) external; + + function replaceFtsosBulk( + IIFtso[] memory _ftsosToAdd, + bool copyCurrentPrice, + bool copyAssetOrAssetFtsos + ) external; + + function setFtsoAsset(IIFtso _ftso, IIVPToken _asset) external; + + function setFtsoAssetFtsos(IIFtso _ftso, IIFtso[] memory _assetFtsos) external; + + function setFallbackMode(bool _fallbackMode) external; + + function setFtsoFallbackMode(IIFtso _ftso, bool _fallbackMode) external; + + function notInitializedFtsos(IIFtso) external view returns (bool); + + function getRewardEpochData(uint256 _rewardEpochId) external view returns (RewardEpochData memory); + + function currentRewardEpochEnds() external view returns (uint256); + + function getLastUnprocessedPriceEpochData() external view + returns( + uint256 _lastUnprocessedPriceEpoch, + uint256 _lastUnprocessedPriceEpochRevealEnds, + bool _lastUnprocessedPriceEpochInitialized + ); + + function rewardEpochsStartTs() external view returns(uint256); + + function rewardEpochDurationSeconds() external view returns(uint256); + + function rewardEpochs(uint256 _rewardEpochId) external view + returns ( + uint256 _votepowerBlock, + uint256 _startBlock, + uint256 _startTimestamp + ); + + function getRewardExpiryOffsetSeconds() external view returns (uint256); + + /** + * @notice Returns elastic band width in PPM (parts-per-million) for given ftso + */ + function getElasticBandWidthPPMFtso(IIFtso _ftso) external view returns (uint256); +} diff --git a/src/coston2/ftso/interfaces/IIFtsoManagerV1.sol b/src/coston2/ftso/interfaces/IIFtsoManagerV1.sol new file mode 100644 index 0000000..44cf4cc --- /dev/null +++ b/src/coston2/ftso/interfaces/IIFtsoManagerV1.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +// interface for the first version of ftso manger (V1 = oldest version) - last version is always without any Vx +interface IIFtsoManagerV1 { + function rewardEpochsStartTs() external view returns(uint256); + function rewardEpochDurationSeconds() external view returns(uint256); + + function getCurrentRewardEpoch() external view returns(uint256); + + function rewardEpochs(uint256 _rewardEpochId) external view returns ( + uint256 _votepowerBlock, + uint256 _startBlock, + uint256 _startTimestamp + ); + + function getPriceEpochConfiguration() external view + returns ( + uint256 _firstPriceEpochStartTs, + uint256 _priceEpochDurationSeconds, + uint256 _revealEpochDurationSeconds + ); +} diff --git a/src/coston2/genesis/interface/IFlareDaemonize.sol b/src/coston2/genesis/interfaces/IFlareDaemonize.sol similarity index 100% rename from src/coston2/genesis/interface/IFlareDaemonize.sol rename to src/coston2/genesis/interfaces/IFlareDaemonize.sol diff --git a/src/coston2/genesis/interface/IFtsoGenesis.sol b/src/coston2/genesis/interfaces/IFtsoGenesis.sol similarity index 100% rename from src/coston2/genesis/interface/IFtsoGenesis.sol rename to src/coston2/genesis/interfaces/IFtsoGenesis.sol diff --git a/src/coston2/genesis/interface/IFtsoManagerGenesis.sol b/src/coston2/genesis/interfaces/IFtsoManagerGenesis.sol similarity index 100% rename from src/coston2/genesis/interface/IFtsoManagerGenesis.sol rename to src/coston2/genesis/interfaces/IFtsoManagerGenesis.sol diff --git a/src/coston2/genesis/interface/IFtsoRegistryGenesis.sol b/src/coston2/genesis/interfaces/IFtsoRegistryGenesis.sol similarity index 100% rename from src/coston2/genesis/interface/IFtsoRegistryGenesis.sol rename to src/coston2/genesis/interfaces/IFtsoRegistryGenesis.sol diff --git a/src/coston2/genesis/interfaces/IIPriceSubmitter.sol b/src/coston2/genesis/interfaces/IIPriceSubmitter.sol new file mode 100644 index 0000000..b69beab --- /dev/null +++ b/src/coston2/genesis/interfaces/IIPriceSubmitter.sol @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IPriceSubmitter.sol"; +interface IIPriceSubmitter is IPriceSubmitter { + + /** + * Set trusted addresses that are always allowed to submit and reveal. + * Only ftso manager can call this method. + */ + function setTrustedAddresses(address[] memory _trustedAddresses) external; + + /** + * Called from whitelister when new voter has been whitelisted. + */ + function voterWhitelisted(address _voter, uint256 _ftsoIndex) external; + + /** + * Called from whitelister when one or more voters have been removed. + */ + function votersRemovedFromWhitelist(address[] memory _voters, uint256 _ftsoIndex) external; + + /** + * Returns a list of trusted addresses that are always allowed to submit and reveal. + */ + function getTrustedAddresses() external view returns (address[] memory); +} diff --git a/src/coston2/genesis/interfaces/IInflationGenesis.sol b/src/coston2/genesis/interfaces/IInflationGenesis.sol new file mode 100644 index 0000000..eb0e98c --- /dev/null +++ b/src/coston2/genesis/interfaces/IInflationGenesis.sol @@ -0,0 +1,15 @@ + +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IInflationGenesis { + /** + * @notice Receive newly minted native tokens from the FlareDaemon. + * @dev Assume that the amount received will be >= last topup requested across all services. + * If there is not enough balance sent to cover the topup request, expect library method will revert. + * Also assume that any balance received greater than the topup request calculated + * came from self-destructor sending a balance to this contract. + */ + function receiveMinting() external payable; +} diff --git a/src/coston/governance/interface/IIGovernorProposer.sol b/src/coston2/governance/interfaces/IIGovernorProposer.sol similarity index 58% rename from src/coston/governance/interface/IIGovernorProposer.sol rename to src/coston2/governance/interfaces/IIGovernorProposer.sol index adb6c4c..8e7dc87 100644 --- a/src/coston/governance/interface/IIGovernorProposer.sol +++ b/src/coston2/governance/interfaces/IIGovernorProposer.sol @@ -1,12 +1,13 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; interface IIGovernorProposer { /** - * Determines if account is eligible to submit a proposal. - * @param _account Address of the queried account. - * @return True if account is eligible for proposal submission, and false otherwise. + * @notice Determines if account is eligible to submit a proposal + * @param _account Address of the queried account + * @return True if account is eligible for proposal submission, and false otherwise */ function isProposer(address _account) external view returns (bool); diff --git a/src/coston/governance/interface/IIPollingFoundation.sol b/src/coston2/governance/interfaces/IIPollingFoundation.sol similarity index 53% rename from src/coston/governance/interface/IIPollingFoundation.sol rename to src/coston2/governance/interfaces/IIPollingFoundation.sol index 9fe2fd4..59f9854 100644 --- a/src/coston/governance/interface/IIPollingFoundation.sol +++ b/src/coston2/governance/interfaces/IIPollingFoundation.sol @@ -1,5 +1,6 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; import "../../IGovernor.sol"; import "./IIGovernorProposer.sol"; @@ -8,7 +9,7 @@ interface IIPollingFoundation is IGovernor, IIGovernorProposer { struct GovernorSettingsWithoutExecParams { bool accept; - uint256 votingStartTs; + uint256 votingDelaySeconds; uint256 votingPeriodSeconds; uint256 vpBlockPeriodSeconds; uint256 thresholdConditionBIPS; @@ -16,11 +17,11 @@ interface IIPollingFoundation is IGovernor, IIGovernorProposer { } /** - * Creates a new proposal without execution parameters. - * @param _description String description of the proposal. - * @param _settings Settings of the poposal. - * @return Proposal id (unique identifier obtained by hashing proposal data). - * Emits a ProposalCreated event. + * @notice Creates a new proposal without execution parameters + * @param _description String description of the proposal + * @param _settings Settings of the poposal + * @return Proposal id (unique identifier obtained by hashing proposal data) + * @notice Emits a ProposalCreated event */ function propose( string memory _description, @@ -28,14 +29,14 @@ interface IIPollingFoundation is IGovernor, IIGovernorProposer { ) external returns (uint256); /** - * Creates a new proposal with execution parameters. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * @param _description String description of the proposal. - * @param _settings Settings of the poposal. - * @return Proposal id (unique identifier obtained by hashing proposal data). - * Emits a ProposalCreated event. + * @notice Creates a new proposal with execution parameters + * @param _targets Array of target addresses on which the calls are to be invoked + * @param _values Array of values with which the calls are to be invoked + * @param _calldatas Array of call data to be invoked + * @param _description String description of the proposal + * @param _settings Settings of the poposal + * @return Proposal id (unique identifier obtained by hashing proposal data) + * @notice Emits a ProposalCreated event */ function propose( address[] memory _targets, diff --git a/src/coston2/governance/interface/IIPollingManagementGroup.sol b/src/coston2/governance/interfaces/IIPollingManagementGroup.sol similarity index 100% rename from src/coston2/governance/interface/IIPollingManagementGroup.sol rename to src/coston2/governance/interfaces/IIPollingManagementGroup.sol diff --git a/src/coston2/inflation/interfaces/IIInflationAllocation.sol b/src/coston2/inflation/interfaces/IIInflationAllocation.sol new file mode 100644 index 0000000..da5305a --- /dev/null +++ b/src/coston2/inflation/interfaces/IIInflationAllocation.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIInflationReceiver.sol"; + +struct SharingPercentage { + IIInflationReceiver inflationReceiver; + uint256 percentBips; +} + +interface IIInflationAllocation { + /** + * Return the time slot inflation rate in bips. + */ + function getTimeSlotPercentageBips() external returns(uint256); + + /** + * Return the shared percentage per inflation receiver. + * @dev Assumption is that implementer edited that percents sum to 100 pct and + * that receiver addresses are valid. + */ + function getSharingPercentages() external returns(SharingPercentage[] memory); +} diff --git a/src/coston2/inflation/interfaces/IIInflationReceiver.sol b/src/coston2/inflation/interfaces/IIInflationReceiver.sol new file mode 100644 index 0000000..43a9499 --- /dev/null +++ b/src/coston2/inflation/interfaces/IIInflationReceiver.sol @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +/** + * Internal interface for contracts that can receive inflation. + */ +interface IIInflationReceiver { + /** + * Notify the receiver that it is entitled to receive a new inflation amount. + * @param _toAuthorizeWei The amount of inflation that can be awarded in the coming day, in wei. + */ + function setDailyAuthorizedInflation(uint256 _toAuthorizeWei) external; + + /** + * Receive native tokens from inflation. + */ + function receiveInflation() external payable; + + /** + * Returns the address of the `Inflation` contract. + */ + function getInflationAddress() external returns(address); + + /** + * Returns the contract's expected balance + * (actual balance may be higher due to self-destruct funds). + * @return Expected native token balance. + */ + function getExpectedBalance() external view returns(uint256); + + /** + * Implement this function to allow updating inflation receiver contracts through `AddressUpdater`. + * @return Contract name. + */ + function getContractName() external view returns (string memory); +} diff --git a/src/coston2/inflation/interfaces/IIInflationReceiverV1.sol b/src/coston2/inflation/interfaces/IIInflationReceiverV1.sol new file mode 100644 index 0000000..a75342a --- /dev/null +++ b/src/coston2/inflation/interfaces/IIInflationReceiverV1.sol @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIInflationReceiverV1 { + /** + * Notify the receiver that it is entitled to receive `_toAuthorizeWei` inflation amount. + * @param _toAuthorizeWei the amount of inflation that can be awarded in the coming day + */ + function setDailyAuthorizedInflation(uint256 _toAuthorizeWei) external; + + /** + * Receive native tokens from inflation. + */ + function receiveInflation() external payable; + + /** + * Inflation receivers have a reference to the Inflation contract. + */ + function getInflationAddress() external returns(address); + + /** + * Implement this function for updating inflation receiver contracts through AddressUpdater. + */ + function getContractName() external view returns (string memory); +} diff --git a/src/coston2/inflation/interfaces/IIInflationV1.sol b/src/coston2/inflation/interfaces/IIInflationV1.sol new file mode 100644 index 0000000..5e91360 --- /dev/null +++ b/src/coston2/inflation/interfaces/IIInflationV1.sol @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIInflationReceiver.sol"; + + +// interface for the first version of inflation (V1 = oldest version) - last version is always without any Vx +interface IIInflationV1 { + + struct RewardServiceState { + IIInflationReceiver inflationReceiver; // The target rewarding contract + uint256 authorizedInflationWei; // Total authorized inflation for this reward service + uint256 lastDailyAuthorizedInflationWei; // Last daily authorized inflation amount + uint256 inflationTopupRequestedWei; // Total inflation topup requested to be minted + uint256 inflationTopupReceivedWei; // Total inflation minting received + uint256 inflationTopupWithdrawnWei; // Total inflation minting sent to rewarding service contract + } + + struct RewardServicesState { + // Collection of annums + RewardServiceState[] rewardServices; + // Balances + uint256 totalAuthorizedInflationWei; + uint256 totalInflationTopupRequestedWei; + uint256 totalInflationTopupReceivedWei; + uint256 totalInflationTopupWithdrawnWei; + } + + struct InflationAnnumState { + uint256 recognizedInflationWei; + uint256 startTimeStamp; + uint256 endTimeStamp; + RewardServicesState rewardServices; + } + + + function lastAuthorizationTs() external returns(uint256); + function rewardEpochStartedTs() external returns(uint256); + function getAnnum(uint256 _index) external view returns(InflationAnnumState memory); + +} diff --git a/src/coston2/inflation/interfaces/IIPreInflationCalculation.sol b/src/coston2/inflation/interfaces/IIPreInflationCalculation.sol new file mode 100644 index 0000000..29e5043 --- /dev/null +++ b/src/coston2/inflation/interfaces/IIPreInflationCalculation.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIPreInflationCalculation { + /** + * @notice A method that is triggered before new inflation is calculated + */ + function trigger() external; +} diff --git a/src/coston2/inflation/interfaces/IISupply.sol b/src/coston2/inflation/interfaces/IISupply.sol new file mode 100644 index 0000000..0090891 --- /dev/null +++ b/src/coston2/inflation/interfaces/IISupply.sol @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IISupply { + + /** + * @notice Updates circulating supply + * @dev Also updates the burn address amount + */ + function updateCirculatingSupply() external; + + /** + * @notice Updates authorized inflation and circulating supply - emits event if error + * @param _inflationAuthorizedWei Authorized inflation + * @dev Also updates the burn address amount + */ + function updateAuthorizedInflationAndCirculatingSupply(uint256 _inflationAuthorizedWei) external; + + /** + * @notice Get approximate circulating supply for given block number from cache - only past block + * @param _blockNumber Block number + * @return _circulatingSupplyWei Return approximate circulating supply for last known block <= _blockNumber + */ + function getCirculatingSupplyAtCached(uint256 _blockNumber) external returns(uint256 _circulatingSupplyWei); + + /** + * @notice Get approximate circulating supply for given block number + * @param _blockNumber Block number + * @return _circulatingSupplyWei Return approximate circulating supply for last known block <= _blockNumber + */ + function getCirculatingSupplyAt(uint256 _blockNumber) external view returns(uint256 _circulatingSupplyWei); + + /** + * @notice Get total inflatable balance (initial genesis amount + total authorized inflation) + * @return _inflatableBalanceWei Return inflatable balance + */ + function getInflatableBalance() external view returns(uint256 _inflatableBalanceWei); +} diff --git a/src/coston2/mockXAsset/interfaces/ICollateralizable.sol b/src/coston2/mockXAsset/interfaces/ICollateralizable.sol new file mode 100644 index 0000000..3ed5a99 --- /dev/null +++ b/src/coston2/mockXAsset/interfaces/ICollateralizable.sol @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface ICollateralizable { + + enum FeeHandling { + DEPOSIT_TO_POSITION, + SEND_TO_AGENT + } + + /// addRewardToAgentPosition function will be triggered by the reward contract per reward allocation. + /// Function will claim rewards for last epoch, and allocate to relevant agents + /// Flow: + /// - check which FTSO won. + /// - claim relevant reward from reward contract. + /// - iterate list of current delegators to this FTSO + /// - per the list, check weight agent delegated to this FTSO + /// - add native token reward to this Agent position. + function addRewardToAgentPosition(uint256 epochID) external returns (bool succeess); + + function deposit( + uint256 amount, + uint256 freshMint, // amount to add to fresh minting pool + uint256 agentPosition, // amount to add to position pool + uint256 freshMintMinRatio, // if position pool collateral ratio < min, no new mints + address natAddress, + FeeHandling handling + ) external; + + /// note: must send collateral reservation fee as msg.value. or approve to this contract + function mintRequest ( // AKA collateral reservation + uint256 mintAmountTwei, + address mintDestination, + bytes32 underlyingAddress + ) + external + returns ( + uint256 mintRequestId, + address[] calldata agents, // agent list + uint256[] calldata assetAmounts, // amount to send to agent in underlying chain + bytes32[] calldata assetAddress // underlying chain address + ); + + function proveMintPayment ( // AKA mint + uint256 mintRequestId, + bytes32 minterSourceAddress, //do we need this? + bytes32 agentAssetAddress, + bytes32 destinationTag, + uint256 assetAmount, + bytes32[] calldata merkleProof + ) + external + returns ( + uint256 mintedAmount + ); + + function assetRedemptionRequest ( + uint256 amount, + bytes32 assetAddress // address in underlying chain[] + ) + external + returns ( + uint256 redemptionId, + address[] calldata agents, // agent list + uint256[] calldata assetAmounts // amount agent should in underlying chain + ); + + function proveRedemptionPayment ( // same as prove mint payment? + uint256 redemptionRequestId, + bytes32 agentSourceAssetAddress, //do we need this? + bytes32 redeemerAssetAddress, + bytes32 destinationTag, + uint256 assetAmount, + bytes32[] calldata merkleProof + ) + external + returns ( + uint256 redeemedAmount + ); +} diff --git a/src/coston2/protocol/interface/IIClaimSetupManager.sol b/src/coston2/protocol/interfaces/IIClaimSetupManager.sol similarity index 100% rename from src/coston2/protocol/interface/IIClaimSetupManager.sol rename to src/coston2/protocol/interfaces/IIClaimSetupManager.sol diff --git a/src/coston2/protocol/interface/IICleanupBlockNumberManager.sol b/src/coston2/protocol/interfaces/IICleanupBlockNumberManager.sol similarity index 100% rename from src/coston2/protocol/interface/IICleanupBlockNumberManager.sol rename to src/coston2/protocol/interfaces/IICleanupBlockNumberManager.sol diff --git a/src/coston2/protocol/interface/IIEntityManager.sol b/src/coston2/protocol/interfaces/IIEntityManager.sol similarity index 100% rename from src/coston2/protocol/interface/IIEntityManager.sol rename to src/coston2/protocol/interfaces/IIEntityManager.sol diff --git a/src/coston2/protocol/interface/IIFlareSystemsCalculator.sol b/src/coston2/protocol/interfaces/IIFlareSystemsCalculator.sol similarity index 100% rename from src/coston2/protocol/interface/IIFlareSystemsCalculator.sol rename to src/coston2/protocol/interfaces/IIFlareSystemsCalculator.sol diff --git a/src/coston2/protocol/interface/IIFlareSystemsManager.sol b/src/coston2/protocol/interfaces/IIFlareSystemsManager.sol similarity index 100% rename from src/coston2/protocol/interface/IIFlareSystemsManager.sol rename to src/coston2/protocol/interfaces/IIFlareSystemsManager.sol diff --git a/src/coston2/protocol/interface/IINodePossessionVerifier.sol b/src/coston2/protocol/interfaces/IINodePossessionVerifier.sol similarity index 100% rename from src/coston2/protocol/interface/IINodePossessionVerifier.sol rename to src/coston2/protocol/interfaces/IINodePossessionVerifier.sol diff --git a/src/coston2/protocol/interface/IIPublicKeyVerifier.sol b/src/coston2/protocol/interfaces/IIPublicKeyVerifier.sol similarity index 100% rename from src/coston2/protocol/interface/IIPublicKeyVerifier.sol rename to src/coston2/protocol/interfaces/IIPublicKeyVerifier.sol diff --git a/src/coston2/protocol/interface/IIRelay.sol b/src/coston2/protocol/interfaces/IIRelay.sol similarity index 100% rename from src/coston2/protocol/interface/IIRelay.sol rename to src/coston2/protocol/interfaces/IIRelay.sol diff --git a/src/coston2/protocol/interface/IIRewardEpochSwitchoverTrigger.sol b/src/coston2/protocol/interfaces/IIRewardEpochSwitchoverTrigger.sol similarity index 100% rename from src/coston2/protocol/interface/IIRewardEpochSwitchoverTrigger.sol rename to src/coston2/protocol/interfaces/IIRewardEpochSwitchoverTrigger.sol diff --git a/src/coston2/protocol/interface/IIRewardManager.sol b/src/coston2/protocol/interfaces/IIRewardManager.sol similarity index 100% rename from src/coston2/protocol/interface/IIRewardManager.sol rename to src/coston2/protocol/interfaces/IIRewardManager.sol diff --git a/src/coston2/protocol/interface/IISubmission.sol b/src/coston2/protocol/interfaces/IISubmission.sol similarity index 100% rename from src/coston2/protocol/interface/IISubmission.sol rename to src/coston2/protocol/interfaces/IISubmission.sol diff --git a/src/coston2/protocol/interface/IIVoterRegistrationTrigger.sol b/src/coston2/protocol/interfaces/IIVoterRegistrationTrigger.sol similarity index 100% rename from src/coston2/protocol/interface/IIVoterRegistrationTrigger.sol rename to src/coston2/protocol/interfaces/IIVoterRegistrationTrigger.sol diff --git a/src/coston2/protocol/interface/IIVoterRegistry.sol b/src/coston2/protocol/interfaces/IIVoterRegistry.sol similarity index 100% rename from src/coston2/protocol/interface/IIVoterRegistry.sol rename to src/coston2/protocol/interfaces/IIVoterRegistry.sol diff --git a/src/coston2/rNat/interface/IIRNat.sol b/src/coston2/rNat/interfaces/IIRNat.sol similarity index 100% rename from src/coston2/rNat/interface/IIRNat.sol rename to src/coston2/rNat/interfaces/IIRNat.sol diff --git a/src/coston/rNat/interface/IIRNatAccount.sol b/src/coston2/rNat/interfaces/IIRNatAccount.sol similarity index 98% rename from src/coston/rNat/interface/IIRNatAccount.sol rename to src/coston2/rNat/interfaces/IIRNatAccount.sol index 0a7d05e..017902d 100644 --- a/src/coston/rNat/interface/IIRNatAccount.sol +++ b/src/coston2/rNat/interfaces/IIRNatAccount.sol @@ -3,7 +3,7 @@ pragma solidity >=0.7.6 <0.9; import "../../IRNatAccount.sol"; -import "../../protocol/interface/IIClaimSetupManager.sol"; +import "../../protocol/interfaces/IIClaimSetupManager.sol"; interface IIRNatAccount is IRNatAccount { diff --git a/src/coston2/staking/interfaces/IIPChainStakeMirrorVerifier.sol b/src/coston2/staking/interfaces/IIPChainStakeMirrorVerifier.sol new file mode 100644 index 0000000..3833ea3 --- /dev/null +++ b/src/coston2/staking/interfaces/IIPChainStakeMirrorVerifier.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../IPChainStakeMirrorVerifier.sol"; + + +/** + * Internal interface for P-chain stake mirror verifications. + */ +interface IIPChainStakeMirrorVerifier is IPChainStakeMirrorVerifier { + + /** + * Method for P-chain stake verification using `IPChainStakeMirrorVerifier.PChainStake` data and Merkle proof. + * @param _stakeData Information about P-chain stake. + * @param _merkleProof Merkle proof that should be used to prove the P-chain stake. + * @return True if stake can be verified using provided Merkle proof. + */ + function verifyStake( + IPChainStakeMirrorVerifier.PChainStake calldata _stakeData, + bytes32[] calldata _merkleProof + ) + external view returns(bool); +} diff --git a/src/coston2/token/interface/IICleanable.sol b/src/coston2/token/interfaces/IICleanable.sol similarity index 100% rename from src/coston2/token/interface/IICleanable.sol rename to src/coston2/token/interfaces/IICleanable.sol diff --git a/src/coston2/token/interfaces/IICombinedNatBalance.sol b/src/coston2/token/interfaces/IICombinedNatBalance.sol new file mode 100644 index 0000000..8a76dcb --- /dev/null +++ b/src/coston2/token/interfaces/IICombinedNatBalance.sol @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +/** + * Internal interface for the balance part of `CombinedNat` contract. + */ +interface IICombinedNatBalance { + + /** + * Total amount of tokens at current block. + * @return The current total amount of tokens. + **/ + function totalSupply() external view returns (uint256); + + /** + * Total amount of tokens at a specific `_blockNumber`. + * @param _blockNumber The block number when the totalSupply is queried. + * @return The total amount of tokens at `_blockNumber`. + **/ + function totalSupplyAt(uint _blockNumber) external view returns(uint256); + + /** + * Queries the token balance of `_owner` at current block. + * @param _owner The address from which the balance will be retrieved. + * @return The current balance. + **/ + function balanceOf(address _owner) external view returns (uint256); + + /** + * Queries the token balance of `_owner` at a specific `_blockNumber`. + * @param _owner The address from which the balance will be retrieved. + * @param _blockNumber The block number when the balance is queried. + * @return The balance at `_blockNumber`. + **/ + function balanceOfAt(address _owner, uint _blockNumber) external view returns (uint256); +} diff --git a/src/coston2/token/interface/IIGovernanceVotePower.sol b/src/coston2/token/interfaces/IIGovernanceVotePower.sol similarity index 100% rename from src/coston2/token/interface/IIGovernanceVotePower.sol rename to src/coston2/token/interfaces/IIGovernanceVotePower.sol diff --git a/src/coston2/token/interface/IIVPContract.sol b/src/coston2/token/interfaces/IIVPContract.sol similarity index 100% rename from src/coston2/token/interface/IIVPContract.sol rename to src/coston2/token/interfaces/IIVPContract.sol diff --git a/src/coston2/token/interface/IIVPToken.sol b/src/coston2/token/interfaces/IIVPToken.sol similarity index 100% rename from src/coston2/token/interface/IIVPToken.sol rename to src/coston2/token/interfaces/IIVPToken.sol diff --git a/src/coston2/tokenPools/interfaces/IIFtsoRewardManager.sol b/src/coston2/tokenPools/interfaces/IIFtsoRewardManager.sol new file mode 100644 index 0000000..f7907a3 --- /dev/null +++ b/src/coston2/tokenPools/interfaces/IIFtsoRewardManager.sol @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IFtsoRewardManager.sol"; +import "../interfaces/IITokenPool.sol"; +import "../../inflation/interfaces/IIInflationReceiverV1.sol"; + +interface IIFtsoRewardManager is IFtsoRewardManager, IIInflationReceiverV1, IITokenPool { + + event DailyAuthorizedInflationSet(uint256 authorizedAmountWei); + event InflationReceived(uint256 amountReceivedWei); + event RewardsBurned(uint256 amountBurnedWei); + + function activate() external; + function enableClaims() external; + function deactivate() external; + function closeExpiredRewardEpoch(uint256 _rewardEpochId) external; + + function distributeRewards( + address[] memory addresses, + uint256[] memory weights, + uint256 totalWeight, + uint256 epochId, + address ftso, + uint256 priceEpochDurationSeconds, + uint256 currentRewardEpoch, + uint256 priceEpochEndTime, + uint256 votePowerBlock + ) external; + + function accrueUnearnedRewards( + uint256 epochId, + uint256 priceEpochDurationSeconds, + uint256 priceEpochEndTime + ) external; + + function firstClaimableRewardEpoch() external view returns (uint256); + + /** + * @notice Returns the information on unclaimed reward of `_dataProvider` for `_rewardEpoch` + * @param _rewardEpoch reward epoch number + * @param _dataProvider address representing the data provider + * @return _amount number representing the unclaimed amount + * @return _weight number representing the share that has not yet been claimed + */ + function getUnclaimedReward( + uint256 _rewardEpoch, + address _dataProvider + ) + external view + returns ( + uint256 _amount, + uint256 _weight + ); +} diff --git a/src/coston2/tokenPools/interfaces/IIGenericRewardManager.sol b/src/coston2/tokenPools/interfaces/IIGenericRewardManager.sol new file mode 100644 index 0000000..c543ef6 --- /dev/null +++ b/src/coston2/tokenPools/interfaces/IIGenericRewardManager.sol @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IGenericRewardManager.sol"; +import "../interfaces/IITokenPool.sol"; +import "../../inflation/interfaces/IIInflationReceiverV1.sol"; + +interface IIGenericRewardManager is IGenericRewardManager, IIInflationReceiverV1, IITokenPool { + + event DailyAuthorizedInflationSet(uint256 authorizedAmountWei); + event InflationReceived(uint256 amountReceivedWei); + + function activate() external; + function deactivate() external; + + function distributeRewards( + address[] memory _addresses, + uint256[] memory _rewardAmounts + ) external; + + function getTotals() + external view + returns ( + uint256 _totalAwardedWei, + uint256 _totalClaimedWei, + uint256 _totalInflationAuthorizedWei, + uint256 _totalInflationReceivedWei, + uint256 _lastInflationAuthorizationReceivedTs, + uint256 _dailyAuthorizedInflation + ); +} diff --git a/src/coston2/tokenPools/interfaces/IIIncentivePoolAllocation.sol b/src/coston2/tokenPools/interfaces/IIIncentivePoolAllocation.sol new file mode 100644 index 0000000..a395bee --- /dev/null +++ b/src/coston2/tokenPools/interfaces/IIIncentivePoolAllocation.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIIncentivePoolPercentageProvider.sol"; +import "./IIIncentivePoolSharingPercentageProvider.sol"; + +interface IIIncentivePoolAllocation is IIIncentivePoolPercentageProvider, IIIncentivePoolSharingPercentageProvider { + +} diff --git a/src/coston2/tokenPools/interfaces/IIIncentivePoolPercentageProvider.sol b/src/coston2/tokenPools/interfaces/IIIncentivePoolPercentageProvider.sol new file mode 100644 index 0000000..f9bea30 --- /dev/null +++ b/src/coston2/tokenPools/interfaces/IIIncentivePoolPercentageProvider.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIIncentivePoolPercentageProvider { + /** + * Return the annual incentivePool rate in bips. + */ + function getAnnualPercentageBips() external returns(uint256); +} diff --git a/src/coston2/tokenPools/interfaces/IIIncentivePoolReceiver.sol b/src/coston2/tokenPools/interfaces/IIIncentivePoolReceiver.sol new file mode 100644 index 0000000..d1c4f10 --- /dev/null +++ b/src/coston2/tokenPools/interfaces/IIIncentivePoolReceiver.sol @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIIncentivePoolReceiver { + /** + * Notify the receiver that it is entitled to receive `_toAuthorizeWei` incentive amount. + * @param _toAuthorizeWei the amount of incentive that can be awarded in the coming day + */ + function setDailyAuthorizedIncentive(uint256 _toAuthorizeWei) external; + + /** + * Receive native tokens from incentivePool. + */ + function receiveIncentive() external payable; + + /** + * IncentivePool receivers have a reference to the IncentivePool contract. + */ + function getIncentivePoolAddress() external returns(address); + + /** + * Implement this function for updating incentivePool receiver contracts through AddressUpdater. + */ + function getContractName() external view returns (string memory); +} diff --git a/src/coston2/tokenPools/interfaces/IIIncentivePoolSharingPercentageProvider.sol b/src/coston2/tokenPools/interfaces/IIIncentivePoolSharingPercentageProvider.sol new file mode 100644 index 0000000..8910145 --- /dev/null +++ b/src/coston2/tokenPools/interfaces/IIIncentivePoolSharingPercentageProvider.sol @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIIncentivePoolReceiver.sol"; + +struct SharingPercentage { + IIIncentivePoolReceiver incentivePoolReceiver; + uint256 percentBips; +} + +interface IIIncentivePoolSharingPercentageProvider { + /** + * Return the shared percentage per incentivPool receiver. + * @dev Assumption is that implementer edited that percents sum to 100 pct and + * that receiver addresses are valid. + */ + function getSharingPercentages() external returns(SharingPercentage[] memory); +} diff --git a/src/coston2/tokenPools/interfaces/IITokenPool.sol b/src/coston2/tokenPools/interfaces/IITokenPool.sol new file mode 100644 index 0000000..a8a463f --- /dev/null +++ b/src/coston2/tokenPools/interfaces/IITokenPool.sol @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IITokenPool { + + /** + * @notice Return token pool supply data + * @return _lockedFundsWei Funds that are intentionally locked in the token pool + * and not part of circulating supply + * @return _totalInflationAuthorizedWei Total inflation authorized amount (wei) + * @return _totalClaimedWei Total claimed amount (wei) + */ + function getTokenPoolSupplyData() external returns ( + uint256 _lockedFundsWei, + uint256 _totalInflationAuthorizedWei, + uint256 _totalClaimedWei + ); +} diff --git a/src/coston2/utils/interfaces/IIFtsoRegistry.sol b/src/coston2/utils/interfaces/IIFtsoRegistry.sol new file mode 100644 index 0000000..82d239a --- /dev/null +++ b/src/coston2/utils/interfaces/IIFtsoRegistry.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../ftso/interfaces/IIFtso.sol"; +import "../../IFtsoRegistry.sol"; + + +interface IIFtsoRegistry is IFtsoRegistry { + + // returns ftso index + function addFtso(IIFtso _ftsoContract) external returns(uint256); + + function removeFtso(IIFtso _ftso) external; +} diff --git a/src/coston2/utils/interfaces/IIRandomProvider.sol b/src/coston2/utils/interfaces/IIRandomProvider.sol new file mode 100644 index 0000000..26b45cd --- /dev/null +++ b/src/coston2/utils/interfaces/IIRandomProvider.sol @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IIRandomProvider { + + function chillNonrevealingDataProviders(uint256 _finalizingPriceEpochId, uint256 _currentPriceEpochId) external; + + function getCurrentRandom() external view returns(uint256 _currentRandom); + + function getCurrentRandomWithQuality() external view returns(uint256 _currentRandom, bool _goodRandom); +} diff --git a/src/coston2/utils/interfaces/IIVoterWhitelister.sol b/src/coston2/utils/interfaces/IIVoterWhitelister.sol new file mode 100644 index 0000000..34ff426 --- /dev/null +++ b/src/coston2/utils/interfaces/IIVoterWhitelister.sol @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IVoterWhitelister.sol"; + + +interface IIVoterWhitelister is IVoterWhitelister { + /** + * @notice Used to chill voter - remove from whitelist for a specified number of reward epochs + * @dev Only governance can call this method. + */ + function chillVoter( + address _voter, + uint256 _noOfRewardEpochs, + uint256[] memory _ftsoIndices + ) + external + returns( + bool[] memory _removed, + uint256 _untilRewardEpoch + ); + + /** + * Set the maximum number of voters in the whitelist for FTSO at index `_ftsoIndex`. + * Possibly removes several voters with the least votepower from the whitelist. + * Only governance can call this method. + */ + function setMaxVotersForFtso(uint256 _ftsoIndex, uint256 _newMaxVoters) external; + + /** + * Set the maximum number of voters in the whitelist for a new FTSO. + * Only governance can call this method. + */ + function setDefaultMaxVotersForFtso(uint256 _defaultMaxVotersForFtso) external; + + /** + * Create whitelist with default size for ftso. + * Only ftso manager can call this method. + */ + function addFtso(uint256 _ftsoIndex) external; + + /** + * Clear whitelist for ftso at `_ftsoIndex`. + * Only ftso manager can call this method. + */ + function removeFtso(uint256 _ftsoIndex) external; + + /** + * Remove `_trustedAddress` from whitelist for ftso at `_ftsoIndex`. + */ + function removeTrustedAddressFromWhitelist(address _trustedAddress, uint256 _ftsoIndex) external; +} diff --git a/src/coston2/utils/interfaces/IUpdateValidators.sol b/src/coston2/utils/interfaces/IUpdateValidators.sol new file mode 100644 index 0000000..4788daf --- /dev/null +++ b/src/coston2/utils/interfaces/IUpdateValidators.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IUpdateValidators { + /** + update the validators after reward epoch + **/ + function updateActiveValidators() external; +} diff --git a/src/flare/ContractRegistry.sol b/src/flare/ContractRegistry.sol index ac04c55..68935bb 100644 --- a/src/flare/ContractRegistry.sol +++ b/src/flare/ContractRegistry.sol @@ -1,38 +1,46 @@ // SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; +pragma solidity ^0.8.25; -import {IFlareContractRegistry} from "./IFlareContractRegistry.sol"; - -// Auto generated imports +import { IFlareContractRegistry } from "./IFlareContractRegistry.sol"; // AUTO GENERATED - DO NOT EDIT BELOW THIS LINE -import {IPriceSubmitter} from "./IPriceSubmitter.sol"; -import {IGovernanceSettings} from "./IGovernanceSettings.sol"; -import {IFtsoRewardManager} from "./IFtsoRewardManager.sol"; -import {IFtsoRegistry} from "./IFtsoRegistry.sol"; -import {IVoterWhitelister} from "./IVoterWhitelister.sol"; -import {IDistributionToDelegators} from "./IDistributionToDelegators.sol"; -import {IFtsoManager} from "./IFtsoManager.sol"; -import {IWNat} from "./IWNat.sol"; -import {IGovernanceVotePower} from "./IGovernanceVotePower.sol"; -import {IClaimSetupManager} from "./IClaimSetupManager.sol"; -import {IGenericRewardManager} from "./IGenericRewardManager.sol"; -import {IFlareAssetRegistry} from "./IFlareAssetRegistry.sol"; -import {IValidatorRegistry} from "./IValidatorRegistry.sol"; -import {IFlareContractRegistry} from "./IFlareContractRegistry.sol"; -import {IAddressBinder} from "./IAddressBinder.sol"; -import {IPChainStakeMirror} from "./IPChainStakeMirror.sol"; -import {IPChainStakeMirrorVerifier} from "./IPChainStakeMirrorVerifier.sol"; -import {IPChainStakeMirrorMultiSigVoting} from "./IPChainStakeMirrorMultiSigVoting.sol"; -import {IRNat} from "./IRNat.sol"; -import {IFeeCalculator} from "./IFeeCalculator.sol"; -import {FtsoV2Interface} from "./FtsoV2Interface.sol"; -import {TestFtsoV2Interface} from "./TestFtsoV2Interface.sol"; -import {ProtocolsV2Interface} from "./ProtocolsV2Interface.sol"; -import {RandomNumberV2Interface} from "./RandomNumberV2Interface.sol"; -import {RewardsV2Interface} from "./RewardsV2Interface.sol"; -import {IFdcVerification} from "./IFdcVerification.sol"; -import {IFdcHub} from "./IFdcHub.sol"; -import {IFdcRequestFeeConfigurations} from "./IFdcRequestFeeConfigurations.sol"; +import { IPriceSubmitter } from "./IPriceSubmitter.sol"; +import { IGovernanceSettings } from "./IGovernanceSettings.sol"; +import { IFtsoRewardManager } from "./IFtsoRewardManager.sol"; +import { IFtsoRegistry } from "./IFtsoRegistry.sol"; +import { IVoterWhitelister } from "./IVoterWhitelister.sol"; +import { IFtsoManager } from "./IFtsoManager.sol"; +import { IWNat } from "./IWNat.sol"; +import { IGovernanceVotePower } from "./IGovernanceVotePower.sol"; +import { IClaimSetupManager } from "./IClaimSetupManager.sol"; +import { IFlareAssetRegistry } from "./IFlareAssetRegistry.sol"; +import { IFlareContractRegistry } from "./IFlareContractRegistry.sol"; +import { ISubmission } from "./ISubmission.sol"; +import { IEntityManager } from "./IEntityManager.sol"; +import { IVoterRegistry } from "./IVoterRegistry.sol"; +import { IFlareSystemsCalculator } from "./IFlareSystemsCalculator.sol"; +import { IFlareSystemsManager } from "./IFlareSystemsManager.sol"; +import { IRewardManager } from "./IRewardManager.sol"; +import { IRelay } from "./IRelay.sol"; +import { IWNatDelegationFee } from "./IWNatDelegationFee.sol"; +import { IFtsoInflationConfigurations } from "./IFtsoInflationConfigurations.sol"; +import { IFtsoRewardOffersManager } from "./IFtsoRewardOffersManager.sol"; +import { IFtsoFeedDecimals } from "./IFtsoFeedDecimals.sol"; +import { IFtsoFeedPublisher } from "./IFtsoFeedPublisher.sol"; +import { IFtsoFeedIdConverter } from "./IFtsoFeedIdConverter.sol"; +import { IFastUpdateIncentiveManager } from "./IFastUpdateIncentiveManager.sol"; +import { IFastUpdater } from "./IFastUpdater.sol"; +import { IFastUpdatesConfiguration } from "./IFastUpdatesConfiguration.sol"; +import { IFeeCalculator } from "./IFeeCalculator.sol"; +import { FtsoV2Interface } from "./FtsoV2Interface.sol"; +import { TestFtsoV2Interface } from "./TestFtsoV2Interface.sol"; +import { ProtocolsV2Interface } from "./ProtocolsV2Interface.sol"; +import { RandomNumberV2Interface } from "./RandomNumberV2Interface.sol"; +import { RewardsV2Interface } from "./RewardsV2Interface.sol"; +import { IFdcVerification } from "./IFdcVerification.sol"; +import { IFdcHub } from "./IFdcHub.sol"; +import { IFdcRequestFeeConfigurations } from "./IFdcRequestFeeConfigurations.sol"; +import { IAssetManagerController } from "./IAssetManagerController.sol"; +import { IGenericRewardManager } from "./IGenericRewardManager.sol"; // END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE // Library is intended to be used inline, so the strings are all memory allocated (instead of calldata) @@ -95,14 +103,18 @@ library ContractRegistry { } // Nice typed getters for all the important contracts - // AUTO GENERATED - DO NOT EDIT BELOW THIS LINE - function getPriceSubmitter() internal view returns (IPriceSubmitter) { +// AUTO GENERATED - DO NOT EDIT BELOW THIS LINE + function getPriceSubmitter() + internal + view + returns (IPriceSubmitter) + { return IPriceSubmitter( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PriceSubmitter")) - ) - ); + keccak256(abi.encode("PriceSubmitter")) + ) + ); } function getGovernanceSettings() @@ -113,67 +125,74 @@ library ContractRegistry { return IGovernanceSettings( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("GovernanceSettings")) - ) - ); + keccak256(abi.encode("GovernanceSettings")) + ) + ); } - function getFtsoRewardManager() internal view returns (IFtsoRewardManager) { + function getFtsoRewardManager() + internal + view + returns (IFtsoRewardManager) + { return IFtsoRewardManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRewardManager")) - ) - ); + keccak256(abi.encode("FtsoRewardManager")) + ) + ); } - function getFtsoRegistry() internal view returns (IFtsoRegistry) { + function getFtsoRegistry() + internal + view + returns (IFtsoRegistry) + { return IFtsoRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRegistry")) - ) - ); + keccak256(abi.encode("FtsoRegistry")) + ) + ); } - function getVoterWhitelister() internal view returns (IVoterWhitelister) { + function getVoterWhitelister() + internal + view + returns (IVoterWhitelister) + { return IVoterWhitelister( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("VoterWhitelister")) - ) - ); + keccak256(abi.encode("VoterWhitelister")) + ) + ); } - function getDistributionToDelegators() + function getFtsoManager() internal view - returns (IDistributionToDelegators) + returns (IFtsoManager) { - return - IDistributionToDelegators( - FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("DistributionToDelegators")) - ) - ); - } - - function getFtsoManager() internal view returns (IFtsoManager) { return IFtsoManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoManager")) - ) - ); + keccak256(abi.encode("FtsoManager")) + ) + ); } - function getWNat() internal view returns (IWNat) { + function getWNat() + internal + view + returns (IWNat) + { return IWNat( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("WNat")) - ) - ); + keccak256(abi.encode("WNat")) + ) + ); } function getGovernanceVotePower() @@ -184,155 +203,308 @@ library ContractRegistry { return IGovernanceVotePower( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("GovernanceVotePower")) - ) - ); + keccak256(abi.encode("GovernanceVotePower")) + ) + ); } - function getClaimSetupManager() internal view returns (IClaimSetupManager) { + function getClaimSetupManager() + internal + view + returns (IClaimSetupManager) + { return IClaimSetupManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ClaimSetupManager")) - ) - ); + keccak256(abi.encode("ClaimSetupManager")) + ) + ); } - function getValidatorRewardManager() + function getFlareAssetRegistry() internal view - returns (IGenericRewardManager) + returns (IFlareAssetRegistry) { return - IGenericRewardManager( + IFlareAssetRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ValidatorRewardManager")) - ) - ); + keccak256(abi.encode("FlareAssetRegistry")) + ) + ); } - function getFlareAssetRegistry() + function getFlareContractRegistry() internal view - returns (IFlareAssetRegistry) + returns (IFlareContractRegistry) { return - IFlareAssetRegistry( + IFlareContractRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareAssetRegistry")) - ) - ); + keccak256(abi.encode("FlareContractRegistry")) + ) + ); } - function getValidatorRegistry() internal view returns (IValidatorRegistry) { + function getSubmission() + internal + view + returns (ISubmission) + { return - IValidatorRegistry( + ISubmission( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ValidatorRegistry")) - ) - ); + keccak256(abi.encode("Submission")) + ) + ); } - function getFlareContractRegistry() + function getEntityManager() internal view - returns (IFlareContractRegistry) + returns (IEntityManager) { return - IFlareContractRegistry( + IEntityManager( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("EntityManager")) + ) + ); + } + + function getVoterRegistry() + internal + view + returns (IVoterRegistry) + { + return + IVoterRegistry( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("VoterRegistry")) + ) + ); + } + + function getFlareSystemsCalculator() + internal + view + returns (IFlareSystemsCalculator) + { + return + IFlareSystemsCalculator( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("FlareSystemsCalculator")) + ) + ); + } + + function getFlareSystemsManager() + internal + view + returns (IFlareSystemsManager) + { + return + IFlareSystemsManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareContractRegistry")) - ) - ); + keccak256(abi.encode("FlareSystemsManager")) + ) + ); } - function getAddressBinder() internal view returns (IAddressBinder) { + function getRewardManager() + internal + view + returns (IRewardManager) + { return - IAddressBinder( + IRewardManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("AddressBinder")) - ) - ); + keccak256(abi.encode("RewardManager")) + ) + ); } - function getPChainStakeMirror() internal view returns (IPChainStakeMirror) { + function getRelay() + internal + view + returns (IRelay) + { return - IPChainStakeMirror( + IRelay( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PChainStakeMirror")) - ) - ); + keccak256(abi.encode("Relay")) + ) + ); } - function getPChainStakeMirrorVerifier() + function getWNatDelegationFee() internal view - returns (IPChainStakeMirrorVerifier) + returns (IWNatDelegationFee) { return - IPChainStakeMirrorVerifier( + IWNatDelegationFee( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PChainStakeMirrorVerifier")) - ) - ); + keccak256(abi.encode("WNatDelegationFee")) + ) + ); } - function getPChainStakeMirrorMultiSigVoting() + function getFtsoInflationConfigurations() internal view - returns (IPChainStakeMirrorMultiSigVoting) + returns (IFtsoInflationConfigurations) { return - IPChainStakeMirrorMultiSigVoting( + IFtsoInflationConfigurations( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PChainStakeMirrorMultiSigVoting")) - ) - ); + keccak256(abi.encode("FtsoInflationConfigurations")) + ) + ); } - function getRNat() internal view returns (IRNat) { + function getFtsoRewardOffersManager() + internal + view + returns (IFtsoRewardOffersManager) + { return - IRNat( + IFtsoRewardOffersManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RNat")) - ) - ); + keccak256(abi.encode("FtsoRewardOffersManager")) + ) + ); } - function getFeeCalculator() internal view returns (IFeeCalculator) { + function getFtsoFeedDecimals() + internal + view + returns (IFtsoFeedDecimals) + { + return + IFtsoFeedDecimals( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("FtsoFeedDecimals")) + ) + ); + } + + function getFtsoFeedPublisher() + internal + view + returns (IFtsoFeedPublisher) + { + return + IFtsoFeedPublisher( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("FtsoFeedPublisher")) + ) + ); + } + + function getFtsoFeedIdConverter() + internal + view + returns (IFtsoFeedIdConverter) + { + return + IFtsoFeedIdConverter( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("FtsoFeedIdConverter")) + ) + ); + } + + function getFastUpdateIncentiveManager() + internal + view + returns (IFastUpdateIncentiveManager) + { + return + IFastUpdateIncentiveManager( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("FastUpdateIncentiveManager")) + ) + ); + } + + function getFastUpdater() + internal + view + returns (IFastUpdater) + { + return + IFastUpdater( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("FastUpdater")) + ) + ); + } + + function getFastUpdatesConfiguration() + internal + view + returns (IFastUpdatesConfiguration) + { + return + IFastUpdatesConfiguration( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("FastUpdatesConfiguration")) + ) + ); + } + + function getFeeCalculator() + internal + view + returns (IFeeCalculator) + { return IFeeCalculator( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FeeCalculator")) - ) - ); + keccak256(abi.encode("FeeCalculator")) + ) + ); } - function getFtsoV2() internal view returns (FtsoV2Interface) { + function getFtsoV2() + internal + view + returns (FtsoV2Interface) + { return FtsoV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoV2")) - ) - ); + keccak256(abi.encode("FtsoV2")) + ) + ); } - function getTestFtsoV2() internal view returns (TestFtsoV2Interface) { + function getTestFtsoV2() + internal + view + returns (TestFtsoV2Interface) + { return TestFtsoV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoV2")) - ) - ); + keccak256(abi.encode("FtsoV2")) + ) + ); } - function getProtocolsV2() internal view returns (ProtocolsV2Interface) { + function getProtocolsV2() + internal + view + returns (ProtocolsV2Interface) + { return ProtocolsV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ProtocolsV2")) - ) - ); + keccak256(abi.encode("ProtocolsV2")) + ) + ); } function getRandomNumberV2() @@ -343,36 +515,48 @@ library ContractRegistry { return RandomNumberV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RandomNumberV2")) - ) - ); + keccak256(abi.encode("RandomNumberV2")) + ) + ); } - function getRewardsV2() internal view returns (RewardsV2Interface) { + function getRewardsV2() + internal + view + returns (RewardsV2Interface) + { return RewardsV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RewardsV2")) - ) - ); + keccak256(abi.encode("RewardsV2")) + ) + ); } - function getFdcVerification() internal view returns (IFdcVerification) { + function getFdcVerification() + internal + view + returns (IFdcVerification) + { return IFdcVerification( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcVerification")) - ) - ); + keccak256(abi.encode("FdcVerification")) + ) + ); } - function getFdcHub() internal view returns (IFdcHub) { + function getFdcHub() + internal + view + returns (IFdcHub) + { return IFdcHub( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcHub")) - ) - ); + keccak256(abi.encode("FdcHub")) + ) + ); } function getFdcRequestFeeConfigurations() @@ -383,10 +567,36 @@ library ContractRegistry { return IFdcRequestFeeConfigurations( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcRequestFeeConfigurations")) - ) - ); + keccak256(abi.encode("FdcRequestFeeConfigurations")) + ) + ); + } + + function getAssetManagerController() + internal + view + returns (IAssetManagerController) + { + return + IAssetManagerController( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("AssetManagerController")) + ) + ); } - // END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE -} + function getValidatorRewardManager() + internal + view + returns (IGenericRewardManager) + { + return + IGenericRewardManager( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("ValidatorRewardManager")) + ) + ); + } + +// END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE +} \ No newline at end of file diff --git a/src/flare/IAgentAlwaysAllowedMinters.sol b/src/flare/IAgentAlwaysAllowedMinters.sol new file mode 100644 index 0000000..48a4ea1 --- /dev/null +++ b/src/flare/IAgentAlwaysAllowedMinters.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IAgentAlwaysAllowedMinters { + function addAlwaysAllowedMinterForAgent(address _agentVault, address _minter) + external; + + function removeAlwaysAllowedMinterForAgent(address _agentVault, address _minter) + external; + + function alwaysAllowedMintersForAgent(address _agentVault) + external view + returns (address[] memory); +} diff --git a/src/flare/IAgentOwnerRegistry.sol b/src/flare/IAgentOwnerRegistry.sol new file mode 100644 index 0000000..4075ba8 --- /dev/null +++ b/src/flare/IAgentOwnerRegistry.sol @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +/** + * Agent owner management and work address management + */ +interface IAgentOwnerRegistry { + + event Whitelisted(address value); + event WhitelistingRevoked(address value); + + /** + * Agent owner's work address has been set. + */ + event WorkAddressChanged( + address indexed managementAddress, + address prevWorkAddress, + address workAddress); + + event AgentDataChanged( + address indexed managementAddress, + string name, + string description, + string iconUrl, + string termsOfUseUrl); + + error AgentNotWhitelisted(); + error WorkAddressInUse(); + + + /** + * Returns true if the address is whitelisted, false otherwise. + * @param _address address to check + */ + function isWhitelisted(address _address) external view returns (bool); + + /** + * Return agent owner's name. + * @param _managementAddress agent owner's management address + */ + function getAgentName(address _managementAddress) + external view + returns (string memory); + + /** + * Return agent owner's description. + * @param _managementAddress agent owner's management address + */ + function getAgentDescription(address _managementAddress) + external view + returns (string memory); + + /** + * Return url of the agent owner's icon. + * @param _managementAddress agent owner's management address + */ + function getAgentIconUrl(address _managementAddress) + external view + returns (string memory); + + /** + * Return url of the agent's page with terms of use. + * @param _managementAddress agent owner's management address + */ + function getAgentTermsOfUseUrl(address _managementAddress) + external view + returns (string memory); + + /** + * Get the (unique) work address for the given management address. + */ + function getWorkAddress(address _managementAddress) + external view + returns (address); + + /** + * Get the (unique) management address for the given work address. + */ + function getManagementAddress(address _workAddress) + external view + returns (address); +} \ No newline at end of file diff --git a/src/flare/IAgentPing.sol b/src/flare/IAgentPing.sol new file mode 100644 index 0000000..63770bf --- /dev/null +++ b/src/flare/IAgentPing.sol @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IAgentPing { + /** + * Agent bot liveness check. + * @param agentVault the agent vault whose owner bot to ping + * @param sender the account that triggered ping; helps bot decide whether it is important to answer + * @param query off-chain defined id of the query + */ + event AgentPing( + address indexed agentVault, + address indexed sender, + uint256 query); + + /** + * Response to agent bot liveness check. + * @param agentVault the pinged agent vault + * @param owner owner of the agent vault (management address) + * @param query repeated `query` from the AgentPing event + * @param response response data to the query + */ + event AgentPingResponse( + address indexed agentVault, + address indexed owner, + uint256 query, + string response); + + /** + * Used for liveness checks, simply emits AgentPing event. + * @param _agentVault the agent vault whose owner bot to ping + * @param _query off-chain defined id of the query + */ + function agentPing( + address _agentVault, + uint256 _query + ) external; + + /** + * Used for liveness checks, the bot's response to AgentPing event. + * Simply emits AgentPingResponse event identifying the owner. + * NOTE: may only be called by the agent vault owner + * @param _agentVault the pinged agent vault + * @param _query repeated `_query` from the agentPing + * @param _response response data to the query + */ + function agentPingResponse( + address _agentVault, + uint256 _query, + string memory _response + ) external; +} diff --git a/src/flare/IAssetManager.sol b/src/flare/IAssetManager.sol new file mode 100644 index 0000000..60953d0 --- /dev/null +++ b/src/flare/IAssetManager.sol @@ -0,0 +1,940 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {IConfirmedBlockHeightExists, IPayment, IAddressValidity, IReferencedPaymentNonexistence, + IBalanceDecreasingTransaction} + from ".//IFdcVerification.sol"; +import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; +import {IDiamondLoupe} from "./diamond/interfaces/IDiamondLoupe.sol"; +import {AssetManagerSettings} from "./data/AssetManagerSettings.sol"; +import {CollateralType} from "./data/CollateralType.sol"; +import {AgentInfo} from "./data/AgentInfo.sol"; +import {AgentSettings} from "./data/AgentSettings.sol"; +import {AvailableAgentInfo} from "./data/AvailableAgentInfo.sol"; +import {RedemptionTicketInfo} from "./data/RedemptionTicketInfo.sol"; +import {RedemptionRequestInfo} from "./data/RedemptionRequestInfo.sol"; +import {CollateralReservationInfo} from "./data/CollateralReservationInfo.sol"; +import {IAssetManagerEvents} from "./IAssetManagerEvents.sol"; +import {IAgentPing} from "./IAgentPing.sol"; +import {IRedemptionTimeExtension} from "./IRedemptionTimeExtension.sol"; +import {ICoreVaultClient} from "./ICoreVaultClient.sol"; +import {ICoreVaultClientSettings} from "./ICoreVaultClientSettings.sol"; +import {IAgentAlwaysAllowedMinters} from "./IAgentAlwaysAllowedMinters.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + + +/** + * Asset manager publicly callable methods. + */ +interface IAssetManager is + IERC165, + IDiamondLoupe, + IAssetManagerEvents, + IAgentPing, + IRedemptionTimeExtension, + ICoreVaultClient, + ICoreVaultClientSettings, + IAgentAlwaysAllowedMinters +{ + //////////////////////////////////////////////////////////////////////////////////// + // Basic system information + + /** + * Get the asset manager controller, the only address that can change settings. + * Asset manager must be attached to the asset manager controller in the system contract registry. + */ + function assetManagerController() + external view + returns (address); + + /** + * Get the f-asset contract managed by this asset manager instance. + */ + function fAsset() + external view + returns (IERC20); + + /** + * Get the price reader contract used by this asset manager instance. + */ + function priceReader() + external view + returns (address); + + /** + * Return lot size in UBA (underlying base amount - smallest amount on underlying chain, e.g. satoshi). + */ + function lotSize() + external view + returns (uint256 _lotSizeUBA); + + /** + * Return asset minting granularity - smallest unit of f-asset stored internally + * within this asset manager instance. + */ + function assetMintingGranularityUBA() + external view + returns (uint256); + + /** + * Return asset minting decimals - the number of decimals of precision for minting. + + */ + function assetMintingDecimals() + external view + returns (uint256); + + //////////////////////////////////////////////////////////////////////////////////// + // System settings + + /** + * Get complete current settings. + * @return the current settings + */ + function getSettings() + external view + returns (AssetManagerSettings.Data memory); + + /** + * When `controllerAttached` is true, asset manager has been added to the asset manager controller. + * This is required for the asset manager to be operational (create agent and minting don't work otherwise). + */ + function controllerAttached() + external view + returns (bool); + + //////////////////////////////////////////////////////////////////////////////////// + // Emergency pause + + /** + * If true, the system is in emergency pause mode and most operations (mint, redeem, liquidate) are disabled. + */ + function emergencyPaused() + external view + returns (bool); + + /** + * The time when emergency pause mode will end automatically. + */ + function emergencyPausedUntil() + external view + returns (uint256); + + //////////////////////////////////////////////////////////////////////////////////// + // Emergency pause transfers + + /** + * If true, the system is in emergency pause mode and most operations (mint, redeem, liquidate) are disabled. + */ + function transfersEmergencyPaused() + external view + returns (bool); + + /** + * The time when emergency pause mode will end automatically. + */ + function transfersEmergencyPausedUntil() + external view + returns (uint256); + + //////////////////////////////////////////////////////////////////////////////////// + // Asset manager upgrading state + + /** + * True if the asset manager is paused. + * In the paused state, minting is disabled, but all other operations (e.g. redemptions, liquidation) still work. + * Paused asset manager can be later unpaused. + */ + function mintingPaused() + external view + returns (bool); + + //////////////////////////////////////////////////////////////////////////////////// + // Timekeeping for underlying chain + + /** + * Prove that a block with given number and timestamp exists and + * update the current underlying block info if the provided data is higher. + * This method should be called by minters before minting and by agent's regularly + * to prevent current block being too outdated, which gives too short time for + * minting or redemption payment. + * NOTE: anybody can call. + * @param _proof proof that a block with given number and timestamp exists + */ + function updateCurrentBlock( + IConfirmedBlockHeightExists.Proof calldata _proof + ) external; + + /** + * Get block number and timestamp of the current underlying block known to the f-asset system. + * @return _blockNumber current underlying block number tracked by asset manager + * @return _blockTimestamp current underlying block timestamp tracked by asset manager + * @return _lastUpdateTs the timestamp on this chain when the current underlying block was last updated + */ + function currentUnderlyingBlock() + external view + returns (uint256 _blockNumber, uint256 _blockTimestamp, uint256 _lastUpdateTs); + + //////////////////////////////////////////////////////////////////////////////////// + // Available collateral types + + /** + * Get collateral information about a token. + */ + function getCollateralType(CollateralType.Class _collateralClass, IERC20 _token) + external view + returns (CollateralType.Data memory); + + /** + * Get the list of all available and deprecated tokens used for collateral. + */ + function getCollateralTypes() + external view + returns (CollateralType.Data[] memory); + + //////////////////////////////////////////////////////////////////////////////////// + // Agent create / destroy + + /** + * Create an agent vault. + * The agent will always be identified by `_agentVault` address. + * (Externally, one account may own several agent vaults, + * but in fasset system, each agent vault acts as an independent agent.) + * NOTE: may only be called by an agent on the allowed agent list. + * Can be called from the management or the work agent owner address. + * @return _agentVault new agent vault address + */ + function createAgentVault( + IAddressValidity.Proof calldata _addressProof, + AgentSettings.Data calldata _settings + ) external + returns (address _agentVault); + + /** + * Announce that the agent is going to be destroyed. At this time, the agent must not have any mintings + * or collateral reservations and must not be on the available agents list. + * NOTE: may only be called by the agent vault owner. + * @return _destroyAllowedAt the timestamp at which the destroy can be executed + */ + function announceDestroyAgent( + address _agentVault + ) external + returns (uint256 _destroyAllowedAt); + + /** + * Delete all agent data, self destruct agent vault and send remaining collateral to the `_recipient`. + * Procedure for destroying agent: + * - exit available agents list + * - wait until all assets are redeemed or perform self-close + * - announce destroy (and wait the required time) + * - call destroyAgent() + * NOTE: may only be called by the agent vault owner. + * NOTE: the remaining funds from the vault will be transferred to the provided recipient. + * @param _agentVault address of the agent's vault to destroy + * @param _recipient address that receives the remaining funds and possible vault balance + */ + function destroyAgent( + address _agentVault, + address payable _recipient + ) external; + + /** + * When agent vault, collateral pool or collateral pool token factory is upgraded, new agent vaults + * automatically get the new implementation from the factory. But the existing agent vaults must + * be upgraded by their owners using this method. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault address of the agent's vault; both vault, its corresponding pool, and + * its pool token will be upgraded to the newest implementations + */ + function upgradeAgentVaultAndPool( + address _agentVault + ) external; + + /** + * Check if the collateral pool token has been used already by some vault. + * @param _suffix the suffix to check + */ + function isPoolTokenSuffixReserved( + string memory _suffix + ) external view + returns (bool); + + //////////////////////////////////////////////////////////////////////////////////// + // Agent settings update + + /** + * Due to the effect on the pool, all agent settings are timelocked. + * This method announces a setting change. The change can be executed after the timelock expires. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault agent vault address + * @param _name setting name, same as for `getAgentSetting` + * @return _updateAllowedAt the timestamp at which the update can be executed + */ + function announceAgentSettingUpdate( + address _agentVault, + string memory _name, + uint256 _value + ) external + returns (uint256 _updateAllowedAt); + + /** + * Due to the effect on the pool, all agent settings are timelocked. + * This method executes a setting change after the timelock expires. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault agent vault address + * @param _name setting name, same as for `getAgentSetting` + */ + function executeAgentSettingUpdate( + address _agentVault, + string memory _name + ) external; + + /** + * If the current agent's vault collateral token gets deprecated, the agent must switch with this method. + * NOTE: may only be called by the agent vault owner. + * NOTE: at the time of switch, the agent must have enough of both collaterals in the vault. + */ + function switchVaultCollateral( + address _agentVault, + IERC20 _token + ) external; + + /** + * When current pool collateral token contract (WNat) is replaced by the method setPoolWNatCollateralType, + * pools don't switch automatically. Instead, the agent must call this method that swaps old WNat tokens for + * new ones and sets it for use by the pool. + * NOTE: may only be called by the agent vault owner. + */ + function upgradeWNatContract( + address _agentVault + ) external; + + //////////////////////////////////////////////////////////////////////////////////// + // Collateral withdrawal announcement + + /** + * The agent is going to withdraw `_valueNATWei` amount of collateral from the agent vault. + * This has to be announced and the agent must then wait `withdrawalWaitMinSeconds` time. + * After that time, the agent can call `withdrawCollateral(_vaultCollateralToken, _valueNATWei)` + * on the agent vault. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault agent vault address + * @param _valueNATWei the amount to be withdrawn + * @return _withdrawalAllowedAt the timestamp when the withdrawal can be made + */ + function announceVaultCollateralWithdrawal( + address _agentVault, + uint256 _valueNATWei + ) external + returns (uint256 _withdrawalAllowedAt); + + /** + * The agent is going to redeem `_valueWei` collateral pool tokens in the agent vault. + * This has to be announced and the agent must then wait `withdrawalWaitMinSeconds` time. + * After that time, the agent can call `redeemCollateralPoolTokens(_valueNATWei)` on the agent vault. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault agent vault address + * @param _valueNATWei the amount to be withdrawn + * @return _redemptionAllowedAt the timestamp when the redemption can be made + */ + function announceAgentPoolTokenRedemption( + address _agentVault, + uint256 _valueNATWei + ) external + returns (uint256 _redemptionAllowedAt); + + //////////////////////////////////////////////////////////////////////////////////// + // Underlying balance topup + + /** + * When the agent tops up his underlying address, it has to be confirmed by calling this method, + * which updates the underlying free balance value. + * NOTE: may only be called by the agent vault owner. + * @param _payment proof of the underlying payment; must include payment + * reference of the form `0x4642505266410011000...0` + * @param _agentVault agent vault address + */ + function confirmTopupPayment( + IPayment.Proof calldata _payment, + address _agentVault + ) external; + + //////////////////////////////////////////////////////////////////////////////////// + // Underlying withdrawal announcements + + /** + * Announce withdrawal of underlying currency. + * In the event UnderlyingWithdrawalAnnounced the agent receives payment reference, which must be + * added to the payment, otherwise it can be challenged as illegal. + * Until the announced withdrawal is performed and confirmed or canceled, no other withdrawal can be announced. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault agent vault address + */ + function announceUnderlyingWithdrawal( + address _agentVault + ) external; + + /** + * Agent must provide confirmation of performed underlying withdrawal, which updates free balance with used gas + * and releases announcement so that a new one can be made. + * If the agent doesn't call this method, anyone can call it after a time (`confirmationByOthersAfterSeconds`). + * NOTE: may only be called by the owner of the agent vault + * except if enough time has passed without confirmation - then it can be called by anybody. + * @param _payment proof of the underlying payment + * @param _agentVault agent vault address + */ + function confirmUnderlyingWithdrawal( + IPayment.Proof calldata _payment, + address _agentVault + ) external; + + /** + * Cancel ongoing withdrawal of underlying currency. + * Needed in order to reset announcement timestamp, so that others cannot front-run the agent at + * `confirmUnderlyingWithdrawal` call. This could happen if withdrawal would be performed more + * than `confirmationByOthersAfterSeconds` seconds after announcement. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault agent vault address + */ + function cancelUnderlyingWithdrawal( + address _agentVault + ) external; + + //////////////////////////////////////////////////////////////////////////////////// + // Agent information + + /** + * Get (a part of) the list of all agents. + * The list must be retrieved in parts since retrieving the whole list can consume too much gas for one block. + * @param _start first index to return from the available agent's list + * @param _end end index (one above last) to return from the available agent's list + */ + function getAllAgents(uint256 _start, uint256 _end) + external view + returns (address[] memory _agents, uint256 _totalLength); + + /** + * Return detailed info about an agent, typically needed by a minter. + * @param _agentVault agent vault address + * @return structure containing agent's minting fee (BIPS), min collateral ratio (BIPS), + * and current free collateral (lots) + */ + function getAgentInfo(address _agentVault) + external view + returns (AgentInfo.Info memory); + + /** + * Get agent's setting by name. + * This allows reading individual settings. + * @param _agentVault agent vault address + * @param _name setting name, one of: `feeBIPS`, `poolFeeShareBIPS`, `redemptionPoolFeeShareBIPS`, + * `mintingVaultCollateralRatioBIPS`, `mintingPoolCollateralRatioBIPS`,`buyFAssetByAgentFactorBIPS`, + * `poolExitCollateralRatioBIPS` + */ + function getAgentSetting(address _agentVault, string memory _name) + external view + returns (uint256); + + /** + * Returns the collateral pool address of the agent identified by `_agentVault`. + */ + function getCollateralPool(address _agentVault) + external view + returns (address); + + /** + * Return the management address of the owner of the agent identified by `_agentVault`. + */ + function getAgentVaultOwner(address _agentVault) + external view + returns (address _ownerManagementAddress); + + /** + * Return vault collateral ERC20 token chosen by the agent identified by `_agentVault`. + */ + function getAgentVaultCollateralToken(address _agentVault) + external view + returns (IERC20); + + /** + * Return full vault collateral (free + locked) deposited in the vault `_agentVault`. + */ + function getAgentFullVaultCollateral(address _agentVault) + external view + returns (uint256); + + /** + * Return full pool NAT collateral (free + locked) deposited in the vault `_agentVault`. + */ + function getAgentFullPoolCollateral(address _agentVault) + external view + returns (uint256); + + /** + * Return the current liquidation factors and max liquidation amount of the agent + * identified by `_agentVault`. + */ + function getAgentLiquidationFactorsAndMaxAmount(address _agentVault) + external view + returns ( + uint256 liquidationPaymentFactorVaultBIPS, + uint256 liquidationPaymentFactorPoolBIPS, + uint256 maxLiquidationAmountUBA + ); + + /** + * Return the minimum collateral ratio of the pool collateral owned by vault `_agentVault`. + */ + function getAgentMinPoolCollateralRatioBIPS(address _agentVault) + external view + returns (uint256); + + /** + * Return the minimum collateral ratio of the vault collateral owned by vault `_agentVault`. + */ + function getAgentMinVaultCollateralRatioBIPS(address _agentVault) + external view + returns (uint256); + + //////////////////////////////////////////////////////////////////////////////////// + // List of available agents (i.e. publicly available for minting). + + /** + * Add the agent to the list of publicly available agents. + * Other agents can only self-mint. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault agent vault address + */ + function makeAgentAvailable( + address _agentVault + ) external; + + /** + * Announce exit from the publicly available agents list. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault agent vault address + * @return _exitAllowedAt the timestamp when the agent can exit + */ + function announceExitAvailableAgentList( + address _agentVault + ) external + returns (uint256 _exitAllowedAt); + + /** + * Exit the publicly available agents list. + * NOTE: may only be called by the agent vault owner and after announcement. + * @param _agentVault agent vault address + */ + function exitAvailableAgentList( + address _agentVault + ) external; + + /** + * Get (a part of) the list of available agents. + * The list must be retrieved in parts since retrieving the whole list can consume too much gas for one block. + * @param _start first index to return from the available agent's list + * @param _end end index (one above last) to return from the available agent's list + */ + function getAvailableAgentsList(uint256 _start, uint256 _end) + external view + returns (address[] memory _agents, uint256 _totalLength); + + /** + * Get (a part of) the list of available agents with extra information about agents' fee, min collateral ratio + * and available collateral (in lots). + * The list must be retrieved in parts since retrieving the whole list can consume too much gas for one block. + * NOTE: agent's available collateral can change anytime due to price changes, minting, or changes + * in agent's min collateral ratio, so it is only to be used as an estimate. + * @param _start first index to return from the available agent's list + * @param _end end index (one above last) to return from the available agent's list + */ + function getAvailableAgentsDetailedList(uint256 _start, uint256 _end) + external view + returns (AvailableAgentInfo.Data[] memory _agents, uint256 _totalLength); + + //////////////////////////////////////////////////////////////////////////////////// + // Minting + + /** + * Before paying underlying assets for minting, minter has to reserve collateral and + * pay collateral reservation fee. Collateral is reserved at ratio of agent's agentMinCollateralRatio + * to requested lots NAT market price. + * The minter receives instructions for underlying payment + * (value, fee and payment reference) in event CollateralReserved. + * Then the minter has to pay `value + fee` on the underlying chain. + * If the minter pays the underlying amount, minter obtains f-assets. + * The collateral reservation fee is split between the agent and the collateral pool. + * NOTE: the owner of the agent vault must be in the AgentOwnerRegistry. + * @param _agentVault agent vault address + * @param _lots the number of lots for which to reserve collateral + * @param _maxMintingFeeBIPS maximum minting fee (BIPS) that can be charged by the agent - best is just to + * copy current agent's published fee; used to prevent agent from front-running reservation request + * and increasing fee (that would mean that the minter would have to pay raised fee or forfeit + * collateral reservation fee) + * @param _executor the account that is allowed to execute minting (besides minter and agent) + */ + function reserveCollateral( + address _agentVault, + uint256 _lots, + uint256 _maxMintingFeeBIPS, + address payable _executor + ) external payable + returns (uint256 _collateralReservationId); + + /** + * Return the collateral reservation fee amount that has to be passed to the `reserveCollateral` method. + * NOTE: the amount paid may be larger than the required amount, but the difference is not returned. + * It is advised that the minter pays the exact amount, but when the amount is so small that the revert + * would cost more than the lost difference, the minter may want to send a slightly larger amount to compensate + * for the possibility of a FTSO price change between obtaining this value and calling `reserveCollateral`. + * @param _lots the number of lots for which to reserve collateral + * @return _reservationFeeNATWei the amount of reservation fee in NAT wei + */ + function collateralReservationFee(uint256 _lots) + external view + returns (uint256 _reservationFeeNATWei); + + /** + * Returns the data about the collateral reservation for an ongoing minting. + * Note: once the minting is executed or defaulted, the collateral reservation is deleted and this method fails. + * @param _collateralReservationId the collateral reservation id, as used for executing or defaulting the minting + */ + function collateralReservationInfo(uint256 _collateralReservationId) + external view + returns (CollateralReservationInfo.Data memory); + + /** + * After obtaining proof of underlying payment, the minter calls this method to finish the minting + * and collect the minted f-assets. + * NOTE: may only be called by the minter (= creator of CR, the collateral reservation request), + * the executor appointed by the minter, or the agent owner (= owner of the agent vault in CR). + * @param _payment proof of the underlying payment (must contain exact `value + fee` amount and correct + * payment reference) + * @param _collateralReservationId collateral reservation id + */ + function executeMinting( + IPayment.Proof calldata _payment, + uint256 _collateralReservationId + ) external; + + /** + * When the time for the minter to pay the underlying amount is over (i.e. the last underlying block has passed), + * the agent can declare payment default. Then the agent collects the collateral reservation fee + * (it goes directly to the vault), and the reserved collateral is unlocked. + * NOTE: The attestation request must be done with `checkSourceAddresses=false`. + * NOTE: may only be called by the owner of the agent vault in the collateral reservation request. + * @param _proof proof that the minter didn't pay with correct payment reference on the underlying chain + * @param _collateralReservationId id of a collateral reservation created by the minter + */ + function mintingPaymentDefault( + IReferencedPaymentNonexistence.Proof calldata _proof, + uint256 _collateralReservationId + ) external; + + /** + * If a collateral reservation request exists for more than 24 hours, payment or non-payment proof are no longer + * available. In this case the agent can call this method, which burns reserved collateral at market price + * and releases the remaining collateral (CRF is also burned). + * NOTE: may only be called by the owner of the agent vault in the collateral reservation request. + * NOTE: the agent (management address) receives the vault collateral and NAT is burned instead. Therefore + * this method is `payable` and the caller must provide enough NAT to cover the received vault collateral + * amount multiplied by `vaultCollateralBuyForFlareFactorBIPS`. + * @param _proof proof that the attestation query window can not not contain + * the payment/non-payment proof anymore + * @param _collateralReservationId collateral reservation id + */ + function unstickMinting( + IConfirmedBlockHeightExists.Proof calldata _proof, + uint256 _collateralReservationId + ) external payable; + + /** + * Agent can mint against himself. + * This is a one-step process, skipping collateral reservation and collateral reservation fee payment. + * Moreover, the agent doesn't have to be on the publicly available agents list to self-mint. + * NOTE: may only be called by the agent vault owner. + * NOTE: the caller must be a whitelisted agent. + * @param _payment proof of the underlying payment; must contain payment reference of the form + * `0x4642505266410012000...0` + * @param _agentVault agent vault address + * @param _lots number of lots to mint + */ + function selfMint( + IPayment.Proof calldata _payment, + address _agentVault, + uint256 _lots + ) external; + + /** + * If an agent has enough free underlying, they can mint immediately without any underlying payment. + * This is a one-step process, skipping collateral reservation and collateral reservation fee payment. + * Moreover, the agent doesn't have to be on the publicly available agents list to self-mint. + * NOTE: may only be called by the agent vault owner. + * NOTE: the caller must be a whitelisted agent. + * @param _agentVault agent vault address + * @param _lots number of lots to mint + */ + function mintFromFreeUnderlying( + address _agentVault, + uint64 _lots + ) external; + + //////////////////////////////////////////////////////////////////////////////////// + // Redemption + + /** + * Redeem (up to) `_lots` lots of f-assets. The corresponding amount of the f-assets belonging + * to the redeemer will be burned and the redeemer will get paid by the agent in underlying currency + * (or, in case of agent's payment default, by agent's collateral with a premium). + * NOTE: in some cases not all sent f-assets can be redeemed (either there are not enough tickets or + * more than a fixed limit of tickets should be redeemed). In this case only part of the approved assets + * are burned and redeemed and the redeemer can execute this method again for the remaining lots. + * In such a case the `RedemptionRequestIncomplete` event will be emitted, indicating the number + * of remaining lots. + * Agent receives redemption request id and instructions for underlying payment in + * RedemptionRequested event and has to pay `value - fee` and use the provided payment reference. + * @param _lots number of lots to redeem + * @param _redeemerUnderlyingAddressString the address to which the agent must transfer underlying amount + * @param _executor the account that is allowed to execute redemption default (besides redeemer and agent) + * @return _redeemedAmountUBA the actual redeemed amount; may be less than requested if there are not enough + * redemption tickets available or the maximum redemption ticket limit is reached + */ + function redeem( + uint256 _lots, + string memory _redeemerUnderlyingAddressString, + address payable _executor + ) external payable + returns (uint256 _redeemedAmountUBA); + + /** + * If the redeemer provides invalid address, the agent should provide the proof of address invalidity from the + * Flare data connector. With this, the agent's obligations are fulfilled and they can keep the underlying. + * NOTE: may only be called by the owner of the agent vault in the redemption request + * NOTE: also checks that redeemer's address is normalized, so the redeemer must normalize their address, + * otherwise it will be rejected! + * @param _proof proof that the address is invalid + * @param _redemptionRequestId id of an existing redemption request + */ + function rejectInvalidRedemption( + IAddressValidity.Proof calldata _proof, + uint256 _redemptionRequestId + ) external; + + /** + * After paying to the redeemer, the agent must call this method to unlock the collateral + * and to make sure that the redeemer cannot demand payment in collateral on timeout. + * The same method must be called for any payment status (SUCCESS, FAILED, BLOCKED). + * In case of FAILED, it just releases the agent's underlying funds and the redeemer gets paid in collateral + * after calling redemptionPaymentDefault. + * In case of SUCCESS or BLOCKED, remaining underlying funds and collateral are released to the agent. + * If the agent doesn't confirm payment in enough time (several hours, setting + * `confirmationByOthersAfterSeconds`), anybody can do it and get rewarded from the agent's vault. + * NOTE: may only be called by the owner of the agent vault in the redemption request + * except if enough time has passed without confirmation - then it can be called by anybody + * @param _payment proof of the underlying payment (must contain exact `value - fee` amount and correct + * payment reference) + * @param _redemptionRequestId id of an existing redemption request + */ + function confirmRedemptionPayment( + IPayment.Proof calldata _payment, + uint256 _redemptionRequestId + ) external; + + /** + * If the agent doesn't transfer the redeemed underlying assets in time (until the last allowed block on + * the underlying chain), the redeemer calls this method and receives payment in collateral (with some extra). + * The agent can also call default if the redeemer is unresponsive, to payout the redeemer and free the + * remaining collateral. + * NOTE: The attestation request must be done with `checkSourceAddresses=false`. + * NOTE: may only be called by the redeemer (= creator of the redemption request), + * the executor appointed by the redeemer, + * or the agent owner (= owner of the agent vault in the redemption request) + * @param _proof proof that the agent didn't pay with correct payment reference on the underlying chain + * @param _redemptionRequestId id of an existing redemption request + */ + function redemptionPaymentDefault( + IReferencedPaymentNonexistence.Proof calldata _proof, + uint256 _redemptionRequestId + ) external; + + /** + * If the agent hasn't performed the payment, the agent can close the redemption request to free underlying funds. + * It can be done immediately after the redeemer or agent calls `redemptionPaymentDefault`, + * or this method can trigger the default payment without proof, but only after enough time has passed so that + * attestation proof of non-payment is not available any more. + * NOTE: may only be called by the owner of the agent vault in the redemption request. + * @param _proof proof that the attestation query window can not not contain + * the payment/non-payment proof anymore + * @param _redemptionRequestId id of an existing, but already defaulted, redemption request + */ + function finishRedemptionWithoutPayment( + IConfirmedBlockHeightExists.Proof calldata _proof, + uint256 _redemptionRequestId + ) external; + + /** + * Returns the data about an ongoing redemption request. + * Note: once the redemptions is confirmed, the request is deleted and this method fails. + * However, if there is no payment and the redemption defaults, the method works and returns status DEFAULTED. + * @param _redemptionRequestId the redemption request id, as used for confirming or defaulting the redemption + */ + function redemptionRequestInfo(uint256 _redemptionRequestId) + external view + returns (RedemptionRequestInfo.Data memory); + + /** + * Agent can "redeem against himself" by calling `selfClose`, which burns agent's own f-assets + * and unlocks agent's collateral. The underlying funds backing the f-assets are released + * as agent's free underlying funds and can be later withdrawn after announcement. + * NOTE: may only be called by the agent vault owner. + * @param _agentVault agent vault address + * @param _amountUBA amount of f-assets to self-close + * @return _closedAmountUBA the actual self-closed amount, may be less than requested if there are not enough + * redemption tickets available or the maximum redemption ticket limit is reached + */ + function selfClose( + address _agentVault, + uint256 _amountUBA + ) external + returns (uint256 _closedAmountUBA); + + //////////////////////////////////////////////////////////////////////////////////// + // Redemption queue info + + /** + * Return (part of) the redemption queue. + * @param _firstRedemptionTicketId the ticket id to start listing from; if 0, starts from the beginning + * @param _pageSize the maximum number of redemption tickets to return + * @return _queue the (part of) the redemption queue; maximum length is _pageSize + * @return _nextRedemptionTicketId works as a cursor - if the _pageSize is reached and there are more tickets, + * it is the first ticket id not returned; if the end is reached, it is 0 + */ + function redemptionQueue( + uint256 _firstRedemptionTicketId, + uint256 _pageSize + ) external view + returns (RedemptionTicketInfo.Data[] memory _queue, uint256 _nextRedemptionTicketId); + + /** + * Return (part of) the redemption queue for a specific agent. + * @param _agentVault the agent vault address of the queried agent + * @param _firstRedemptionTicketId the ticket id to start listing from; if 0, starts from the beginning + * @param _pageSize the maximum number of redemption tickets to return + * @return _queue the (part of) the redemption queue; maximum length is _pageSize + * @return _nextRedemptionTicketId works as a cursor - if the _pageSize is reached and there are more tickets, + * it is the first ticket id not returned; if the end is reached, it is 0 + */ + function agentRedemptionQueue( + address _agentVault, + uint256 _firstRedemptionTicketId, + uint256 _pageSize + ) external view + returns (RedemptionTicketInfo.Data[] memory _queue, uint256 _nextRedemptionTicketId); + + //////////////////////////////////////////////////////////////////////////////////// + // Dust + + /** + * Due to the minting pool fees or after a lot size change by the governance, + * it may happen that less than one lot remains on a redemption ticket. This is named "dust" and + * can be self closed or liquidated, but not redeemed. However, after several additions, + * the total dust can amount to more than one lot. Using this method, the amount, rounded down + * to a whole number of lots, can be converted to a new redemption ticket. + * NOTE: we do NOT check that the caller is the agent vault owner, since we want to + * allow anyone to convert dust to tickets to increase asset fungibility. + * NOTE: dust above 1 lot is actually added to ticket at every minting, so this function need + * only be called when the agent doesn't have any minting. + * @param _agentVault agent vault address + */ + function convertDustToTicket( + address _agentVault + ) external; + + //////////////////////////////////////////////////////////////////////////////////// + // Liquidation + + /** + * Checks that the agent's collateral is too low and if true, starts agent's liquidation. + * If the agent is already in liquidation, returns the timestamp when liquidation started. + * @param _agentVault agent vault address + * @return _liquidationStartTs timestamp when liquidation started + */ + function startLiquidation( + address _agentVault + ) external + returns (uint256 _liquidationStartTs); + + /** + * Burns up to `_amountUBA` f-assets owned by the caller and pays + * the caller the corresponding amount of native currency with premium + * (premium depends on the liquidation state). + * If the agent isn't in liquidation yet, but satisfies conditions, + * automatically puts the agent in liquidation status. + * @param _agentVault agent vault address + * @param _amountUBA the amount of f-assets to liquidate + * @return _liquidatedAmountUBA liquidated amount of f-asset + * @return _amountPaidVault amount paid to liquidator (in agent's vault collateral) + * @return _amountPaidPool amount paid to liquidator (in NAT from pool) + */ + function liquidate( + address _agentVault, + uint256 _amountUBA + ) external + returns (uint256 _liquidatedAmountUBA, uint256 _amountPaidVault, uint256 _amountPaidPool); + + /** + * When the agent's collateral reaches the safe level during liquidation, the liquidation + * process can be stopped by calling this method. + * Full liquidation (i.e. the liquidation triggered by illegal underlying payment) + * cannot be stopped. + * NOTE: anybody can call. + * NOTE: if the method succeeds, the agent's liquidation has ended. + * @param _agentVault agent vault address + */ + function endLiquidation( + address _agentVault + ) external; + + //////////////////////////////////////////////////////////////////////////////////// + // Challenges + + /** + * Called with a proof of payment made from the agent's underlying address, for which + * no valid payment reference exists (valid payment references are from redemption and + * underlying withdrawal announcement calls). + * On success, immediately triggers full agent liquidation and rewards the caller. + * @param _payment proof of a transaction from the agent's underlying address + * @param _agentVault agent vault address + */ + function illegalPaymentChallenge( + IBalanceDecreasingTransaction.Proof calldata _payment, + address _agentVault + ) external; + + /** + * Called with proofs of two payments made from the agent's underlying address + * with the same payment reference (each payment reference is valid for only one payment). + * On success, immediately triggers full agent liquidation and rewards the caller. + * @param _payment1 proof of first payment from the agent's underlying address + * @param _payment2 proof of second payment from the agent's underlying address + * @param _agentVault agent vault address + */ + function doublePaymentChallenge( + IBalanceDecreasingTransaction.Proof calldata _payment1, + IBalanceDecreasingTransaction.Proof calldata _payment2, + address _agentVault + ) external; + + /** + * Called with proofs of several (otherwise legal) payments, which together make the agent's + * underlying free balance negative (i.e. the underlying address balance is less than + * the total amount of backed f-assets). + * On success, immediately triggers full agent liquidation and rewards the caller. + * @param _payments proofs of several distinct payments from the agent's underlying address + * @param _agentVault agent vault address + */ + function freeBalanceNegativeChallenge( + IBalanceDecreasingTransaction.Proof[] calldata _payments, + address _agentVault + ) external; +} diff --git a/src/flare/IAssetManagerController.sol b/src/flare/IAssetManagerController.sol new file mode 100644 index 0000000..be64480 --- /dev/null +++ b/src/flare/IAssetManagerController.sol @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {IAssetManager} from "./IAssetManager.sol"; + + +interface IAssetManagerController { + /** + * Return the list of all asset managers managed by this controller. + */ + function getAssetManagers() + external view + returns (IAssetManager[] memory); + + /** + * Check whether the asset manager is managed by this controller. + * @param _assetManager an asset manager address + */ + function assetManagerExists(address _assetManager) + external view + returns (bool); +} diff --git a/src/flare/IAssetManagerEvents.sol b/src/flare/IAssetManagerEvents.sol new file mode 100644 index 0000000..e9dd216 --- /dev/null +++ b/src/flare/IAssetManagerEvents.sol @@ -0,0 +1,525 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +/** + * All asset manager events. + */ +interface IAssetManagerEvents { + struct AgentVaultCreationData { + address collateralPool; + address collateralPoolToken; + string underlyingAddress; + address vaultCollateralToken; + address poolWNatToken; + uint256 feeBIPS; + uint256 poolFeeShareBIPS; + uint256 mintingVaultCollateralRatioBIPS; + uint256 mintingPoolCollateralRatioBIPS; + uint256 buyFAssetByAgentFactorBIPS; + uint256 poolExitCollateralRatioBIPS; + uint256 redemptionPoolFeeShareBIPS; + } + + /** + * A new agent vault was created. + */ + event AgentVaultCreated( + address indexed owner, + address indexed agentVault, + AgentVaultCreationData creationData); + + /** + * Agent has announced destroy (close) of agent vault and will be able to + * perform destroy after the timestamp `destroyAllowedAt`. + */ + event AgentDestroyAnnounced( + address indexed agentVault, + uint256 destroyAllowedAt); + + /** + * Agent has destroyed (closed) the agent vault. + */ + event AgentDestroyed( + address indexed agentVault); + + /** + * Agent has announced a withdrawal of collateral and will be able to + * withdraw the announced amount after timestamp `withdrawalAllowedAt`. + * If withdrawal was canceled (announced with amount 0), amountWei and withdrawalAllowedAt are zero. + */ + event VaultCollateralWithdrawalAnnounced( + address indexed agentVault, + uint256 amountWei, + uint256 withdrawalAllowedAt); + + /** + * Agent has announced a withdrawal of collateral and will be able to + * redeem the announced amount of pool tokens after the timestamp `withdrawalAllowedAt`. + * If withdrawal was canceled (announced with amount 0), amountWei and withdrawalAllowedAt are zero. + */ + event PoolTokenRedemptionAnnounced( + address indexed agentVault, + uint256 amountWei, + uint256 withdrawalAllowedAt); + + /** + * Agent was added to the list of available agents and can accept collateral reservation requests. + */ + event AgentAvailable( + address indexed agentVault, + uint256 feeBIPS, + uint256 mintingVaultCollateralRatioBIPS, + uint256 mintingPoolCollateralRatioBIPS, + uint256 freeCollateralLots); + + /** + * Agent exited from available agents list. + * The agent can exit the available list after the timestamp `exitAllowedAt`. + */ + event AvailableAgentExitAnnounced( + address indexed agentVault, + uint256 exitAllowedAt); + + /** + * Agent exited from available agents list. + */ + event AvailableAgentExited( + address indexed agentVault); + + /** + * Agent has initiated setting change (fee or some agent collateral ratio change). + * The setting change can be executed after the timestamp `validAt`. + */ + event AgentSettingChangeAnnounced( + address indexed agentVault, + string name, + uint256 value, + uint256 validAt); + + /** + * Agent has executed setting change (fee or some agent collateral ratio change). + */ + event AgentSettingChanged( + address indexed agentVault, + string name, + uint256 value); + + /** + * Agent or agent's collateral pool has changed token contract. + */ + event AgentCollateralTypeChanged( + address indexed agentVault, + uint8 collateralClass, + address token); + + /** + * Minter reserved collateral, paid the reservation fee, and is expected to pay the underlying funds. + * Agent's collateral was reserved. + */ + event CollateralReserved( + address indexed agentVault, + address indexed minter, + uint256 indexed collateralReservationId, + uint256 valueUBA, + uint256 feeUBA, + uint256 firstUnderlyingBlock, + uint256 lastUnderlyingBlock, + uint256 lastUnderlyingTimestamp, + string paymentAddress, + bytes32 paymentReference, + address executor, + uint256 executorFeeNatWei); + + /** + * Minter paid underlying funds in time and received the fassets. + * The agent's collateral is locked. + */ + event MintingExecuted( + address indexed agentVault, + uint256 indexed collateralReservationId, + uint256 mintedAmountUBA, + uint256 agentFeeUBA, + uint256 poolFeeUBA); + + /** + * Minter failed to pay underlying funds in time. Collateral reservation fee was paid to the agent. + * Reserved collateral was released. + */ + event MintingPaymentDefault( + address indexed agentVault, + address indexed minter, + uint256 indexed collateralReservationId, + uint256 reservedAmountUBA); + + /** + * Both minter and agent failed to present any proof within attestation time window, so + * the agent called `unstickMinting` to release reserved collateral. + */ + event CollateralReservationDeleted( + address indexed agentVault, + address indexed minter, + uint256 indexed collateralReservationId, + uint256 reservedAmountUBA); + + /** + * Agent performed self minting, either by executing selfMint with underlying deposit or + * by executing mintFromFreeUnderlying (in this case, `mintFromFreeUnderlying` is true and + * `depositedAmountUBA` is zero). + */ + event SelfMint( + address indexed agentVault, + bool mintFromFreeUnderlying, + uint256 mintedAmountUBA, + uint256 depositedAmountUBA, + uint256 poolFeeUBA); + + /** + * Redeemer started the redemption process and provided fassets. + * The amount of fassets corresponding to valueUBA was burned. + * Several RedemptionRequested events are emitted, one for every agent redeemed against + * (but multiple tickets for the same agent are combined). + * The agent's collateral is still locked. + */ + event RedemptionRequested( + address indexed agentVault, + address indexed redeemer, + uint256 indexed requestId, + string paymentAddress, + uint256 valueUBA, + uint256 feeUBA, + uint256 firstUnderlyingBlock, + uint256 lastUnderlyingBlock, + uint256 lastUnderlyingTimestamp, + bytes32 paymentReference, + address executor, + uint256 executorFeeNatWei); + + /** + * Agent rejected the redemption payment because the redeemer's address is invalid. + */ + event RedemptionRejected( + address indexed agentVault, + address indexed redeemer, + uint256 indexed requestId, + uint256 redemptionAmountUBA); + + /** + * In case there were not enough tickets or more than allowed number would have to be redeemed, + * only partial redemption is done and the `remainingLots` lots of the fassets are returned to + * the redeemer. + */ + event RedemptionRequestIncomplete( + address indexed redeemer, + uint256 remainingLots); + + /** + * Agent provided proof of redemption payment. + * Agent's collateral is released. + */ + event RedemptionPerformed( + address indexed agentVault, + address indexed redeemer, + uint256 indexed requestId, + bytes32 transactionHash, + uint256 redemptionAmountUBA, + int256 spentUnderlyingUBA); + + /** + * The time for redemption payment is over and payment proof was not provided. + * Redeemer was paid in the collateral (with extra). + * The rest of the agent's collateral is released. + * The corresponding amount of underlying currency, held by the agent, is released + * and the agent can withdraw it (after underlying withdrawal announcement). + */ + event RedemptionDefault( + address indexed agentVault, + address indexed redeemer, + uint256 indexed requestId, + uint256 redemptionAmountUBA, + uint256 redeemedVaultCollateralWei, + uint256 redeemedPoolCollateralWei); + + /** + * Agent provided the proof that redemption payment was attempted, but failed due to + * the redeemer's address being blocked (or burning more than allowed amount of gas). + * Redeemer is not paid and all of the agent's collateral is released. + * The underlying currency is also released to the agent. + */ + event RedemptionPaymentBlocked( + address indexed agentVault, + address indexed redeemer, + uint256 indexed requestId, + bytes32 transactionHash, + uint256 redemptionAmountUBA, + int256 spentUnderlyingUBA); + + /** + * Agent provided the proof that redemption payment was attempted, but failed due to + * his own error. Also triggers payment default, unless the redeemer has done it already. + */ + event RedemptionPaymentFailed( + address indexed agentVault, + address indexed redeemer, + uint256 indexed requestId, + bytes32 transactionHash, + int256 spentUnderlyingUBA, + string failureReason); + + /** + * At the end of a successful redemption, part of the redemption fee is re-minted as FAssets + * and paid to the agent's collateral pool as fee. + */ + event RedemptionPoolFeeMinted( + address indexed agentVault, + uint256 indexed requestId, + uint256 poolFeeUBA); + + /** + * Due to self-close exit, some of the agent's backed fAssets were redeemed, + * but the redemption was immediately paid in collateral so no redemption process is started. + */ + event RedeemedInCollateral( + address indexed agentVault, + address indexed redeemer, + uint256 redemptionAmountUBA, + uint256 paidVaultCollateralWei); + + /** + * Agent self-closed valueUBA of backing fassets. + */ + event SelfClose( + address indexed agentVault, + uint256 valueUBA); + + /** + * Redemption ticket with given value was created (when minting was executed). + */ + event RedemptionTicketCreated( + address indexed agentVault, + uint256 indexed redemptionTicketId, + uint256 ticketValueUBA); + + /** + * Redemption ticket value was changed (partially redeemed). + * @param ticketValueUBA the ticket value after update + */ + event RedemptionTicketUpdated( + address indexed agentVault, + uint256 indexed redemptionTicketId, + uint256 ticketValueUBA); + + /** + * Redemption ticket was deleted. + */ + event RedemptionTicketDeleted( + address indexed agentVault, + uint256 indexed redemptionTicketId); + + /** + * Due to lot size change, some dust was created for this agent during + * redemption. Value `dustUBA` is the new amount of dust. Dust cannot be directly redeemed, + * but it can be self-closed or liquidated and if it accumulates to more than 1 lot, + * it can be converted to a new redemption ticket. + */ + event DustChanged( + address indexed agentVault, + uint256 dustUBA); + + /** + * Agent entered liquidation state due to unhealthy position. + * The liquidation ends when the agent is again healthy or the agent's position is fully liquidated. + */ + event LiquidationStarted( + address indexed agentVault, + uint256 timestamp); + + /** + * Agent entered liquidation state due to illegal payment. + * Full liquidation will always liquidate the whole agent's position and + * the agent can never use the same vault and underlying address for minting again. + */ + event FullLiquidationStarted( + address indexed agentVault, + uint256 timestamp); + + /** + * Some of the agent's position was liquidated, by burning liquidator's fassets. + * Liquidator was paid in collateral with extra. + * The corresponding amount of underlying currency, held by the agent, is released + * and the agent can withdraw it (after underlying withdrawal announcement). + */ + event LiquidationPerformed( + address indexed agentVault, + address indexed liquidator, + uint256 valueUBA, + uint256 paidVaultCollateralWei, + uint256 paidPoolCollateralWei); + + /** + * Agent exited liquidation state as agent's position was healthy again and not in full liquidation. + */ + event LiquidationEnded( + address indexed agentVault); + + /** + * Part of the balance in the agent's underlying address is "free balance" that the agent can withdraw. + * It is obtained from minting / redemption fees and self-closed fassets. + * Some of this amount should be left for paying redemption (and withdrawal) gas fees, + * and the rest can be withdrawn by the agent. + * However, withdrawal has to be announced, otherwise it can be challenged as illegal payment. + * Only one announcement can exist per agent - agent has to present payment proof for withdrawal + * before starting a new one. + */ + event UnderlyingWithdrawalAnnounced( + address indexed agentVault, + uint256 indexed announcementId, + bytes32 paymentReference); + + /** + * After announcing legal underlying withdrawal and creating transaction, + * the agent must confirm the transaction. This frees the announcement so the agent can create another one. + * If the agent doesn't confirm in time, anybody can confirm the transaction after several hours. + * Failed payments must also be confirmed. + */ + event UnderlyingWithdrawalConfirmed( + address indexed agentVault, + uint256 indexed announcementId, + int256 spentUBA, + bytes32 transactionHash); + + /** + * After announcing legal underlying withdrawal agent can cancel ongoing withdrawal. + * The reason for doing that would be in resetting announcement timestamp due to any problems with underlying + * withdrawal - in order to prevent others to confirm withdrawal before agent and get some of his collateral. + */ + event UnderlyingWithdrawalCancelled( + address indexed agentVault, + uint256 indexed announcementId); + + /** + * Emitted when the agent tops up the underlying address balance. + */ + event UnderlyingBalanceToppedUp( + address indexed agentVault, + bytes32 transactionHash, + uint256 depositedUBA); + + /** + * Emitted whenever the tracked underlying balance changes. + */ + event UnderlyingBalanceChanged( + address indexed agentVault, + int256 underlyingBalanceUBA); + + /** + * An unexpected transaction from the agent's underlying address was proved. + * Whole agent's position goes into liquidation. + * The challenger is rewarded from the agent's collateral. + */ + event IllegalPaymentConfirmed( + address indexed agentVault, + bytes32 transactionHash); + + /** + * Two transactions with the same payment reference, both from the agent's underlying address, were proved. + * Whole agent's position goes into liquidation. + * The challenger is rewarded from the agent's collateral. + */ + event DuplicatePaymentConfirmed( + address indexed agentVault, + bytes32 transactionHash1, + bytes32 transactionHash2); + + /** + * Agent's underlying balance became lower than required for backing f-assets (either through payment or via + * a challenge. Agent goes to a full liquidation. + * The challenger is rewarded from the agent's collateral. + */ + event UnderlyingBalanceTooLow( + address indexed agentVault, + int256 balance, + uint256 requiredBalance); + + /** + * A setting has changed. + */ + event SettingChanged( + string name, + uint256 value); + + /** + * A setting has changed. + */ + event SettingArrayChanged( + string name, + uint256[] value); + + /** + * A contract in the settings has changed. + */ + event ContractChanged( + string name, + address value); + + /** + * Current underlying block number or timestamp has been updated. + */ + event CurrentUnderlyingBlockUpdated( + uint256 underlyingBlockNumber, + uint256 underlyingBlockTimestamp, + uint256 updatedAt); + + /** + * New collateral token has been added. + */ + event CollateralTypeAdded( + uint8 collateralClass, + address token, + uint256 decimals, + bool directPricePair, + string assetFtsoSymbol, + string tokenFtsoSymbol, + uint256 minCollateralRatioBIPS, + uint256 safetyMinCollateralRatioBIPS); + + /** + * System defined collateral ratios for the token have changed (minimal and safety collateral ratio). + */ + event CollateralRatiosChanged( + uint8 collateralClass, + address collateralToken, + uint256 minCollateralRatioBIPS, + uint256 safetyMinCollateralRatioBIPS); + + /** + * Collateral token has been marked as deprecated. After the timestamp `validUntil` passes, it will be + * considered invalid and the agents who haven't switched their collateral before will be liquidated. + */ + event CollateralTypeDeprecated( + uint8 collateralClass, + address collateralToken, + uint256 validUntil); + + /** + * Emergency pause was triggered. + */ + event EmergencyPauseTriggered( + uint256 pausedUntil); + + /** + * Emergency pause was canceled. + */ + event EmergencyPauseCanceled(); + + /** + * Emergency pause transfers was triggered. + */ + event EmergencyPauseTransfersTriggered( + uint256 pausedUntil); + + /** + * Emergency pause transfers was canceled. + */ + event EmergencyPauseTransfersCanceled(); +} diff --git a/src/flare/IClaimSetupManager.sol b/src/flare/IClaimSetupManager.sol index 384de98..17cc70c 100644 --- a/src/flare/IClaimSetupManager.sol +++ b/src/flare/IClaimSetupManager.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IDelegationAccount.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IClaimSetupManager { diff --git a/src/coston2/ICoreVault.sol b/src/flare/ICoreVaultClient.sol similarity index 90% rename from src/coston2/ICoreVault.sol rename to src/flare/ICoreVaultClient.sol index d503cad..9340e57 100644 --- a/src/coston2/ICoreVault.sol +++ b/src/flare/ICoreVaultClient.sol @@ -1,13 +1,13 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IFdcVerification.sol"; +import {IPayment} from ".//IFdcVerification.sol"; /** * Core vault */ -interface ICoreVault { +interface ICoreVaultClient { /** * Agent has requested transfer of (some of) their backing to the core vault. */ @@ -78,7 +78,7 @@ interface ICoreVault { * @param _amountUBA the amount to transfer to the core vault */ function transferToCoreVault(address _agentVault, uint256 _amountUBA) - external payable; + external; /** * Request that core vault transfers funds to the agent's underlying address, @@ -90,7 +90,7 @@ interface ICoreVault { * @param _agentVault the agent vault address * @param _lots number of lots (same lots as for minting and redemptions) */ - function requestReturnFromCoreVault(address _agentVault, uint64 _lots) + function requestReturnFromCoreVault(address _agentVault, uint256 _lots) external; /** @@ -118,19 +118,9 @@ interface ICoreVault { * must have been added to the `allowedDestinations` list in the core vault manager by * the governance before the redemption request. */ - function redeemFromCoreVault(uint64 _lots, string memory _redeemerUnderlyingAddress) + function redeemFromCoreVault(uint256 _lots, string memory _redeemerUnderlyingAddress) external; - /** - * Return the amount of NAT that has to be paid in `transferToCoreVault` call. - * @param _amountUBA the amount to transfer to the core vault - * @return _transferFeeNatWei the amount that has to be included as `msg.value` and is paid to the core vault - */ - function transferToCoreVaultFee( - uint256 _amountUBA - ) external view - returns (uint256 _transferFeeNatWei); - /** * Return the maximum amount that can be transferred and the minimum amount that * has to remain on the agent vault's underlying address. diff --git a/src/coston2/ICoreVaultSettings.sol b/src/flare/ICoreVaultClientSettings.sol similarity index 85% rename from src/coston2/ICoreVaultSettings.sol rename to src/flare/ICoreVaultClientSettings.sol index a43c345..c708303 100644 --- a/src/coston2/ICoreVaultSettings.sol +++ b/src/flare/ICoreVaultClientSettings.sol @@ -4,16 +4,13 @@ pragma solidity >=0.7.6 <0.9; /** * Core vault settings */ -interface ICoreVaultSettings { +interface ICoreVaultClientSettings { function setCoreVaultManager(address _coreVaultManager) external; function setCoreVaultNativeAddress(address payable _nativeAddress) external; - function setCoreVaultTransferFeeBIPS(uint256 _transferFeeBIPS) - external; - function setCoreVaultTransferTimeExtensionSeconds(uint256 _transferTimeExtensionSeconds) external; @@ -34,10 +31,6 @@ interface ICoreVaultSettings { external view returns (address); - function getCoreVaultTransferFeeBIPS() - external view - returns (uint256); - function getCoreVaultTransferTimeExtensionSeconds() external view returns (uint256); diff --git a/src/flare/IDelegationAccount.sol b/src/flare/IDelegationAccount.sol index 2093b99..815a909 100644 --- a/src/flare/IDelegationAccount.sol +++ b/src/flare/IDelegationAccount.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IClaimSetupManager.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDelegationAccount { diff --git a/src/flare/IFdcVerification.sol b/src/flare/IFdcVerification.sol index d7e51cd..b37662c 100644 --- a/src/flare/IFdcVerification.sol +++ b/src/flare/IFdcVerification.sol @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +import "./IRelay.sol"; import "./IAddressValidityVerification.sol"; import "./IBalanceDecreasingTransactionVerification.sol"; import "./IConfirmedBlockHeightExistsVerification.sol"; @@ -9,16 +10,25 @@ import "./IPaymentVerification.sol"; import "./IReferencedPaymentNonexistenceVerification.sol"; import "./IWeb2JsonVerification.sol"; - /** * FdcVerification interface. */ interface IFdcVerification is - IAddressValidityVerification, - IBalanceDecreasingTransactionVerification, - IConfirmedBlockHeightExistsVerification, - IEVMTransactionVerification, - IPaymentVerification, - IReferencedPaymentNonexistenceVerification, - IWeb2JsonVerification -{ } + IAddressValidityVerification, + IBalanceDecreasingTransactionVerification, + IConfirmedBlockHeightExistsVerification, + IEVMTransactionVerification, + IPaymentVerification, + IReferencedPaymentNonexistenceVerification, + IWeb2JsonVerification +{ + /** + * The FDC protocol id. + */ + function fdcProtocolId() external view returns (uint8 _fdcProtocolId); + + /** + * Relay contract address. + */ + function relay() external view returns (IRelay); +} diff --git a/src/flare/IFtsoManager.sol b/src/flare/IFtsoManager.sol index ed1c4c0..cfc7cc5 100644 --- a/src/flare/IFtsoManager.sol +++ b/src/flare/IFtsoManager.sol @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./ftso/interface/IIFtso.sol"; -import "./genesis/interface/IFtsoManagerGenesis.sol"; +import "./ftso/interfaces/IIFtso.sol"; +import "./genesis/interfaces/IFtsoManagerGenesis.sol"; interface IFtsoManager is IFtsoManagerGenesis { diff --git a/src/flare/IFtsoRegistry.sol b/src/flare/IFtsoRegistry.sol index f9d8c6a..46ab964 100644 --- a/src/flare/IFtsoRegistry.sol +++ b/src/flare/IFtsoRegistry.sol @@ -2,8 +2,8 @@ pragma solidity >=0.7.6 <0.9; pragma abicoder v2; -import "./ftso/interface/IIFtso.sol"; -import "./genesis/interface/IFtsoRegistryGenesis.sol"; +import "./ftso/interfaces/IIFtso.sol"; +import "./genesis/interfaces/IFtsoRegistryGenesis.sol"; interface IFtsoRegistry is IFtsoRegistryGenesis { diff --git a/src/flare/IGovernor.sol b/src/flare/IGovernor.sol index 48bdd0f..fff729f 100644 --- a/src/flare/IGovernor.sol +++ b/src/flare/IGovernor.sol @@ -1,14 +1,12 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; -/** - * Governor interface. - */ interface IGovernor { struct GovernorSettings { bool accept; - uint256 votingStartTs; + uint256 votingDelaySeconds; uint256 votingPeriodSeconds; uint256 vpBlockPeriodSeconds; uint256 thresholdConditionBIPS; @@ -18,15 +16,7 @@ interface IGovernor { } /** - * Enum describing a proposal state. - - * A proposal is: - * * `Pending` when first created, - * * `Active` when it’s being voted on, - * * `Defeated` or `Succeeded` as a result of the vote, - * * `Queued` when in the process of executing, - * * `Expired` when it times out or fails to execute upon a certain date, and - * * `Executed` when it goes live. + * @notice Enum describing a proposal state */ enum ProposalState { Pending, @@ -40,7 +30,7 @@ interface IGovernor { } /** - * Event emitted when a proposal is created. + * @notice Event emitted when a proposal is created */ event ProposalCreated( uint256 indexed proposalId, @@ -59,17 +49,17 @@ interface IGovernor { ); /** - * Event emitted when a proposal is canceled. + * @notice Event emitted when a proposal is canceled */ event ProposalCanceled(uint256 indexed proposalId); /** - * Event emitted when a proposal is executed. + * @notice Event emitted when a proposal is executed */ event ProposalExecuted(uint256 indexed proposalId); /** - * Event emitted when a vote is cast. + * @notice Event emitted when a vote is cast */ event VoteCast( address indexed voter, @@ -80,30 +70,30 @@ interface IGovernor { uint256 forVotePower, uint256 againstVotePower ); - + /** - * Cancels a proposal. - * @param _proposalId Unique identifier obtained by hashing proposal data. - * Emits a ProposalCanceled event + * @notice Cancels a proposal + * @param _proposalId Unique identifier obtained by hashing proposal data + * @notice Emits a ProposalCanceled event */ function cancel(uint256 _proposalId) external; /** - * Casts a vote on a proposal. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @return Vote power of the cast vote. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @return Vote power of the cast vote + * @notice Emits a VoteCast event */ function castVote(uint256 _proposalId, uint8 _support) external returns (uint256); /** - * Casts a vote on a proposal with a reason. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @param _reason Vote reason. - * @return Vote power of the cast vote. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal with a reason + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @param _reason Vote reason + * @return Vote power of the cast vote + * @notice Emits a VoteCast event */ function castVoteWithReason( uint256 _proposalId, @@ -112,13 +102,13 @@ interface IGovernor { ) external returns (uint256); /** - * Casts a vote on a proposal using the user cryptographic signature. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @param _v v part of the signature. - * @param _r r part of the signature. - * @param _s s part of the signature. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal using the user cryptographic signature + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @param _v v part of the signature + * @param _r r part of the signature + * @param _s s part of the signature + * @notice Emits a VoteCast event */ function castVoteBySig( uint256 _proposalId, @@ -129,84 +119,63 @@ interface IGovernor { ) external returns (uint256); /** - * Executes a successful proposal without execution parameters. - * @param _proposalId Id of the proposal. - * Emits a ProposalExecuted event. + * @notice Executes a successful proposal without execution parameters + * @param _description String description of the proposal + * @notice Emits a ProposalExecuted event */ - function execute(uint256 _proposalId) external; + function execute(string memory _description) external returns (uint256); /** - * Executes a successful proposal. - * @param _proposalId Id of the proposal. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * Emits a ProposalExecuted event. + * @notice Executes a successful proposal with execution parameters + * @param _targets Array of target addresses on which the calls are to be invoked + * @param _values Array of values with which the calls are to be invoked + * @param _calldatas Array of call data to be invoked + * @param _description String description of the proposal + * @notice Emits a ProposalExecuted event */ function execute( - uint256 _proposalId, address[] memory _targets, uint256[] memory _values, - bytes[] memory _calldatas - ) external payable; + bytes[] memory _calldatas, + string memory _description + ) external payable returns (uint256); /** - * Returns the current state of a proposal. - * @param _proposalId Id of the proposal. - * @return ProposalState enum. + * @notice Returns the current state of a proposal + * @param _proposalId Id of the proposal + * @return ProposalState enum */ function state(uint256 _proposalId) external view returns (ProposalState); /** - * Returns the vote power of a voter at a specific block number. - * @param _voter Address of the voter. - * @param _blockNumber The block number. - * @return Vote power of the voter at the block number. + * @notice Returns the vote power of a voter at a specific block number + * @param _voter Address of the voter + * @param _blockNumber The block number + * @return Vote power of the voter at the block number */ function getVotes(address _voter, uint256 _blockNumber) external view returns (uint256); /** - * Returns information if a voter has cast a vote on a specific proposal. - * @param _proposalId Id of the proposal. - * @param _voter Address of the voter. - * @return True if the voter has cast a vote on the proposal, and false otherwise. + * @notice Returns information if a voter has cast a vote on a specific proposal + * @param _proposalId Id of the proposal + * @param _voter Address of the voter + * @return True if the voter has cast a vote on the proposal, and false otherwise */ function hasVoted(uint256 _proposalId, address _voter) external view returns (bool); /** - * Returns proposal id determined by hashing proposal data. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * @param _description Description of the proposal. - * @return Proposal id. - */ - function getProposalId( - address[] memory _targets, - uint256[] memory _values, - bytes[] memory _calldatas, - string memory _description - ) external view returns (uint256); - - /** - * Returns the list of proposal ids. - */ - function getProposalIds() external view returns (uint256[] memory); - - /** - * Returns information of the specified proposal. - * @param _proposalId Id of the proposal. - * @return _proposer Address of the proposal submitter. - * @return _accept Type of the proposal - accept or reject. - * @return _votePowerBlock Block number used to determine the vote powers in voting process. - * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting. - * @return _voteEndTime End time (in seconds from epoch) of the proposal voting. - * @return _execStartTime Start time (in seconds from epoch) of the proposal execution window. - * @return _execEndTime End time (in seconds from epoch) of the proposal exectuion window. - * @return _thresholdConditionBIPS Percentage in BIPS of the total vote power required for proposal "quorum". - * @return _majorityConditionBIPS Percentage in BIPS of the proper relation between FOR and AGAINST votes. - * @return _circulatingSupply Circulating supply at votePowerBlock. - * @return _description Description of the proposal. + * @notice Returns information of the specified proposal + * @param _proposalId Id of the proposal + * @return _proposer Address of the proposal submitter + * @return _accept Type of the proposal - accept or reject + * @return _votePowerBlock Block number used to determine the vote powers in voting process + * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting + * @return _voteEndTime End time (in seconds from epoch) of the proposal voting + * @return _execStartTime Start time (in seconds from epoch) of the proposal execution window + * @return _execEndTime End time (in seconds from epoch) of the proposal exectuion window + * @return _thresholdConditionBIPS Percentage in BIPS of the total vote power required for proposal "quorum" + * @return _majorityConditionBIPS Percentage in BIPS of the proper relation between FOR and AGAINST votes + * @return _circulatingSupply Circulating supply at votePowerBlock */ function getProposalInfo( uint256 _proposalId @@ -222,20 +191,19 @@ interface IGovernor { uint256 _execEndTime, uint256 _thresholdConditionBIPS, uint256 _majorityConditionBIPS, - uint256 _circulatingSupply, - string memory _description + uint256 _circulatingSupply ); /** - * Returns votes (for, against) of the specified proposal. - * @param _proposalId Id of the proposal. - * @return _for Accumulated vote power for the proposal. - * @return _against Accumulated vote power against the proposal. + * @notice Returns votes (for, against) of the specified proposal + * @param _proposalId Id of the proposal + * @return _for Accumulated vote power for the proposal + * @return _against Accumulated vote power against the proposal */ function getProposalVotes( uint256 _proposalId ) - external view + external view returns ( uint256 _for, uint256 _against diff --git a/src/flare/IPollingFtso.sol b/src/flare/IPollingFtso.sol new file mode 100644 index 0000000..7bbf313 --- /dev/null +++ b/src/flare/IPollingFtso.sol @@ -0,0 +1,295 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IPollingFtso { + + /** + * @notice Struct holding the information about proposal properties + */ + struct Proposal { + string description; // description of the proposal + address proposer; // address of the proposer + bool canceled; // flag indicating if proposal has been canceled + uint256 voteStartTime; // start time of voting window (in seconds from epoch) + uint256 voteEndTime; // end time of voting window (in seconds from epoch) + uint256 thresholdConditionBIPS; // percentage in BIPS of the total vote power required for proposal "quorum" + uint256 majorityConditionBIPS; // percentage in BIPS of the proper relation between FOR and AGAINST votes + mapping(address => bool) isEligible; // flag if an address is eligible to cast a vote in a proposal + uint256 noOfEligibleMembers; // number of addresses that can vote in the proposal + } + + /** + * @notice Struct holding the information about proposal voting + */ + struct ProposalVoting { + uint256 againstVotePower; // accumulated vote power against the proposal + uint256 forVotePower; // accumulated vote power for the proposal + mapping(address => bool) hasVoted; // flag if a voter has cast a vote + } + + /** + * @notice Enum describing a proposal state + */ + enum ProposalState { + Canceled, + Pending, + Active, + Defeated, + Succeeded + } + + /** + * @notice Enum that determines vote (support) type + * @dev 0 = Against, 1 = For + */ + enum VoteType { + Against, + For + } + + /** + * @notice Event emitted when a proposal is created + */ + event FtsoProposalCreated( + uint256 indexed proposalId, + address proposer, + string description, + uint256 voteStartTime, + uint256 voteEndTime, + uint256 thresholdConditionBIPS, + uint256 majorityConditionBIPS, + address[] eligibleMembers + ); + + /** + * @notice Event emitted when a vote is cast + */ + event VoteCast( + address indexed voter, + uint256 indexed proposalId, + uint8 support, + uint256 forVotePower, + uint256 againstVotePower + ); + + /** + * @notice Event emitted when a proposal is canceled + */ + event ProposalCanceled(uint256 indexed proposalId); + + /** + * @notice Event emitted when parameters are set + */ + event ParametersSet( + uint256 votingDelaySeconds, + uint256 votingPeriodSeconds, + uint256 thresholdConditionBIPS, + uint256 majorityConditionBIPS, + uint256 proposalFeeValueWei, + uint256 addAfterRewardedEpochs, + uint256 addAfterNotChilledEpochs, + uint256 removeAfterNotRewardedEpochs, + uint256 removeAfterEligibleProposals, + uint256 removeAfterNonParticipatingProposals, + uint256 removeForDays + ); + + /** + * @notice Event emitted when management group member is added + */ + event ManagementGroupMemberAdded(address addedMember); + + /** + * @notice Event emitted when management group member is removed + */ + event ManagementGroupMemberRemoved(address removedMember); + + /** + * @notice Event emitted when maintainer is set + */ + event MaintainerSet(address newMaintainer); + + /** + * @notice Event emitted when proxy voter is set + */ + event ProxyVoterSet(address account, address proxyVoter); + + /** + * @notice Sets (or changes) contract's parameters. It is called after deployment of the contract + * and every time one of the parameters changes. + */ + function setParameters( + uint256 _votingDelaySeconds, + uint256 _votingPeriodSeconds, + uint256 _thresholdConditionBIPS, + uint256 _majorityConditionBIPS, + uint256 _proposalFeeValueWei, + uint256 _addAfterRewardedEpochs, + uint256 _addAfterNotChilledEpochs, + uint256 _removeAfterNotRewardedEpochs, + uint256 _removeAfterEligibleProposals, + uint256 _removeAfterNonParticipatingProposals, + uint256 _removeForDays + ) + external; + + /** + * @notice Cancels an existing proposal + * @param _proposalId Unique identifier of a proposal + * @notice Emits a ProposalCanceled event + */ + function cancel(uint256 _proposalId) external; + + /** + * @notice Creates a new proposal + * @param _description String description of the proposal + * @return _proposalId Unique identifier of the proposal + * @notice Emits a FtsoProposalCreated event + */ + function propose( + string memory _description + ) external payable returns (uint256); + + /** + * @notice Casts a vote on a proposal + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @notice Emits a VoteCast event + */ + function castVote(uint256 _proposalId, uint8 _support) external; + + /** + * @notice Changes list of management group members + * @param _providersToAdd Array of addresses to add to the list + * @param _providersToRemove Array of addresses to remove from the list + * @notice This operation can only be performed through a maintainer + * (mostly used for manually adding KYCed providers) + */ + function changeManagementGroupMembers( + address[] memory _providersToAdd, + address[] memory _providersToRemove + ) external; + + /** + * @notice Sets a proxy voter for data provider (i.e. address that can vote in his name) + * @param _proxyVoter Address to register as a proxy (use address(0) to remove proxy) + * @notice Emits a ProxyVoterSet event + */ + function setProxyVoter(address _proxyVoter) external; + + /** + * @notice Adds msg.sender to the management group + */ + function addMember() external; + + /** + * @notice Removes member from the management group + * @param _account Account to remove from the management group + */ + function removeMember(address _account) external; + + /** + * @notice Returns the current state of a proposal + * @param _proposalId Id of the proposal + * @return ProposalState enum + */ + function state(uint256 _proposalId) external view returns (ProposalState); + + /** + * @notice Returns whether a voter has cast a vote on a specific proposal + * @param _proposalId Id of the proposal + * @param _voter Address of the voter + * @return True if the voter has cast a vote on the proposal, and false otherwise + */ + function hasVoted(uint256 _proposalId, address _voter) external view returns (bool); + + /** + * @notice Returns information about the specified proposal + * @param _proposalId Id of the proposal + * @return _description Description of the proposal + * @return _proposer Address of the proposal submitter + * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting + * @return _voteEndTime End time (in seconds from epoch) of the proposal voting + * @return _thresholdConditionBIPS Total number of cast votes, as a percentage in BIPS of the + total vote power, required for the proposal to pass (quorum) + * @return _majorityConditionBIPS Number of FOR votes, as a percentage in BIPS of the + total cast votes, requires for the proposal to pass + * @return _noOfEligibleMembers Number of members that are eligible to vote in the specified proposal + */ + function getProposalInfo( + uint256 _proposalId + ) + external view + returns ( + string memory _description, + address _proposer, + uint256 _voteStartTime, + uint256 _voteEndTime, + uint256 _thresholdConditionBIPS, + uint256 _majorityConditionBIPS, + uint256 _noOfEligibleMembers + ); + + /** + * @notice Returns the description string that was supplied when the specified proposal was created + * @param _proposalId Id of the proposal + * @return _description Description of the proposal + */ + function getProposalDescription(uint256 _proposalId) external view + returns (string memory _description); + + /** + * @notice Returns id and description of the last created proposal + * @return _proposalId Id of the last proposal + * @return _description Description of the last proposal + */ + function getLastProposal() external view + returns ( uint256 _proposalId, string memory _description); + + /** + * @notice Returns number of votes for and against the specified proposal + * @param _proposalId Id of the proposal + * @return _for Accumulated vote power for the proposal + * @return _against Accumulated vote power against the proposal + */ + function getProposalVotes( + uint256 _proposalId + ) + external view + returns ( + uint256 _for, + uint256 _against + ); + + /** + * @notice Returns list of current management group members + * @return _list List of management group members + */ + function getManagementGroupMembers() external view returns (address[] memory _list); + + /** + * @notice Returns whether an account can create proposals + * @notice An address can make proposals if it is a member of the management group, + * one of their proxies or the maintainer of the contract + * @param _account Address of a queried account + * @return True if a queried account can propose, false otherwise + */ + function canPropose(address _account) external view returns (bool); + + /** + * @notice Returns whether an account can vote for a given proposal + * @param _account Address of the queried account + * @param _proposalId Id of the queried proposal + * @return True if account is eligible to vote, and false otherwise + */ + function canVote(address _account, uint256 _proposalId) external view returns (bool); + + /** + * @notice Returns whether an account is member of the management group + * @param _account Address of the queried account + * @return True if the queried account is member, false otherwise + */ + function isMember(address _account) external view returns (bool); +} diff --git a/src/flare/IPriceSubmitter.sol b/src/flare/IPriceSubmitter.sol index 54ebf98..4fbbf35 100644 --- a/src/flare/IPriceSubmitter.sol +++ b/src/flare/IPriceSubmitter.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./genesis/interface/IFtsoGenesis.sol"; -import "./genesis/interface/IFtsoRegistryGenesis.sol"; -import "./genesis/interface/IFtsoManagerGenesis.sol"; +import "./genesis/interfaces/IFtsoGenesis.sol"; +import "./genesis/interfaces/IFtsoRegistryGenesis.sol"; +import "./genesis/interfaces/IFtsoManagerGenesis.sol"; interface IPriceSubmitter { /** diff --git a/src/flare/IRNat.sol b/src/flare/IRNat.sol index b710fd2..76bf5bc 100644 --- a/src/flare/IRNat.sol +++ b/src/flare/IRNat.sol @@ -3,7 +3,7 @@ pragma solidity >=0.7.6 <0.9; import "./IRNatAccount.sol"; import "./IWNat.sol"; -import "@openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol"; +import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IRNat is IERC20Metadata { diff --git a/src/flare/IRNatAccount.sol b/src/flare/IRNatAccount.sol index d8c465d..fea1340 100644 --- a/src/flare/IRNatAccount.sol +++ b/src/flare/IRNatAccount.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IRNat.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRNatAccount { diff --git a/src/flare/IRedemptionTimeExtension.sol b/src/flare/IRedemptionTimeExtension.sol new file mode 100644 index 0000000..a116ce3 --- /dev/null +++ b/src/flare/IRedemptionTimeExtension.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IRedemptionTimeExtension { + function setRedemptionPaymentExtensionSeconds(uint256 _value) + external; + + function redemptionPaymentExtensionSeconds() + external view + returns (uint256); +} diff --git a/src/flare/IVPToken.sol b/src/flare/IVPToken.sol index 4ff0be0..f874698 100644 --- a/src/flare/IVPToken.sol +++ b/src/flare/IVPToken.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import {IERC20} from "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IGovernanceVotePower} from "./IGovernanceVotePower.sol"; import {IVPContractEvents} from "./IVPContractEvents.sol"; diff --git a/src/flare/IVoterPreRegistry.sol b/src/flare/IVoterPreRegistry.sol index c7d09c9..6e0a524 100644 --- a/src/flare/IVoterPreRegistry.sol +++ b/src/flare/IVoterPreRegistry.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./protocol/interface/IIVoterRegistry.sol"; +import "./protocol/interfaces/IIVoterRegistry.sol"; interface IVoterPreRegistry { diff --git a/src/flare/IWNat.sol b/src/flare/IWNat.sol index ade3c7a..59cee8e 100644 --- a/src/flare/IWNat.sol +++ b/src/flare/IWNat.sol @@ -1,42 +1,34 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IVPToken.sol"; -import "./token/interface/IICleanable.sol"; - - -/** - * @title Wrapped Native token - * Accept native token deposits and mint ERC20 WNAT (wrapped native) tokens 1-1. - */ -interface IWNat is IVPToken, IICleanable { +interface IWNat { /** - * Deposit Native and mint wNat ERC20. + * @notice Deposit native token and mint WNAT ERC20. */ function deposit() external payable; /** - * Deposit Native from msg.sender and mints WNAT ERC20 to recipient address. - * @param recipient An address to receive minted WNAT. + * @notice Withdraw native token and burn WNAT ERC20. + * @param _amount The amount to withdraw. */ - function depositTo(address recipient) external payable; - + function withdraw(uint256 _amount) external; + /** - * Withdraw Native and burn WNAT ERC20. - * @param amount The amount to withdraw. + * @notice Deposit native token from msg.sender and mint WNAT ERC20. + * @param _recipient An address to receive minted WNAT. */ - function withdraw(uint256 amount) external; - + function depositTo(address _recipient) external payable; + /** - * Withdraw WNAT from an owner and send native tokens to msg.sender given an allowance. - * @param owner An address spending the Native tokens. - * @param amount The amount to spend. + * @notice Withdraw WNAT from an owner and send NAT to msg.sender given an allowance. + * @param _owner An address spending the native tokens. + * @param _amount The amount to spend. * * Requirements: * - * - `owner` must have a balance of at least `amount`. - * - the caller must have allowance for `owners`'s tokens of at least - * `amount`. + * - `_owner` must have a balance of at least `_amount`. + * - the caller must have allowance for `_owners`'s tokens of at least + * `_amount`. */ - function withdrawFrom(address owner, uint256 amount) external; + function withdrawFrom(address _owner, uint256 _amount) external; } diff --git a/src/flare/IWeb2JsonVerification.sol b/src/flare/IWeb2JsonVerification.sol index 8369e1a..d0a5d25 100644 --- a/src/flare/IWeb2JsonVerification.sol +++ b/src/flare/IWeb2JsonVerification.sol @@ -4,5 +4,5 @@ pragma solidity >=0.7.6 <0.9; import "./IWeb2Json.sol"; interface IWeb2JsonVerification { - function verifyJsonApi(IWeb2Json.Proof calldata _proof) external view returns (bool _proved); + function verifyWeb2Json(IWeb2Json.Proof calldata _proof) external view returns (bool _proved); } diff --git a/src/flare/addressUpdater/interfaces/IIAddressUpdatable.sol b/src/flare/addressUpdater/interfaces/IIAddressUpdatable.sol new file mode 100644 index 0000000..e8bd84e --- /dev/null +++ b/src/flare/addressUpdater/interfaces/IIAddressUpdatable.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IIAddressUpdatable { + /** + * @notice Updates contract addresses - should be called only from AddressUpdater contract + * @param _contractNameHashes list of keccak256(abi.encode(...)) contract names + * @param _contractAddresses list of contract addresses corresponding to the contract names + */ + function updateContractAddresses( + bytes32[] memory _contractNameHashes, + address[] memory _contractAddresses + ) external; +} diff --git a/src/flare/addressUpdater/interfaces/IIAddressUpdater.sol b/src/flare/addressUpdater/interfaces/IIAddressUpdater.sol new file mode 100644 index 0000000..9973368 --- /dev/null +++ b/src/flare/addressUpdater/interfaces/IIAddressUpdater.sol @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IIAddressUpdater { + + /** + * @notice Returns all contract names and corresponding addresses + */ + function getContractNamesAndAddresses() external view returns( + string[] memory _contractNames, + address[] memory _contractAddresses + ); + + /** + * @notice Returns contract address for the given name - might be address(0) + * @param _name name of the contract + */ + function getContractAddress(string calldata _name) external view returns(address); + + /** + * @notice Returns contract address for the given name hash - might be address(0) + * @param _nameHash hash of the contract name (keccak256(abi.encode(name)) + */ + function getContractAddressByHash(bytes32 _nameHash) external view returns(address); + + /** + * @notice Returns contract addresses for the given names - might be address(0) + * @param _names names of the contracts + */ + function getContractAddresses(string[] calldata _names) external view returns(address[] memory); + + /** + * @notice Returns contract addresses for the given name hashes - might be address(0) + * @param _nameHashes hashes of the contract names (keccak256(abi.encode(name)) + */ + function getContractAddressesByHash(bytes32[] calldata _nameHashes) external view returns(address[] memory); +} diff --git a/src/flare/assetRegistry/interfaces/IIERC20WithMetadata.sol b/src/flare/assetRegistry/interfaces/IIERC20WithMetadata.sol new file mode 100644 index 0000000..68a9631 --- /dev/null +++ b/src/flare/assetRegistry/interfaces/IIERC20WithMetadata.sol @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + + +/** + * The methods of this interface are optional in ERC20 standard, so they are left out of IERC20 interface. + * However, any sane implementation includes them, and they are mandatory for the tokens in FlareAssetRegistry. + */ +interface IIERC20WithMetadata is IERC20 { + /** + * Returns the name of the token. + */ + function name() external view returns (string memory); + + /** + * Returns the symbol of the token, usually a shorter version of the name. + */ + function symbol() external view returns (string memory); + + /** + * Returns the number of decimals used to get its user representation. + * For example, if `decimals` equals `2`, a balance of `505` tokens should + * be displayed to a user as `5,05` (`505 / 10 ** 2`). + * + * Tokens usually opt for a value of 18, imitating the relationship between + * Ether and Wei. + * + * NOTE: This information is only used for _display_ purposes: the methods + * of the contract should always work with the smallest unit (e.g. wei). + */ + function decimals() external view returns (uint8); +} diff --git a/src/flare/assetRegistry/interfaces/IIFlareAssetRegistry.sol b/src/flare/assetRegistry/interfaces/IIFlareAssetRegistry.sol new file mode 100644 index 0000000..daa0284 --- /dev/null +++ b/src/flare/assetRegistry/interfaces/IIFlareAssetRegistry.sol @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../IFlareAssetRegistry.sol"; + + +interface IIFlareAssetRegistry is IFlareAssetRegistry { + /** + * Allows a provider contract to register assets. + * @param _provider address of the provider (a contract implementing IIFlareAssetRegistryProvider) + * @param _registerAssets if true, all the assets held by the provider are immediately registered; + * should usually be true, but can be false to avoid unbounded work in some cases + * @dev Only governance can call. + */ + function registerProvider(address _provider, bool _registerAssets) external; + + /** + * Remove the provider contract from known providers (e.g. when a new version of the provider is deployed, the + * old one will be removed). + * @param _provider address of the provider (a contract implementing IIFlareAssetRegistryProvider) + * @param _unregisterAssets if true, all the assets belonging to the provider are automatically unregistered; + * should usually be true, but can be false to avoid unbounded work in some cases - in this case, + * all the assets must be unregistered before calling this method + * @dev Only governance can call. + */ + function unregisterProvider(address _provider, bool _unregisterAssets) external; + + /** + * Unregisters and re-registers all the assets belonging to the given provider. + * @param _provider address of the provider (a contract implementing IIFlareAssetRegistryProvider) + * @dev Only governance can call (without timelock). + */ + function refreshProviderAssets(address _provider) external; + + /** + * Register a new asset. + * @param _token address of the asset (a contract implementing IERC20 interface with implemented symbol()) + * @dev Can only be called by a registered provider. + */ + function registerAsset(address _token) external; + + /** + * Unregister an asset. + * @param _token address of the asset (a contract implementing IERC20 interface with implemented symbol()) + * @dev Can only be called by the provider which registered the token. + */ + function unregisterAsset(address _token) external; +} diff --git a/src/flare/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol b/src/flare/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol new file mode 100644 index 0000000..6d9cde2 --- /dev/null +++ b/src/flare/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IIFlareAssetRegistryProvider { + /** + * Returns a unique hash identifying this provider and its assets. + */ + function assetType() external view returns (bytes32); + + /** + * @notice Returns the addresses of all Flare Assets + */ + function allAssets() external view returns (address[] memory); + + /** + * @notice Returns a generic asset attribute value. + * @param _token The token's address + * @param _nameHash attributes name's hash + * @return _defined true if the attribute is defined for this token + * @return _value attribute value, may have to be cast into some other type + */ + function getAttribute(address _token, bytes32 _nameHash) external view returns (bool _defined, bytes32 _value); + +} diff --git a/src/flare/customFeeds/interface/IICustomFeed.sol b/src/flare/customFeeds/interfaces/IICustomFeed.sol similarity index 100% rename from src/flare/customFeeds/interface/IICustomFeed.sol rename to src/flare/customFeeds/interfaces/IICustomFeed.sol diff --git a/src/songbird/userInterfaces/data/AgentInfo.sol b/src/flare/data/AgentInfo.sol similarity index 89% rename from src/songbird/userInterfaces/data/AgentInfo.sol rename to src/flare/data/AgentInfo.sol index cace872..d105789 100644 --- a/src/songbird/userInterfaces/data/AgentInfo.sol +++ b/src/flare/data/AgentInfo.sol @@ -1,189 +1,143 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; - +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AgentInfo { enum Status { // agent is operating normally NORMAL, - // agent in collateral call band - CCB, // liquidation due to collateral ratio - ends when agent is healthy LIQUIDATION, // illegal payment liquidation - always liquidates all and then agent must close vault FULL_LIQUIDATION, // agent announced destroy, cannot mint again; all existing mintings have been redeemed before - DESTROYING + DESTROYING, + // agent has been destroyed, cannot do anything except return info + // owner can still withdraw tokens from the vault + DESTROYED } struct Info { // Current agent's status. AgentInfo.Status status; - // Agent vault owner's management address, used for occasional administration. // Immutable. address ownerManagementAddress; - // Agent vault owner's work address, used for automatic operations. // Can be changed by a call from the owner's management address. address ownerWorkAddress; - // Agent's collateral pool address address collateralPool; - // Agent collateral pool's pool token address address collateralPoolToken; - // Underlying address as string - to be used for minting payments. // For most other purposes, you use underlyingAddressHash, which is `keccak256(underlyingAddressString)`. string underlyingAddressString; - // If true, anybody can mint against this agent. // If false, the agent can only self-mint. // Once minted, all redemption tickets go to the same (public) queue, regardless of this flag. bool publiclyAvailable; - // Current fee the agent charges for minting (paid in underlying currency). uint256 feeBIPS; - // Share of the minting fee that goes to the pool as percentage of the minting fee. // This share of fee is minted as f-assets and belongs to the pool. uint256 poolFeeShareBIPS; - // The token identifier of the agent's current vault collateral. // Token identifier can be used to call AssetManager.getCollateralType(). IERC20 vaultCollateralToken; - // Amount, set by agent, at which locked and free collateral are calculated for new mintings. // For agent's vault collateral. uint256 mintingVaultCollateralRatioBIPS; - // Amount, set by agent, at which locked and free collateral are calculated for new mintings. // For pool collateral. uint256 mintingPoolCollateralRatioBIPS; - // The maximum number of lots that the agent can mint. // This can change any moment due to minting, redemption or price changes. uint256 freeCollateralLots; - // Total amount of vault collateral in agent's vault. uint256 totalVaultCollateralWei; - // Free collateral, available for new mintings. // Note: this value doesn't tell you anything about agent being near liquidation, since it is // calculated at agentMinCollateralRatio, not minCollateralRatio. // Use collateralRatioBIPS to see whether the agent is near liquidation. uint256 freeVaultCollateralWei; - // The actual agent's collateral ratio, as it is used in liquidation. // For calculation, the system checks both FTSO prices and trusted provider's prices and uses // the ones that give higher ratio. uint256 vaultCollateralRatioBIPS; - // The token identifier of the agent's current vault collateral. // Token identifier can be used to call AssetManager.getCollateralType(). IERC20 poolWNatToken; - // Total amount of NAT collateral in agent's pool. uint256 totalPoolCollateralNATWei; - // Free NAT pool collateral (see vault collateral for details). uint256 freePoolCollateralNATWei; - // The actual pool collateral ratio (see vault collateral for details). uint256 poolCollateralRatioBIPS; - // The amount of pool tokens that belong to agent's vault. This limits the amount of possible // minting: to be able to mint, the NAT value of all backed fassets together with new ones, times // mintingPoolHoldingsRequiredBIPS, must be smaller than the agent's pool tokens amount converted to NAT. // Note: the amount of agent's pool tokens only affects minting, not liquidation. uint256 totalAgentPoolTokensWei; - // The amount of vault collateral that will be withdrawn by the agent. uint256 announcedVaultCollateralWithdrawalWei; - // The amount of pool tokens that will be withdrawn by the agent. uint256 announcedPoolTokensWithdrawalWei; - // Free agent's pool tokens. uint256 freeAgentPoolTokensWei; - // Total amount of minted f-assets. uint256 mintedUBA; - // Total amount reserved for ongoing mintings. uint256 reservedUBA; - // Total amount of ongoing redemptions. uint256 redeemingUBA; - // Total amount of ongoing redemptions that lock the pool collateral. // (In pool self-close exits, pool collateral is not locked. So the amount of locked // collateral in the pool can be less than the amount of locked vault collateral.) uint256 poolRedeemingUBA; - // Total amount of dust (unredeemable minted f-assets). // Note: dustUBA is part of mintedUBA, so the amount of redeemable f-assets is calculated as // `mintedUBA - dustUBA` uint256 dustUBA; - // Liquidation info - // If the agent is in CCB or if current liquidation started in CCB, the time agent entered CCB (otherwise 0). - uint256 ccbStartTimestamp; - // If the agent is in LIQUIDATION or FULL_LIQUIDATION, the time agent entered liquidation. - // If the agent is in CCB, the time agent will enter liquidation (in future). // If status is neither of that, returns 0. // Can be used for calculating current liquidation premium, which depends on time since liquidation started. uint256 liquidationStartTimestamp; - // When agent is in liquidation, this is the amount o FAssets that need to be liquidated to bring the agent's // position to safety. When performing liquidation, only up to this amount of FAssets will be liquidated. // If not in liquidation, this value is 0. // Since the liquidation state may need to be upgraded by, call `startLiquidation` before // `getAgentInfo` to get the value that will actually be used in liquidation. uint256 maxLiquidationAmountUBA; - // When agent is in liquidation, this is the factor (in BIPS) of the converted value of the liquidated // FAssets paid by the vault collateral. If not in liquidation, this value is 0. uint256 liquidationPaymentFactorVaultBIPS; - // When agent is in liquidation, this is the factor (in BIPS) of the converted value of the liquidated // FAssets paid by the pool collateral. If not in liquidation, this value is 0. uint256 liquidationPaymentFactorPoolBIPS; - // Total underlying balance (backing and free). int256 underlyingBalanceUBA; - // The minimum underlying balance that has to be held by the agent. Below this, agent is liquidated. uint256 requiredUnderlyingBalanceUBA; - // Underlying balance not backing anything (can be used for gas/fees or withdrawn after announcement). int256 freeUnderlyingBalanceUBA; - // Current underlying withdrawal announcement (or 0 if no announcement was made). uint256 announcedUnderlyingWithdrawalId; - // The factor set by the agent to multiply the price at which agent buys f-assets from pool // token holders on self-close exit (when requested or the redeemed amount is less than 1 lot). uint256 buyFAssetByAgentFactorBIPS; - // The minimum collateral ratio above which a staker can exit the pool // (this is CR that must be left after exit). // Must be higher than system minimum collateral ratio for pool collateral. uint256 poolExitCollateralRatioBIPS; - - // The CR below which it is possible to enter the pool at discounted rate (to prevent liquidation). - // Must be higher than system minimum collateral ratio for pool collateral. - uint256 poolTopupCollateralRatioBIPS; - - // The discount to pool token price when entering and pool CR is below pool topup CR. - uint256 poolTopupTokenPriceFactorBIPS; - - // Agent's handshake type - minting or redeeming can be rejected. - // 0 - no verification, 1 - manual verification, ... - uint256 handshakeType; + // The redemption fee share paid to the pool (as FAssets). + // In redemption dominated situations (when agent requests return from core vault to earn + // from redemption fees), pool can get some share to make it sustainable for pool users. + // NOTE: the pool fee share is locked at the redemption request time, but is charged at the redemption + // confirmation time. If agent uses all the redemption fee for transaction fees, this could make the + // agent's free underlying balance negative. + uint256 redemptionPoolFeeShareBIPS; } } diff --git a/src/coston/userInterfaces/data/AgentSettings.sol b/src/flare/data/AgentSettings.sol similarity index 79% rename from src/coston/userInterfaces/data/AgentSettings.sol rename to src/flare/data/AgentSettings.sol index cded4c4..98cb936 100644 --- a/src/coston/userInterfaces/data/AgentSettings.sol +++ b/src/flare/data/AgentSettings.sol @@ -1,60 +1,48 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; - +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AgentSettings { struct Data { // The token used as vault collateral. Must be one of the tokens obtained by `getCollateralTypes()`, // with class VAULT. IERC20 vaultCollateralToken; - // The suffix to pool token name and symbol that identifies new vault's collateral pool token. // Must be unique within an asset manager. string poolTokenSuffix; - // Minting fee. Normally charged to minters for publicly available agents, but must be set // also for self-minting agents to pay part of it to collateral pool. // Fee is paid in underlying currency along with backing assets. uint256 feeBIPS; - // Share of the minting fee that goes to the pool as percentage of the minting fee. // This share of fee is minted as f-assets and belongs to the pool. uint256 poolFeeShareBIPS; - // Collateral ratio at which we calculate locked collateral and collateral available for minting. // Agent may set own value for minting collateral ratio on creation. // The value must always be greater than system minimum collateral ratio for vault collateral. // Warning: having this value near global min collateral ratio can quickly lead to liquidation for public // agents, so it is advisable to set it significantly higher. uint256 mintingVaultCollateralRatioBIPS; - // Collateral ratio at which we calculate locked collateral and collateral available for minting. // Agent may set own value for minting collateral ratio on creation. // The value must always be greater than system minimum collateral ratio for pool collateral. // Warning: having this value near global min collateral ratio can quickly lead to liquidation for public // agents, so it is advisable to set it significantly higher. uint256 mintingPoolCollateralRatioBIPS; - // The factor set by the agent to multiply the price at which agent buys f-assets from pool // token holders on self-close exit (when requested or the redeemed amount is less than 1 lot). uint256 buyFAssetByAgentFactorBIPS; - // The minimum collateral ratio above which a staker can exit the pool // (this is CR that must be left after exit). // Must be higher than system minimum collateral ratio for pool collateral. uint256 poolExitCollateralRatioBIPS; - - // The CR below which it is possible to enter the pool at discounted rate (to prevent liquidation). - // Must be higher than system minimum collateral ratio for pool collateral. - uint256 poolTopupCollateralRatioBIPS; - - // The discount to pool token price when entering and pool CR is below pool topup CR. - uint256 poolTopupTokenPriceFactorBIPS; - - // Agent's handshake type - minting or redeeming can be rejected. - // 0 - no verification, 1 - manual verification, ... - uint256 handshakeType; + // The redemption fee share paid to the pool (as FAssets). + // In redemption dominated situations (when agent requests return from core vault to earn + // from redemption fees), pool can get some share to make it sustainable for pool users. + // NOTE: the pool fee share is locked at the redemption request time, but is charged at the redemption + // confirmation time. If agent uses all the redemption fee for transaction fees, this could make the + // agent's free underlying balance negative. + uint256 redemptionPoolFeeShareBIPS; } } diff --git a/src/coston2/userInterfaces/data/AssetManagerSettings.sol b/src/flare/data/AssetManagerSettings.sol similarity index 89% rename from src/coston2/userInterfaces/data/AssetManagerSettings.sol rename to src/flare/data/AssetManagerSettings.sol index 7832317..831efbe 100644 --- a/src/coston2/userInterfaces/data/AssetManagerSettings.sol +++ b/src/flare/data/AssetManagerSettings.sol @@ -16,17 +16,17 @@ library AssetManagerSettings { address fAsset; // Factory for creating new agent vaults. - // Type: IAgentVaultFactory + // Type: IIAgentVaultFactory // timelocked address agentVaultFactory; // Factory for creating new agent collateral pools. - // Type: ICollateralPoolFactory + // Type: IICollateralPoolFactory // timelocked address collateralPoolFactory; // Factory for creating new agent collateral pool tokens. - // Type: ICollateralPoolTokenFactory + // Type: IICollateralPoolTokenFactory // timelocked address collateralPoolTokenFactory; @@ -39,7 +39,7 @@ library AssetManagerSettings { // This can be `address(0)`, in which case no whitelist checks are done. // Type: IWhitelist // timelocked - address whitelist; + address __whitelist; // only storage placeholder // If set, the owner address registry contains a list of allowed agent owner's // management addresses and mappings from management to work address. @@ -52,8 +52,7 @@ library AssetManagerSettings { // changed via address updater address fdcVerification; - // The address where burned NAt is sent. - // (E.g. collateral reservation fee is burned on successful minting.) + // The address where burned NAT is sent. // immutable address payable burnAddress; @@ -107,12 +106,12 @@ library AssetManagerSettings { uint64 lotSizeAMG; // The percentage of minted f-assets that the agent must hold in his underlying address. - uint16 minUnderlyingBackingBIPS; + uint16 __minUnderlyingBackingBIPS; // only storage placeholder // for some chains (e.g. Ethereum) we require that agent proves that underlying address is an EOA address // this must be done by presenting a payment proof from that address // immutable - bool requireEOAAddressProof; + bool __requireEOAAddressProof; // only storage placeholder // Maximum minted amount of the f-asset. // rate-limited @@ -149,7 +148,7 @@ library AssetManagerSettings { // This is the part of redemption factor paid from agent's pool collateral. // rate-limited - uint32 redemptionDefaultFactorPoolBIPS; + uint32 __redemptionDefaultFactorPoolBIPS; // only storage placeholder // If the agent or redeemer becomes unresponsive, we still need payment or non-payment confirmations // to be presented eventually to properly track agent's underlying balance. @@ -189,7 +188,7 @@ library AssetManagerSettings { // Agent can remain in CCB for this much time, after that liquidation starts automatically. // rate-limited - uint64 ccbTimeSeconds; + uint64 __ccbTimeSeconds; // only storage placeholder // Amount of seconds (typically 1 day) that the payment/non-payment proofs must be available. // This setting is used in `unstickMinting` and `finishRedemptionWithoutPayment` to prove that the time when @@ -204,23 +203,22 @@ library AssetManagerSettings { // Ratio at which the agents can buy back their collateral when f-asset is terminated. // Typically a bit more than 1 to incentivize agents to buy f-assets and self-close instead. // immutable - uint64 buybackCollateralFactorBIPS; + uint64 __buybackCollateralFactorBIPS; // only storage placeholder // Minimum time that has to pass between underlying withdrawal announcement and the confirmation. // Any value is ok, but higher values give more security against multiple announcement attack by a miner. // Shouldn't be much bigger than Flare data connector response time, so that payments can be confirmed without // extra wait. Should be smaller than confirmationByOthersAfterSeconds (e.g. less than 1 hour). // rate-limited - uint64 announcedUnderlyingConfirmationMinSeconds; + uint64 __announcedUnderlyingConfirmationMinSeconds; // Minimum time from the moment token is deprecated to when it becomes invalid and agents still using // it as vault collateral get liquidated. // timelocked uint64 tokenInvalidationTimeMinSeconds; - // On some rare occasions (stuck minting, locked fassets after termination), the agent has to unlock - // collateral. For this, part of collateral corresponding to FTSO asset value is burned and the rest - // is released. + // On some rare occasions (stuck minting), the agent has to unlock collateral. + // For this, part of collateral corresponding to FTSO asset value is burned and the rest is released. // However, we cannot burn typical vault collateral (stablecoins), so the agent must buy them for NAT // at FTSO price multiplied with this factor (should be a bit above 1) and then we burn the NATs. // timelocked @@ -239,10 +237,10 @@ library AssetManagerSettings { // rate-limited uint64 agentMintingCRChangeTimelockSeconds; - // Amount of seconds that have to pass between agent-set settings for pool exit and topup - // (exit CR, topup CR, topup bonus) change announcement and execution. + // Amount of seconds that have to pass between agent-set settings for pool exit collateral ratio + // change announcement and execution. // rate-limited - uint64 poolExitAndTopupChangeTimelockSeconds; + uint64 poolExitCRChangeTimelockSeconds; // Amount of seconds that an agent is allowed to execute an update once it is allowed. // rate-limited @@ -283,31 +281,31 @@ library AssetManagerSettings { // The amount of time after which the collateral reservation can be cancelled if the // handshake is not completed. // rate-limited - uint64 cancelCollateralReservationAfterSeconds; + uint64 __cancelCollateralReservationAfterSeconds; // only storage placeholder // The amount of collateral reservation fee returned to the minter in case of rejection or cancellation. // Expressed in BIPS, e.g. 9500 for factor of 0.95, max 10000 for factor of 1.0. // rate-limited - uint16 rejectOrCancelCollateralReservationReturnFactorBIPS; + uint16 __rejectOrCancelCollateralReservationReturnFactorBIPS; // only storage placeholder // Time window inside which the agent can reject the redemption request. // rate-limited - uint64 rejectRedemptionRequestWindowSeconds; + uint64 __rejectRedemptionRequestWindowSeconds; // only storage placeholder // Time window inside which the agent can take over the redemption request from another agent // that has rejected it. // rate-limited - uint64 takeOverRedemptionRequestWindowSeconds; + uint64 __takeOverRedemptionRequestWindowSeconds; // only storage placeholder // On redemption rejection, without take over, redeemer is compensated with // redemption value recalculated in flare/sgb times redemption failure factor. // Expressed in BIPS, e.g. 12000 for factor of 1.2. // This is the part of factor paid from agent's vault collateral. // rate-limited - uint32 rejectedRedemptionDefaultFactorVaultCollateralBIPS; + uint32 __rejectedRedemptionDefaultFactorVaultCollateralBIPS; // only storage placeholder // This is the part of rejected redemption factor paid from agent's pool collateral. // rate-limited - uint32 rejectedRedemptionDefaultFactorPoolBIPS; + uint32 __rejectedRedemptionDefaultFactorPoolBIPS; // only storage placeholder } } diff --git a/src/songbird/userInterfaces/data/AvailableAgentInfo.sol b/src/flare/data/AvailableAgentInfo.sol similarity index 95% rename from src/songbird/userInterfaces/data/AvailableAgentInfo.sol rename to src/flare/data/AvailableAgentInfo.sol index 0d90a67..29510f1 100644 --- a/src/songbird/userInterfaces/data/AvailableAgentInfo.sol +++ b/src/flare/data/AvailableAgentInfo.sol @@ -1,31 +1,24 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./AgentInfo.sol"; - +import {AgentInfo} from "./AgentInfo.sol"; library AvailableAgentInfo { struct Data { // Agent vault address. address agentVault; - // The management address of the agent vault's owner. address ownerManagementAddress; - // Agent's minting fee in BIPS. uint256 feeBIPS; - // Minimum agent vault collateral ratio needed for minting. uint256 mintingVaultCollateralRatioBIPS; - // Minimum pool collateral ratio needed for minting. uint256 mintingPoolCollateralRatioBIPS; - // The number of lots that can be minted by this agent. // Note: the value is only informative since it can can change at any time // due to price changes, reservation, minting, redemption, or even lot size change. uint256 freeCollateralLots; - // The agent status, as for getAgentInfo(). AgentInfo.Status status; } diff --git a/src/coston2/userInterfaces/data/CollateralReservationInfo.sol b/src/flare/data/CollateralReservationInfo.sol similarity index 75% rename from src/coston2/userInterfaces/data/CollateralReservationInfo.sol rename to src/flare/data/CollateralReservationInfo.sol index 348bdba..65c3595 100644 --- a/src/coston2/userInterfaces/data/CollateralReservationInfo.sol +++ b/src/flare/data/CollateralReservationInfo.sol @@ -3,6 +3,13 @@ pragma solidity >=0.7.6 <0.9; library CollateralReservationInfo { + enum Status { + ACTIVE, // the minting process hasn't finished yet + SUCCESSFUL, // the payment has been confirmed and the FAssets minted + DEFAULTED, // the payment has defaulted and the agent received the collateral reservation fee + EXPIRED // the confirmation time has expired and the agent called unstickMinting + } + struct Data { // The id used for executing or defaulting the minting. uint64 collateralReservationId; @@ -30,10 +37,10 @@ library CollateralReservationInfo { // Part of the fee is goes to the pool and the rest to the agent vault as WNAT. uint128 reservationFeeNatWei; - // Proportion of the mintingFeeUBA and reservationFeeNatWei that belogs to the collateral pool. + // Proportion of the mintingFeeUBA and reservationFeeNatWei that belongs to the collateral pool. uint16 poolFeeShareBIPS; - // The underlying block (approximate - as known by the asset manager) when the reservation occured. + // The underlying block (approximate - as known by the asset manager) when the reservation occurred. uint64 firstUnderlyingBlock; // The last underlying block and timestamp for redemption payment. Redemption is defaulted if @@ -45,14 +52,10 @@ library CollateralReservationInfo { // (Only minter, agent or executor may execute the minting.) address executor; - // The fee in NAT that the executor receives if they successfuly execute the minting. + // The fee in NAT that the executor receives if they successfully execute the minting. uint256 executorFeeNatWei; - // If non-zero, the agent has started the handshake process. - uint64 handshakeStartTimestamp; - - // Merkle root of the list of addresses from which the minter is going to deposit the underlying assets - // (only needed when handshake is enabled for the agent). - bytes32 sourceAddressesRoot; + // If the minting process has finished, indication of success/default. Otherwise ACTIVE. + CollateralReservationInfo.Status status; } } diff --git a/src/coston/userInterfaces/data/CollateralType.sol b/src/flare/data/CollateralType.sol similarity index 85% rename from src/coston/userInterfaces/data/CollateralType.sol rename to src/flare/data/CollateralType.sol index 2220965..711b4a1 100644 --- a/src/coston/userInterfaces/data/CollateralType.sol +++ b/src/flare/data/CollateralType.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library CollateralType { @@ -45,11 +45,6 @@ library CollateralType { // Minimum collateral ratio for healthy agents. uint256 minCollateralRatioBIPS; - // Minimum collateral ratio for agent in CCB (Collateral call band). - // If the agent's collateral ratio is less than this, skip the CCB and go straight to liquidation. - // A bit smaller than minCollateralRatioBIPS. - uint256 ccbMinCollateralRatioBIPS; - // Minimum collateral ratio required to get agent out of liquidation. // Will always be greater than minCollateralRatioBIPS. uint256 safetyMinCollateralRatioBIPS; diff --git a/src/coston/userInterfaces/data/RedemptionRequestInfo.sol b/src/flare/data/RedemptionRequestInfo.sol similarity index 77% rename from src/coston/userInterfaces/data/RedemptionRequestInfo.sol rename to src/flare/data/RedemptionRequestInfo.sol index 83793a3..e850ec1 100644 --- a/src/coston/userInterfaces/data/RedemptionRequestInfo.sol +++ b/src/flare/data/RedemptionRequestInfo.sol @@ -4,8 +4,13 @@ pragma solidity >=0.7.6 <0.9; library RedemptionRequestInfo { enum Status { - ACTIVE, - DEFAULTED + ACTIVE, // waiting for confirmation/default + DEFAULTED_UNCONFIRMED, // default called, failed or late payment can still be confirmed + // final statuses - there can be no valid payment for this redemption anymore + SUCCESSFUL, // successful payment confirmed + DEFAULTED_FAILED, // payment failed (default was paid) + BLOCKED, // payment blocked + REJECTED // redemption request rejected due to invalid redeemer's address } struct Data { @@ -39,7 +44,7 @@ library RedemptionRequestInfo { // and goes to the collateral pool. uint16 poolFeeShareBIPS; - // The underlying block (approximate - as known by the asset manager) when the request occured. + // The underlying block (approximate - as known by the asset manager) when the request occurred. uint64 firstUnderlyingBlock; // The last underlying block and timestamp for redemption payment. Redemption is defaulted if @@ -47,7 +52,7 @@ library RedemptionRequestInfo { uint64 lastUnderlyingBlock; uint64 lastUnderlyingTimestamp; - // The native (Flare/Songbird) chain timstamp when the request occured. + // The native (Flare/Songbird) chain timestamp when the request occurred. uint64 timestamp; // True if redemption was created by a selfCloseExit on the collateral pool. @@ -60,13 +65,7 @@ library RedemptionRequestInfo { // (Only redeemer, agent or executor may execute the default.) address executor; - // The fee in NAT that the executor receives if they successfuly call default. + // The fee in NAT that the executor receives if they successfully call default. uint256 executorFeeNatWei; - - // If non-zero, request was rejected in handshake process. - uint64 rejectionTimestamp; - - // If non-zero, handshake-rejected request was taken over by another agent. - uint64 takeOverTimestamp; } } diff --git a/src/songbird/userInterfaces/data/RedemptionTicketInfo.sol b/src/flare/data/RedemptionTicketInfo.sol similarity index 100% rename from src/songbird/userInterfaces/data/RedemptionTicketInfo.sol rename to src/flare/data/RedemptionTicketInfo.sol diff --git a/src/flare/diamond/interfaces/IDiamondLoupe.sol b/src/flare/diamond/interfaces/IDiamondLoupe.sol new file mode 100644 index 0000000..c3b2570 --- /dev/null +++ b/src/flare/diamond/interfaces/IDiamondLoupe.sol @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +/******************************************************************************\ +* Author: Nick Mudge (https://twitter.com/mudgen) +* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 +/******************************************************************************/ + +// A loupe is a small magnifying glass used to look at diamonds. +// These functions look at diamonds +interface IDiamondLoupe { + /// These functions are expected to be called frequently + /// by tools. + + struct Facet { + address facetAddress; + bytes4[] functionSelectors; + } + + /// @notice Gets all facet addresses and their four byte function selectors. + /// @return facets_ Facet + function facets() external view returns (Facet[] memory facets_); + + /// @notice Gets all the function selectors supported by a specific facet. + /// @param _facet The facet address. + /// @return facetFunctionSelectors_ + function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); + + /// @notice Get all the facet addresses used by a diamond. + /// @return facetAddresses_ + function facetAddresses() external view returns (address[] memory facetAddresses_); + + /// @notice Gets the facet that supports the given selector. + /// @dev If facet is not found return address(0). + /// @param _functionSelector The function selector. + /// @return facetAddress_ The facet address. + function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); +} diff --git a/src/flare/fdc/interface/ITypeTemplate.sol b/src/flare/fdc/interfaces/ITypeTemplate.sol similarity index 100% rename from src/flare/fdc/interface/ITypeTemplate.sol rename to src/flare/fdc/interfaces/ITypeTemplate.sol diff --git a/src/flare/fdc/interface/ITypeTemplateVerification.sol b/src/flare/fdc/interfaces/ITypeTemplateVerification.sol similarity index 100% rename from src/flare/fdc/interface/ITypeTemplateVerification.sol rename to src/flare/fdc/interfaces/ITypeTemplateVerification.sol diff --git a/src/flare/fscV1/interface/IIFastUpdaterView.sol b/src/flare/fscV1/interfaces/IIFastUpdaterView.sol similarity index 100% rename from src/flare/fscV1/interface/IIFastUpdaterView.sol rename to src/flare/fscV1/interfaces/IIFastUpdaterView.sol diff --git a/src/flare/fscV1/interface/IIFtsoManagerProxy.sol b/src/flare/fscV1/interfaces/IIFtsoManagerProxy.sol similarity index 100% rename from src/flare/fscV1/interface/IIFtsoManagerProxy.sol rename to src/flare/fscV1/interfaces/IIFtsoManagerProxy.sol diff --git a/src/songbird/ftso/interface/IIFtso.sol b/src/flare/ftso/interfaces/IIFtso.sol similarity index 98% rename from src/songbird/ftso/interface/IIFtso.sol rename to src/flare/ftso/interfaces/IIFtso.sol index e2beb8f..d93d935 100644 --- a/src/songbird/ftso/interface/IIFtso.sol +++ b/src/flare/ftso/interfaces/IIFtso.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "../../genesis/interface/IFtsoGenesis.sol"; +import "../../genesis/interfaces/IFtsoGenesis.sol"; import "../../IFtso.sol"; -import "../../token/interface/IIVPToken.sol"; +import "../../token/interfaces/IIVPToken.sol"; interface IIFtso is IFtso, IFtsoGenesis { diff --git a/src/flare/ftso/interface/IIFtsoFeedPublisher.sol b/src/flare/ftso/interfaces/IIFtsoFeedPublisher.sol similarity index 100% rename from src/flare/ftso/interface/IIFtsoFeedPublisher.sol rename to src/flare/ftso/interfaces/IIFtsoFeedPublisher.sol diff --git a/src/flare/ftso/interfaces/IIFtsoManager.sol b/src/flare/ftso/interfaces/IIFtsoManager.sol new file mode 100644 index 0000000..b11605f --- /dev/null +++ b/src/flare/ftso/interfaces/IIFtsoManager.sol @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../ftso/interfaces/IIFtso.sol"; +import "../../IFtsoManager.sol"; +import "../../genesis/interfaces/IFlareDaemonize.sol"; +import "../../token/interfaces/IIVPToken.sol"; + + +interface IIFtsoManager is IFtsoManager, IFlareDaemonize { + + struct RewardEpochData { + uint256 votepowerBlock; + uint256 startBlock; + uint256 startTimestamp; + } + + event ClosingExpiredRewardEpochFailed(uint256 rewardEpoch); + event CleanupBlockNumberManagerFailedForBlock(uint256 blockNumber); + event UpdatingActiveValidatorsTriggerFailed(uint256 rewardEpoch); + event FtsoDeactivationFailed(IIFtso ftso); + event ChillingNonrevealingDataProvidersFailed(); + + function activate() external; + + function setInitialRewardData( + uint256 _nextRewardEpochToExpire, + uint256 _rewardEpochsLength, + uint256 _currentRewardEpochEnds + ) external; + + function setGovernanceParameters( + uint256 _updateTs, + uint256 _maxVotePowerNatThresholdFraction, + uint256 _maxVotePowerAssetThresholdFraction, + uint256 _lowAssetUSDThreshold, + uint256 _highAssetUSDThreshold, + uint256 _highAssetTurnoutThresholdBIPS, + uint256 _lowNatTurnoutThresholdBIPS, + uint256 _elasticBandRewardBIPS, + uint256 _rewardExpiryOffsetSeconds, + address[] memory _trustedAddresses + ) external; + + + function addFtso(IIFtso _ftso) external; + + function addFtsosBulk(IIFtso[] memory _ftsos) external; + + function removeFtso(IIFtso _ftso) external; + + function replaceFtso( + IIFtso _ftsoToAdd, + bool copyCurrentPrice, + bool copyAssetOrAssetFtsos + ) external; + + function replaceFtsosBulk( + IIFtso[] memory _ftsosToAdd, + bool copyCurrentPrice, + bool copyAssetOrAssetFtsos + ) external; + + function setFtsoAsset(IIFtso _ftso, IIVPToken _asset) external; + + function setFtsoAssetFtsos(IIFtso _ftso, IIFtso[] memory _assetFtsos) external; + + function setFallbackMode(bool _fallbackMode) external; + + function setFtsoFallbackMode(IIFtso _ftso, bool _fallbackMode) external; + + function notInitializedFtsos(IIFtso) external view returns (bool); + + function getRewardEpochData(uint256 _rewardEpochId) external view returns (RewardEpochData memory); + + function currentRewardEpochEnds() external view returns (uint256); + + function getLastUnprocessedPriceEpochData() external view + returns( + uint256 _lastUnprocessedPriceEpoch, + uint256 _lastUnprocessedPriceEpochRevealEnds, + bool _lastUnprocessedPriceEpochInitialized + ); + + function rewardEpochsStartTs() external view returns(uint256); + + function rewardEpochDurationSeconds() external view returns(uint256); + + function rewardEpochs(uint256 _rewardEpochId) external view + returns ( + uint256 _votepowerBlock, + uint256 _startBlock, + uint256 _startTimestamp + ); + + function getRewardExpiryOffsetSeconds() external view returns (uint256); + + /** + * @notice Returns elastic band width in PPM (parts-per-million) for given ftso + */ + function getElasticBandWidthPPMFtso(IIFtso _ftso) external view returns (uint256); +} diff --git a/src/flare/ftso/interfaces/IIFtsoManagerV1.sol b/src/flare/ftso/interfaces/IIFtsoManagerV1.sol new file mode 100644 index 0000000..44cf4cc --- /dev/null +++ b/src/flare/ftso/interfaces/IIFtsoManagerV1.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +// interface for the first version of ftso manger (V1 = oldest version) - last version is always without any Vx +interface IIFtsoManagerV1 { + function rewardEpochsStartTs() external view returns(uint256); + function rewardEpochDurationSeconds() external view returns(uint256); + + function getCurrentRewardEpoch() external view returns(uint256); + + function rewardEpochs(uint256 _rewardEpochId) external view returns ( + uint256 _votepowerBlock, + uint256 _startBlock, + uint256 _startTimestamp + ); + + function getPriceEpochConfiguration() external view + returns ( + uint256 _firstPriceEpochStartTs, + uint256 _priceEpochDurationSeconds, + uint256 _revealEpochDurationSeconds + ); +} diff --git a/src/flare/genesis/interface/IFlareDaemonize.sol b/src/flare/genesis/interfaces/IFlareDaemonize.sol similarity index 100% rename from src/flare/genesis/interface/IFlareDaemonize.sol rename to src/flare/genesis/interfaces/IFlareDaemonize.sol diff --git a/src/flare/genesis/interface/IFtsoGenesis.sol b/src/flare/genesis/interfaces/IFtsoGenesis.sol similarity index 100% rename from src/flare/genesis/interface/IFtsoGenesis.sol rename to src/flare/genesis/interfaces/IFtsoGenesis.sol diff --git a/src/flare/genesis/interface/IFtsoManagerGenesis.sol b/src/flare/genesis/interfaces/IFtsoManagerGenesis.sol similarity index 100% rename from src/flare/genesis/interface/IFtsoManagerGenesis.sol rename to src/flare/genesis/interfaces/IFtsoManagerGenesis.sol diff --git a/src/flare/genesis/interface/IFtsoRegistryGenesis.sol b/src/flare/genesis/interfaces/IFtsoRegistryGenesis.sol similarity index 100% rename from src/flare/genesis/interface/IFtsoRegistryGenesis.sol rename to src/flare/genesis/interfaces/IFtsoRegistryGenesis.sol diff --git a/src/flare/genesis/interfaces/IIPriceSubmitter.sol b/src/flare/genesis/interfaces/IIPriceSubmitter.sol new file mode 100644 index 0000000..b69beab --- /dev/null +++ b/src/flare/genesis/interfaces/IIPriceSubmitter.sol @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IPriceSubmitter.sol"; +interface IIPriceSubmitter is IPriceSubmitter { + + /** + * Set trusted addresses that are always allowed to submit and reveal. + * Only ftso manager can call this method. + */ + function setTrustedAddresses(address[] memory _trustedAddresses) external; + + /** + * Called from whitelister when new voter has been whitelisted. + */ + function voterWhitelisted(address _voter, uint256 _ftsoIndex) external; + + /** + * Called from whitelister when one or more voters have been removed. + */ + function votersRemovedFromWhitelist(address[] memory _voters, uint256 _ftsoIndex) external; + + /** + * Returns a list of trusted addresses that are always allowed to submit and reveal. + */ + function getTrustedAddresses() external view returns (address[] memory); +} diff --git a/src/flare/genesis/interfaces/IInflationGenesis.sol b/src/flare/genesis/interfaces/IInflationGenesis.sol new file mode 100644 index 0000000..eb0e98c --- /dev/null +++ b/src/flare/genesis/interfaces/IInflationGenesis.sol @@ -0,0 +1,15 @@ + +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IInflationGenesis { + /** + * @notice Receive newly minted native tokens from the FlareDaemon. + * @dev Assume that the amount received will be >= last topup requested across all services. + * If there is not enough balance sent to cover the topup request, expect library method will revert. + * Also assume that any balance received greater than the topup request calculated + * came from self-destructor sending a balance to this contract. + */ + function receiveMinting() external payable; +} diff --git a/src/coston2/governance/interface/IIGovernorProposer.sol b/src/flare/governance/interfaces/IIGovernorProposer.sol similarity index 58% rename from src/coston2/governance/interface/IIGovernorProposer.sol rename to src/flare/governance/interfaces/IIGovernorProposer.sol index adb6c4c..8e7dc87 100644 --- a/src/coston2/governance/interface/IIGovernorProposer.sol +++ b/src/flare/governance/interfaces/IIGovernorProposer.sol @@ -1,12 +1,13 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; interface IIGovernorProposer { /** - * Determines if account is eligible to submit a proposal. - * @param _account Address of the queried account. - * @return True if account is eligible for proposal submission, and false otherwise. + * @notice Determines if account is eligible to submit a proposal + * @param _account Address of the queried account + * @return True if account is eligible for proposal submission, and false otherwise */ function isProposer(address _account) external view returns (bool); diff --git a/src/coston2/governance/interface/IIPollingFoundation.sol b/src/flare/governance/interfaces/IIPollingFoundation.sol similarity index 53% rename from src/coston2/governance/interface/IIPollingFoundation.sol rename to src/flare/governance/interfaces/IIPollingFoundation.sol index 9fe2fd4..59f9854 100644 --- a/src/coston2/governance/interface/IIPollingFoundation.sol +++ b/src/flare/governance/interfaces/IIPollingFoundation.sol @@ -1,5 +1,6 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; import "../../IGovernor.sol"; import "./IIGovernorProposer.sol"; @@ -8,7 +9,7 @@ interface IIPollingFoundation is IGovernor, IIGovernorProposer { struct GovernorSettingsWithoutExecParams { bool accept; - uint256 votingStartTs; + uint256 votingDelaySeconds; uint256 votingPeriodSeconds; uint256 vpBlockPeriodSeconds; uint256 thresholdConditionBIPS; @@ -16,11 +17,11 @@ interface IIPollingFoundation is IGovernor, IIGovernorProposer { } /** - * Creates a new proposal without execution parameters. - * @param _description String description of the proposal. - * @param _settings Settings of the poposal. - * @return Proposal id (unique identifier obtained by hashing proposal data). - * Emits a ProposalCreated event. + * @notice Creates a new proposal without execution parameters + * @param _description String description of the proposal + * @param _settings Settings of the poposal + * @return Proposal id (unique identifier obtained by hashing proposal data) + * @notice Emits a ProposalCreated event */ function propose( string memory _description, @@ -28,14 +29,14 @@ interface IIPollingFoundation is IGovernor, IIGovernorProposer { ) external returns (uint256); /** - * Creates a new proposal with execution parameters. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * @param _description String description of the proposal. - * @param _settings Settings of the poposal. - * @return Proposal id (unique identifier obtained by hashing proposal data). - * Emits a ProposalCreated event. + * @notice Creates a new proposal with execution parameters + * @param _targets Array of target addresses on which the calls are to be invoked + * @param _values Array of values with which the calls are to be invoked + * @param _calldatas Array of call data to be invoked + * @param _description String description of the proposal + * @param _settings Settings of the poposal + * @return Proposal id (unique identifier obtained by hashing proposal data) + * @notice Emits a ProposalCreated event */ function propose( address[] memory _targets, diff --git a/src/flare/governance/interface/IIPollingManagementGroup.sol b/src/flare/governance/interfaces/IIPollingManagementGroup.sol similarity index 100% rename from src/flare/governance/interface/IIPollingManagementGroup.sol rename to src/flare/governance/interfaces/IIPollingManagementGroup.sol diff --git a/src/flare/inflation/interfaces/IIInflationAllocation.sol b/src/flare/inflation/interfaces/IIInflationAllocation.sol new file mode 100644 index 0000000..da5305a --- /dev/null +++ b/src/flare/inflation/interfaces/IIInflationAllocation.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIInflationReceiver.sol"; + +struct SharingPercentage { + IIInflationReceiver inflationReceiver; + uint256 percentBips; +} + +interface IIInflationAllocation { + /** + * Return the time slot inflation rate in bips. + */ + function getTimeSlotPercentageBips() external returns(uint256); + + /** + * Return the shared percentage per inflation receiver. + * @dev Assumption is that implementer edited that percents sum to 100 pct and + * that receiver addresses are valid. + */ + function getSharingPercentages() external returns(SharingPercentage[] memory); +} diff --git a/src/flare/inflation/interfaces/IIInflationReceiver.sol b/src/flare/inflation/interfaces/IIInflationReceiver.sol new file mode 100644 index 0000000..43a9499 --- /dev/null +++ b/src/flare/inflation/interfaces/IIInflationReceiver.sol @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +/** + * Internal interface for contracts that can receive inflation. + */ +interface IIInflationReceiver { + /** + * Notify the receiver that it is entitled to receive a new inflation amount. + * @param _toAuthorizeWei The amount of inflation that can be awarded in the coming day, in wei. + */ + function setDailyAuthorizedInflation(uint256 _toAuthorizeWei) external; + + /** + * Receive native tokens from inflation. + */ + function receiveInflation() external payable; + + /** + * Returns the address of the `Inflation` contract. + */ + function getInflationAddress() external returns(address); + + /** + * Returns the contract's expected balance + * (actual balance may be higher due to self-destruct funds). + * @return Expected native token balance. + */ + function getExpectedBalance() external view returns(uint256); + + /** + * Implement this function to allow updating inflation receiver contracts through `AddressUpdater`. + * @return Contract name. + */ + function getContractName() external view returns (string memory); +} diff --git a/src/flare/inflation/interfaces/IIInflationReceiverV1.sol b/src/flare/inflation/interfaces/IIInflationReceiverV1.sol new file mode 100644 index 0000000..a75342a --- /dev/null +++ b/src/flare/inflation/interfaces/IIInflationReceiverV1.sol @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIInflationReceiverV1 { + /** + * Notify the receiver that it is entitled to receive `_toAuthorizeWei` inflation amount. + * @param _toAuthorizeWei the amount of inflation that can be awarded in the coming day + */ + function setDailyAuthorizedInflation(uint256 _toAuthorizeWei) external; + + /** + * Receive native tokens from inflation. + */ + function receiveInflation() external payable; + + /** + * Inflation receivers have a reference to the Inflation contract. + */ + function getInflationAddress() external returns(address); + + /** + * Implement this function for updating inflation receiver contracts through AddressUpdater. + */ + function getContractName() external view returns (string memory); +} diff --git a/src/flare/inflation/interfaces/IIInflationV1.sol b/src/flare/inflation/interfaces/IIInflationV1.sol new file mode 100644 index 0000000..5e91360 --- /dev/null +++ b/src/flare/inflation/interfaces/IIInflationV1.sol @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIInflationReceiver.sol"; + + +// interface for the first version of inflation (V1 = oldest version) - last version is always without any Vx +interface IIInflationV1 { + + struct RewardServiceState { + IIInflationReceiver inflationReceiver; // The target rewarding contract + uint256 authorizedInflationWei; // Total authorized inflation for this reward service + uint256 lastDailyAuthorizedInflationWei; // Last daily authorized inflation amount + uint256 inflationTopupRequestedWei; // Total inflation topup requested to be minted + uint256 inflationTopupReceivedWei; // Total inflation minting received + uint256 inflationTopupWithdrawnWei; // Total inflation minting sent to rewarding service contract + } + + struct RewardServicesState { + // Collection of annums + RewardServiceState[] rewardServices; + // Balances + uint256 totalAuthorizedInflationWei; + uint256 totalInflationTopupRequestedWei; + uint256 totalInflationTopupReceivedWei; + uint256 totalInflationTopupWithdrawnWei; + } + + struct InflationAnnumState { + uint256 recognizedInflationWei; + uint256 startTimeStamp; + uint256 endTimeStamp; + RewardServicesState rewardServices; + } + + + function lastAuthorizationTs() external returns(uint256); + function rewardEpochStartedTs() external returns(uint256); + function getAnnum(uint256 _index) external view returns(InflationAnnumState memory); + +} diff --git a/src/flare/inflation/interfaces/IIPreInflationCalculation.sol b/src/flare/inflation/interfaces/IIPreInflationCalculation.sol new file mode 100644 index 0000000..29e5043 --- /dev/null +++ b/src/flare/inflation/interfaces/IIPreInflationCalculation.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIPreInflationCalculation { + /** + * @notice A method that is triggered before new inflation is calculated + */ + function trigger() external; +} diff --git a/src/flare/inflation/interfaces/IISupply.sol b/src/flare/inflation/interfaces/IISupply.sol new file mode 100644 index 0000000..0090891 --- /dev/null +++ b/src/flare/inflation/interfaces/IISupply.sol @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IISupply { + + /** + * @notice Updates circulating supply + * @dev Also updates the burn address amount + */ + function updateCirculatingSupply() external; + + /** + * @notice Updates authorized inflation and circulating supply - emits event if error + * @param _inflationAuthorizedWei Authorized inflation + * @dev Also updates the burn address amount + */ + function updateAuthorizedInflationAndCirculatingSupply(uint256 _inflationAuthorizedWei) external; + + /** + * @notice Get approximate circulating supply for given block number from cache - only past block + * @param _blockNumber Block number + * @return _circulatingSupplyWei Return approximate circulating supply for last known block <= _blockNumber + */ + function getCirculatingSupplyAtCached(uint256 _blockNumber) external returns(uint256 _circulatingSupplyWei); + + /** + * @notice Get approximate circulating supply for given block number + * @param _blockNumber Block number + * @return _circulatingSupplyWei Return approximate circulating supply for last known block <= _blockNumber + */ + function getCirculatingSupplyAt(uint256 _blockNumber) external view returns(uint256 _circulatingSupplyWei); + + /** + * @notice Get total inflatable balance (initial genesis amount + total authorized inflation) + * @return _inflatableBalanceWei Return inflatable balance + */ + function getInflatableBalance() external view returns(uint256 _inflatableBalanceWei); +} diff --git a/src/flare/mockXAsset/interfaces/ICollateralizable.sol b/src/flare/mockXAsset/interfaces/ICollateralizable.sol new file mode 100644 index 0000000..3ed5a99 --- /dev/null +++ b/src/flare/mockXAsset/interfaces/ICollateralizable.sol @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface ICollateralizable { + + enum FeeHandling { + DEPOSIT_TO_POSITION, + SEND_TO_AGENT + } + + /// addRewardToAgentPosition function will be triggered by the reward contract per reward allocation. + /// Function will claim rewards for last epoch, and allocate to relevant agents + /// Flow: + /// - check which FTSO won. + /// - claim relevant reward from reward contract. + /// - iterate list of current delegators to this FTSO + /// - per the list, check weight agent delegated to this FTSO + /// - add native token reward to this Agent position. + function addRewardToAgentPosition(uint256 epochID) external returns (bool succeess); + + function deposit( + uint256 amount, + uint256 freshMint, // amount to add to fresh minting pool + uint256 agentPosition, // amount to add to position pool + uint256 freshMintMinRatio, // if position pool collateral ratio < min, no new mints + address natAddress, + FeeHandling handling + ) external; + + /// note: must send collateral reservation fee as msg.value. or approve to this contract + function mintRequest ( // AKA collateral reservation + uint256 mintAmountTwei, + address mintDestination, + bytes32 underlyingAddress + ) + external + returns ( + uint256 mintRequestId, + address[] calldata agents, // agent list + uint256[] calldata assetAmounts, // amount to send to agent in underlying chain + bytes32[] calldata assetAddress // underlying chain address + ); + + function proveMintPayment ( // AKA mint + uint256 mintRequestId, + bytes32 minterSourceAddress, //do we need this? + bytes32 agentAssetAddress, + bytes32 destinationTag, + uint256 assetAmount, + bytes32[] calldata merkleProof + ) + external + returns ( + uint256 mintedAmount + ); + + function assetRedemptionRequest ( + uint256 amount, + bytes32 assetAddress // address in underlying chain[] + ) + external + returns ( + uint256 redemptionId, + address[] calldata agents, // agent list + uint256[] calldata assetAmounts // amount agent should in underlying chain + ); + + function proveRedemptionPayment ( // same as prove mint payment? + uint256 redemptionRequestId, + bytes32 agentSourceAssetAddress, //do we need this? + bytes32 redeemerAssetAddress, + bytes32 destinationTag, + uint256 assetAmount, + bytes32[] calldata merkleProof + ) + external + returns ( + uint256 redeemedAmount + ); +} diff --git a/src/flare/protocol/interface/IIClaimSetupManager.sol b/src/flare/protocol/interfaces/IIClaimSetupManager.sol similarity index 100% rename from src/flare/protocol/interface/IIClaimSetupManager.sol rename to src/flare/protocol/interfaces/IIClaimSetupManager.sol diff --git a/src/flare/protocol/interface/IICleanupBlockNumberManager.sol b/src/flare/protocol/interfaces/IICleanupBlockNumberManager.sol similarity index 100% rename from src/flare/protocol/interface/IICleanupBlockNumberManager.sol rename to src/flare/protocol/interfaces/IICleanupBlockNumberManager.sol diff --git a/src/flare/protocol/interface/IIEntityManager.sol b/src/flare/protocol/interfaces/IIEntityManager.sol similarity index 100% rename from src/flare/protocol/interface/IIEntityManager.sol rename to src/flare/protocol/interfaces/IIEntityManager.sol diff --git a/src/flare/protocol/interface/IIFlareSystemsCalculator.sol b/src/flare/protocol/interfaces/IIFlareSystemsCalculator.sol similarity index 100% rename from src/flare/protocol/interface/IIFlareSystemsCalculator.sol rename to src/flare/protocol/interfaces/IIFlareSystemsCalculator.sol diff --git a/src/flare/protocol/interface/IIFlareSystemsManager.sol b/src/flare/protocol/interfaces/IIFlareSystemsManager.sol similarity index 100% rename from src/flare/protocol/interface/IIFlareSystemsManager.sol rename to src/flare/protocol/interfaces/IIFlareSystemsManager.sol diff --git a/src/flare/protocol/interface/IINodePossessionVerifier.sol b/src/flare/protocol/interfaces/IINodePossessionVerifier.sol similarity index 100% rename from src/flare/protocol/interface/IINodePossessionVerifier.sol rename to src/flare/protocol/interfaces/IINodePossessionVerifier.sol diff --git a/src/flare/protocol/interface/IIPublicKeyVerifier.sol b/src/flare/protocol/interfaces/IIPublicKeyVerifier.sol similarity index 100% rename from src/flare/protocol/interface/IIPublicKeyVerifier.sol rename to src/flare/protocol/interfaces/IIPublicKeyVerifier.sol diff --git a/src/flare/protocol/interface/IIRelay.sol b/src/flare/protocol/interfaces/IIRelay.sol similarity index 100% rename from src/flare/protocol/interface/IIRelay.sol rename to src/flare/protocol/interfaces/IIRelay.sol diff --git a/src/flare/protocol/interface/IIRewardEpochSwitchoverTrigger.sol b/src/flare/protocol/interfaces/IIRewardEpochSwitchoverTrigger.sol similarity index 100% rename from src/flare/protocol/interface/IIRewardEpochSwitchoverTrigger.sol rename to src/flare/protocol/interfaces/IIRewardEpochSwitchoverTrigger.sol diff --git a/src/flare/protocol/interface/IIRewardManager.sol b/src/flare/protocol/interfaces/IIRewardManager.sol similarity index 100% rename from src/flare/protocol/interface/IIRewardManager.sol rename to src/flare/protocol/interfaces/IIRewardManager.sol diff --git a/src/flare/protocol/interface/IISubmission.sol b/src/flare/protocol/interfaces/IISubmission.sol similarity index 100% rename from src/flare/protocol/interface/IISubmission.sol rename to src/flare/protocol/interfaces/IISubmission.sol diff --git a/src/flare/protocol/interface/IIVoterRegistrationTrigger.sol b/src/flare/protocol/interfaces/IIVoterRegistrationTrigger.sol similarity index 100% rename from src/flare/protocol/interface/IIVoterRegistrationTrigger.sol rename to src/flare/protocol/interfaces/IIVoterRegistrationTrigger.sol diff --git a/src/flare/protocol/interface/IIVoterRegistry.sol b/src/flare/protocol/interfaces/IIVoterRegistry.sol similarity index 100% rename from src/flare/protocol/interface/IIVoterRegistry.sol rename to src/flare/protocol/interfaces/IIVoterRegistry.sol diff --git a/src/flare/rNat/interface/IIRNat.sol b/src/flare/rNat/interfaces/IIRNat.sol similarity index 100% rename from src/flare/rNat/interface/IIRNat.sol rename to src/flare/rNat/interfaces/IIRNat.sol diff --git a/src/coston2/rNat/interface/IIRNatAccount.sol b/src/flare/rNat/interfaces/IIRNatAccount.sol similarity index 98% rename from src/coston2/rNat/interface/IIRNatAccount.sol rename to src/flare/rNat/interfaces/IIRNatAccount.sol index 0a7d05e..017902d 100644 --- a/src/coston2/rNat/interface/IIRNatAccount.sol +++ b/src/flare/rNat/interfaces/IIRNatAccount.sol @@ -3,7 +3,7 @@ pragma solidity >=0.7.6 <0.9; import "../../IRNatAccount.sol"; -import "../../protocol/interface/IIClaimSetupManager.sol"; +import "../../protocol/interfaces/IIClaimSetupManager.sol"; interface IIRNatAccount is IRNatAccount { diff --git a/src/flare/staking/interfaces/IIPChainStakeMirrorVerifier.sol b/src/flare/staking/interfaces/IIPChainStakeMirrorVerifier.sol new file mode 100644 index 0000000..3833ea3 --- /dev/null +++ b/src/flare/staking/interfaces/IIPChainStakeMirrorVerifier.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../IPChainStakeMirrorVerifier.sol"; + + +/** + * Internal interface for P-chain stake mirror verifications. + */ +interface IIPChainStakeMirrorVerifier is IPChainStakeMirrorVerifier { + + /** + * Method for P-chain stake verification using `IPChainStakeMirrorVerifier.PChainStake` data and Merkle proof. + * @param _stakeData Information about P-chain stake. + * @param _merkleProof Merkle proof that should be used to prove the P-chain stake. + * @return True if stake can be verified using provided Merkle proof. + */ + function verifyStake( + IPChainStakeMirrorVerifier.PChainStake calldata _stakeData, + bytes32[] calldata _merkleProof + ) + external view returns(bool); +} diff --git a/src/flare/token/interface/IICleanable.sol b/src/flare/token/interfaces/IICleanable.sol similarity index 100% rename from src/flare/token/interface/IICleanable.sol rename to src/flare/token/interfaces/IICleanable.sol diff --git a/src/flare/token/interfaces/IICombinedNatBalance.sol b/src/flare/token/interfaces/IICombinedNatBalance.sol new file mode 100644 index 0000000..8a76dcb --- /dev/null +++ b/src/flare/token/interfaces/IICombinedNatBalance.sol @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +/** + * Internal interface for the balance part of `CombinedNat` contract. + */ +interface IICombinedNatBalance { + + /** + * Total amount of tokens at current block. + * @return The current total amount of tokens. + **/ + function totalSupply() external view returns (uint256); + + /** + * Total amount of tokens at a specific `_blockNumber`. + * @param _blockNumber The block number when the totalSupply is queried. + * @return The total amount of tokens at `_blockNumber`. + **/ + function totalSupplyAt(uint _blockNumber) external view returns(uint256); + + /** + * Queries the token balance of `_owner` at current block. + * @param _owner The address from which the balance will be retrieved. + * @return The current balance. + **/ + function balanceOf(address _owner) external view returns (uint256); + + /** + * Queries the token balance of `_owner` at a specific `_blockNumber`. + * @param _owner The address from which the balance will be retrieved. + * @param _blockNumber The block number when the balance is queried. + * @return The balance at `_blockNumber`. + **/ + function balanceOfAt(address _owner, uint _blockNumber) external view returns (uint256); +} diff --git a/src/flare/token/interface/IIGovernanceVotePower.sol b/src/flare/token/interfaces/IIGovernanceVotePower.sol similarity index 100% rename from src/flare/token/interface/IIGovernanceVotePower.sol rename to src/flare/token/interfaces/IIGovernanceVotePower.sol diff --git a/src/flare/token/interface/IIVPContract.sol b/src/flare/token/interfaces/IIVPContract.sol similarity index 100% rename from src/flare/token/interface/IIVPContract.sol rename to src/flare/token/interfaces/IIVPContract.sol diff --git a/src/flare/token/interface/IIVPToken.sol b/src/flare/token/interfaces/IIVPToken.sol similarity index 100% rename from src/flare/token/interface/IIVPToken.sol rename to src/flare/token/interfaces/IIVPToken.sol diff --git a/src/flare/tokenPools/interfaces/IIFtsoRewardManager.sol b/src/flare/tokenPools/interfaces/IIFtsoRewardManager.sol new file mode 100644 index 0000000..f7907a3 --- /dev/null +++ b/src/flare/tokenPools/interfaces/IIFtsoRewardManager.sol @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IFtsoRewardManager.sol"; +import "../interfaces/IITokenPool.sol"; +import "../../inflation/interfaces/IIInflationReceiverV1.sol"; + +interface IIFtsoRewardManager is IFtsoRewardManager, IIInflationReceiverV1, IITokenPool { + + event DailyAuthorizedInflationSet(uint256 authorizedAmountWei); + event InflationReceived(uint256 amountReceivedWei); + event RewardsBurned(uint256 amountBurnedWei); + + function activate() external; + function enableClaims() external; + function deactivate() external; + function closeExpiredRewardEpoch(uint256 _rewardEpochId) external; + + function distributeRewards( + address[] memory addresses, + uint256[] memory weights, + uint256 totalWeight, + uint256 epochId, + address ftso, + uint256 priceEpochDurationSeconds, + uint256 currentRewardEpoch, + uint256 priceEpochEndTime, + uint256 votePowerBlock + ) external; + + function accrueUnearnedRewards( + uint256 epochId, + uint256 priceEpochDurationSeconds, + uint256 priceEpochEndTime + ) external; + + function firstClaimableRewardEpoch() external view returns (uint256); + + /** + * @notice Returns the information on unclaimed reward of `_dataProvider` for `_rewardEpoch` + * @param _rewardEpoch reward epoch number + * @param _dataProvider address representing the data provider + * @return _amount number representing the unclaimed amount + * @return _weight number representing the share that has not yet been claimed + */ + function getUnclaimedReward( + uint256 _rewardEpoch, + address _dataProvider + ) + external view + returns ( + uint256 _amount, + uint256 _weight + ); +} diff --git a/src/flare/tokenPools/interfaces/IIGenericRewardManager.sol b/src/flare/tokenPools/interfaces/IIGenericRewardManager.sol new file mode 100644 index 0000000..c543ef6 --- /dev/null +++ b/src/flare/tokenPools/interfaces/IIGenericRewardManager.sol @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IGenericRewardManager.sol"; +import "../interfaces/IITokenPool.sol"; +import "../../inflation/interfaces/IIInflationReceiverV1.sol"; + +interface IIGenericRewardManager is IGenericRewardManager, IIInflationReceiverV1, IITokenPool { + + event DailyAuthorizedInflationSet(uint256 authorizedAmountWei); + event InflationReceived(uint256 amountReceivedWei); + + function activate() external; + function deactivate() external; + + function distributeRewards( + address[] memory _addresses, + uint256[] memory _rewardAmounts + ) external; + + function getTotals() + external view + returns ( + uint256 _totalAwardedWei, + uint256 _totalClaimedWei, + uint256 _totalInflationAuthorizedWei, + uint256 _totalInflationReceivedWei, + uint256 _lastInflationAuthorizationReceivedTs, + uint256 _dailyAuthorizedInflation + ); +} diff --git a/src/flare/tokenPools/interfaces/IIIncentivePoolAllocation.sol b/src/flare/tokenPools/interfaces/IIIncentivePoolAllocation.sol new file mode 100644 index 0000000..a395bee --- /dev/null +++ b/src/flare/tokenPools/interfaces/IIIncentivePoolAllocation.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIIncentivePoolPercentageProvider.sol"; +import "./IIIncentivePoolSharingPercentageProvider.sol"; + +interface IIIncentivePoolAllocation is IIIncentivePoolPercentageProvider, IIIncentivePoolSharingPercentageProvider { + +} diff --git a/src/flare/tokenPools/interfaces/IIIncentivePoolPercentageProvider.sol b/src/flare/tokenPools/interfaces/IIIncentivePoolPercentageProvider.sol new file mode 100644 index 0000000..f9bea30 --- /dev/null +++ b/src/flare/tokenPools/interfaces/IIIncentivePoolPercentageProvider.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIIncentivePoolPercentageProvider { + /** + * Return the annual incentivePool rate in bips. + */ + function getAnnualPercentageBips() external returns(uint256); +} diff --git a/src/flare/tokenPools/interfaces/IIIncentivePoolReceiver.sol b/src/flare/tokenPools/interfaces/IIIncentivePoolReceiver.sol new file mode 100644 index 0000000..d1c4f10 --- /dev/null +++ b/src/flare/tokenPools/interfaces/IIIncentivePoolReceiver.sol @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIIncentivePoolReceiver { + /** + * Notify the receiver that it is entitled to receive `_toAuthorizeWei` incentive amount. + * @param _toAuthorizeWei the amount of incentive that can be awarded in the coming day + */ + function setDailyAuthorizedIncentive(uint256 _toAuthorizeWei) external; + + /** + * Receive native tokens from incentivePool. + */ + function receiveIncentive() external payable; + + /** + * IncentivePool receivers have a reference to the IncentivePool contract. + */ + function getIncentivePoolAddress() external returns(address); + + /** + * Implement this function for updating incentivePool receiver contracts through AddressUpdater. + */ + function getContractName() external view returns (string memory); +} diff --git a/src/flare/tokenPools/interfaces/IIIncentivePoolSharingPercentageProvider.sol b/src/flare/tokenPools/interfaces/IIIncentivePoolSharingPercentageProvider.sol new file mode 100644 index 0000000..8910145 --- /dev/null +++ b/src/flare/tokenPools/interfaces/IIIncentivePoolSharingPercentageProvider.sol @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIIncentivePoolReceiver.sol"; + +struct SharingPercentage { + IIIncentivePoolReceiver incentivePoolReceiver; + uint256 percentBips; +} + +interface IIIncentivePoolSharingPercentageProvider { + /** + * Return the shared percentage per incentivPool receiver. + * @dev Assumption is that implementer edited that percents sum to 100 pct and + * that receiver addresses are valid. + */ + function getSharingPercentages() external returns(SharingPercentage[] memory); +} diff --git a/src/flare/tokenPools/interfaces/IITokenPool.sol b/src/flare/tokenPools/interfaces/IITokenPool.sol new file mode 100644 index 0000000..a8a463f --- /dev/null +++ b/src/flare/tokenPools/interfaces/IITokenPool.sol @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IITokenPool { + + /** + * @notice Return token pool supply data + * @return _lockedFundsWei Funds that are intentionally locked in the token pool + * and not part of circulating supply + * @return _totalInflationAuthorizedWei Total inflation authorized amount (wei) + * @return _totalClaimedWei Total claimed amount (wei) + */ + function getTokenPoolSupplyData() external returns ( + uint256 _lockedFundsWei, + uint256 _totalInflationAuthorizedWei, + uint256 _totalClaimedWei + ); +} diff --git a/src/flare/utils/interfaces/IIFtsoRegistry.sol b/src/flare/utils/interfaces/IIFtsoRegistry.sol new file mode 100644 index 0000000..82d239a --- /dev/null +++ b/src/flare/utils/interfaces/IIFtsoRegistry.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../ftso/interfaces/IIFtso.sol"; +import "../../IFtsoRegistry.sol"; + + +interface IIFtsoRegistry is IFtsoRegistry { + + // returns ftso index + function addFtso(IIFtso _ftsoContract) external returns(uint256); + + function removeFtso(IIFtso _ftso) external; +} diff --git a/src/flare/utils/interfaces/IIRandomProvider.sol b/src/flare/utils/interfaces/IIRandomProvider.sol new file mode 100644 index 0000000..26b45cd --- /dev/null +++ b/src/flare/utils/interfaces/IIRandomProvider.sol @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IIRandomProvider { + + function chillNonrevealingDataProviders(uint256 _finalizingPriceEpochId, uint256 _currentPriceEpochId) external; + + function getCurrentRandom() external view returns(uint256 _currentRandom); + + function getCurrentRandomWithQuality() external view returns(uint256 _currentRandom, bool _goodRandom); +} diff --git a/src/flare/utils/interfaces/IIVoterWhitelister.sol b/src/flare/utils/interfaces/IIVoterWhitelister.sol new file mode 100644 index 0000000..34ff426 --- /dev/null +++ b/src/flare/utils/interfaces/IIVoterWhitelister.sol @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IVoterWhitelister.sol"; + + +interface IIVoterWhitelister is IVoterWhitelister { + /** + * @notice Used to chill voter - remove from whitelist for a specified number of reward epochs + * @dev Only governance can call this method. + */ + function chillVoter( + address _voter, + uint256 _noOfRewardEpochs, + uint256[] memory _ftsoIndices + ) + external + returns( + bool[] memory _removed, + uint256 _untilRewardEpoch + ); + + /** + * Set the maximum number of voters in the whitelist for FTSO at index `_ftsoIndex`. + * Possibly removes several voters with the least votepower from the whitelist. + * Only governance can call this method. + */ + function setMaxVotersForFtso(uint256 _ftsoIndex, uint256 _newMaxVoters) external; + + /** + * Set the maximum number of voters in the whitelist for a new FTSO. + * Only governance can call this method. + */ + function setDefaultMaxVotersForFtso(uint256 _defaultMaxVotersForFtso) external; + + /** + * Create whitelist with default size for ftso. + * Only ftso manager can call this method. + */ + function addFtso(uint256 _ftsoIndex) external; + + /** + * Clear whitelist for ftso at `_ftsoIndex`. + * Only ftso manager can call this method. + */ + function removeFtso(uint256 _ftsoIndex) external; + + /** + * Remove `_trustedAddress` from whitelist for ftso at `_ftsoIndex`. + */ + function removeTrustedAddressFromWhitelist(address _trustedAddress, uint256 _ftsoIndex) external; +} diff --git a/src/flare/utils/interfaces/IUpdateValidators.sol b/src/flare/utils/interfaces/IUpdateValidators.sol new file mode 100644 index 0000000..4788daf --- /dev/null +++ b/src/flare/utils/interfaces/IUpdateValidators.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IUpdateValidators { + /** + update the validators after reward epoch + **/ + function updateActiveValidators() external; +} diff --git a/src/songbird/ContractRegistry.sol b/src/songbird/ContractRegistry.sol index 0e02994..b5e1133 100644 --- a/src/songbird/ContractRegistry.sol +++ b/src/songbird/ContractRegistry.sol @@ -1,46 +1,46 @@ // SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; +pragma solidity ^0.8.25; -import {IFlareContractRegistry} from "./IFlareContractRegistry.sol"; - -// Auto generated imports +import { IFlareContractRegistry } from "./IFlareContractRegistry.sol"; // AUTO GENERATED - DO NOT EDIT BELOW THIS LINE -import {IPriceSubmitter} from "./IPriceSubmitter.sol"; -import {IGovernanceSettings} from "./IGovernanceSettings.sol"; -import {IFtsoRewardManager} from "./IFtsoRewardManager.sol"; -import {IFtsoRegistry} from "./IFtsoRegistry.sol"; -import {IVoterWhitelister} from "./IVoterWhitelister.sol"; -import {IFtsoManager} from "./IFtsoManager.sol"; -import {IWNat} from "./IWNat.sol"; -import {IGovernanceVotePower} from "./IGovernanceVotePower.sol"; -import {IClaimSetupManager} from "./IClaimSetupManager.sol"; -import {IFlareAssetRegistry} from "./IFlareAssetRegistry.sol"; -import {IFlareContractRegistry} from "./IFlareContractRegistry.sol"; -import {ISubmission} from "./ISubmission.sol"; -import {IEntityManager} from "./IEntityManager.sol"; -import {IVoterRegistry} from "./IVoterRegistry.sol"; -import {IFlareSystemsCalculator} from "./IFlareSystemsCalculator.sol"; -import {IFlareSystemsManager} from "./IFlareSystemsManager.sol"; -import {IRewardManager} from "./IRewardManager.sol"; -import {IRelay} from "./IRelay.sol"; -import {IWNatDelegationFee} from "./IWNatDelegationFee.sol"; -import {IFtsoInflationConfigurations} from "./IFtsoInflationConfigurations.sol"; -import {IFtsoRewardOffersManager} from "./IFtsoRewardOffersManager.sol"; -import {IFtsoFeedDecimals} from "./IFtsoFeedDecimals.sol"; -import {IFtsoFeedPublisher} from "./IFtsoFeedPublisher.sol"; -import {IFtsoFeedIdConverter} from "./IFtsoFeedIdConverter.sol"; -import {IFastUpdateIncentiveManager} from "./IFastUpdateIncentiveManager.sol"; -import {IFastUpdater} from "./IFastUpdater.sol"; -import {IFastUpdatesConfiguration} from "./IFastUpdatesConfiguration.sol"; -import {IFeeCalculator} from "./IFeeCalculator.sol"; -import {FtsoV2Interface} from "./FtsoV2Interface.sol"; -import {TestFtsoV2Interface} from "./TestFtsoV2Interface.sol"; -import {ProtocolsV2Interface} from "./ProtocolsV2Interface.sol"; -import {RandomNumberV2Interface} from "./RandomNumberV2Interface.sol"; -import {RewardsV2Interface} from "./RewardsV2Interface.sol"; -import {IFdcVerification} from "./IFdcVerification.sol"; -import {IFdcHub} from "./IFdcHub.sol"; -import {IFdcRequestFeeConfigurations} from "./IFdcRequestFeeConfigurations.sol"; +import { IPriceSubmitter } from "./IPriceSubmitter.sol"; +import { IGovernanceSettings } from "./IGovernanceSettings.sol"; +import { IFtsoRewardManager } from "./IFtsoRewardManager.sol"; +import { IFtsoRegistry } from "./IFtsoRegistry.sol"; +import { IVoterWhitelister } from "./IVoterWhitelister.sol"; +import { IFtsoManager } from "./IFtsoManager.sol"; +import { IWNat } from "./IWNat.sol"; +import { IGovernanceVotePower } from "./IGovernanceVotePower.sol"; +import { IClaimSetupManager } from "./IClaimSetupManager.sol"; +import { IFlareAssetRegistry } from "./IFlareAssetRegistry.sol"; +import { IFlareContractRegistry } from "./IFlareContractRegistry.sol"; +import { ISubmission } from "./ISubmission.sol"; +import { IEntityManager } from "./IEntityManager.sol"; +import { IVoterRegistry } from "./IVoterRegistry.sol"; +import { IFlareSystemsCalculator } from "./IFlareSystemsCalculator.sol"; +import { IFlareSystemsManager } from "./IFlareSystemsManager.sol"; +import { IRewardManager } from "./IRewardManager.sol"; +import { IRelay } from "./IRelay.sol"; +import { IWNatDelegationFee } from "./IWNatDelegationFee.sol"; +import { IFtsoInflationConfigurations } from "./IFtsoInflationConfigurations.sol"; +import { IFtsoRewardOffersManager } from "./IFtsoRewardOffersManager.sol"; +import { IFtsoFeedDecimals } from "./IFtsoFeedDecimals.sol"; +import { IFtsoFeedPublisher } from "./IFtsoFeedPublisher.sol"; +import { IFtsoFeedIdConverter } from "./IFtsoFeedIdConverter.sol"; +import { IFastUpdateIncentiveManager } from "./IFastUpdateIncentiveManager.sol"; +import { IFastUpdater } from "./IFastUpdater.sol"; +import { IFastUpdatesConfiguration } from "./IFastUpdatesConfiguration.sol"; +import { IFeeCalculator } from "./IFeeCalculator.sol"; +import { FtsoV2Interface } from "./FtsoV2Interface.sol"; +import { TestFtsoV2Interface } from "./TestFtsoV2Interface.sol"; +import { ProtocolsV2Interface } from "./ProtocolsV2Interface.sol"; +import { RandomNumberV2Interface } from "./RandomNumberV2Interface.sol"; +import { RewardsV2Interface } from "./RewardsV2Interface.sol"; +import { IFdcVerification } from "./IFdcVerification.sol"; +import { IFdcHub } from "./IFdcHub.sol"; +import { IFdcRequestFeeConfigurations } from "./IFdcRequestFeeConfigurations.sol"; +import { IAssetManagerController } from "./IAssetManagerController.sol"; +import { IAssetManager } from "./IAssetManager.sol"; // END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE // Library is intended to be used inline, so the strings are all memory allocated (instead of calldata) @@ -103,14 +103,18 @@ library ContractRegistry { } // Nice typed getters for all the important contracts - // AUTO GENERATED - DO NOT EDIT BELOW THIS LINE - function getPriceSubmitter() internal view returns (IPriceSubmitter) { +// AUTO GENERATED - DO NOT EDIT BELOW THIS LINE + function getPriceSubmitter() + internal + view + returns (IPriceSubmitter) + { return IPriceSubmitter( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("PriceSubmitter")) - ) - ); + keccak256(abi.encode("PriceSubmitter")) + ) + ); } function getGovernanceSettings() @@ -121,54 +125,74 @@ library ContractRegistry { return IGovernanceSettings( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("GovernanceSettings")) - ) - ); + keccak256(abi.encode("GovernanceSettings")) + ) + ); } - function getFtsoRewardManager() internal view returns (IFtsoRewardManager) { + function getFtsoRewardManager() + internal + view + returns (IFtsoRewardManager) + { return IFtsoRewardManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRewardManager")) - ) - ); + keccak256(abi.encode("FtsoRewardManager")) + ) + ); } - function getFtsoRegistry() internal view returns (IFtsoRegistry) { + function getFtsoRegistry() + internal + view + returns (IFtsoRegistry) + { return IFtsoRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRegistry")) - ) - ); + keccak256(abi.encode("FtsoRegistry")) + ) + ); } - function getVoterWhitelister() internal view returns (IVoterWhitelister) { + function getVoterWhitelister() + internal + view + returns (IVoterWhitelister) + { return IVoterWhitelister( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("VoterWhitelister")) - ) - ); + keccak256(abi.encode("VoterWhitelister")) + ) + ); } - function getFtsoManager() internal view returns (IFtsoManager) { + function getFtsoManager() + internal + view + returns (IFtsoManager) + { return IFtsoManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoManager")) - ) - ); + keccak256(abi.encode("FtsoManager")) + ) + ); } - function getWNat() internal view returns (IWNat) { + function getWNat() + internal + view + returns (IWNat) + { return IWNat( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("WNat")) - ) - ); + keccak256(abi.encode("WNat")) + ) + ); } function getGovernanceVotePower() @@ -179,18 +203,22 @@ library ContractRegistry { return IGovernanceVotePower( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("GovernanceVotePower")) - ) - ); + keccak256(abi.encode("GovernanceVotePower")) + ) + ); } - function getClaimSetupManager() internal view returns (IClaimSetupManager) { + function getClaimSetupManager() + internal + view + returns (IClaimSetupManager) + { return IClaimSetupManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ClaimSetupManager")) - ) - ); + keccak256(abi.encode("ClaimSetupManager")) + ) + ); } function getFlareAssetRegistry() @@ -201,9 +229,9 @@ library ContractRegistry { return IFlareAssetRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareAssetRegistry")) - ) - ); + keccak256(abi.encode("FlareAssetRegistry")) + ) + ); } function getFlareContractRegistry() @@ -214,36 +242,48 @@ library ContractRegistry { return IFlareContractRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareContractRegistry")) - ) - ); + keccak256(abi.encode("FlareContractRegistry")) + ) + ); } - function getSubmission() internal view returns (ISubmission) { + function getSubmission() + internal + view + returns (ISubmission) + { return ISubmission( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("Submission")) - ) - ); + keccak256(abi.encode("Submission")) + ) + ); } - function getEntityManager() internal view returns (IEntityManager) { + function getEntityManager() + internal + view + returns (IEntityManager) + { return IEntityManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("EntityManager")) - ) - ); + keccak256(abi.encode("EntityManager")) + ) + ); } - function getVoterRegistry() internal view returns (IVoterRegistry) { + function getVoterRegistry() + internal + view + returns (IVoterRegistry) + { return IVoterRegistry( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("VoterRegistry")) - ) - ); + keccak256(abi.encode("VoterRegistry")) + ) + ); } function getFlareSystemsCalculator() @@ -254,9 +294,9 @@ library ContractRegistry { return IFlareSystemsCalculator( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareSystemsCalculator")) - ) - ); + keccak256(abi.encode("FlareSystemsCalculator")) + ) + ); } function getFlareSystemsManager() @@ -267,36 +307,48 @@ library ContractRegistry { return IFlareSystemsManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FlareSystemsManager")) - ) - ); + keccak256(abi.encode("FlareSystemsManager")) + ) + ); } - function getRewardManager() internal view returns (IRewardManager) { + function getRewardManager() + internal + view + returns (IRewardManager) + { return IRewardManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RewardManager")) - ) - ); + keccak256(abi.encode("RewardManager")) + ) + ); } - function getRelay() internal view returns (IRelay) { + function getRelay() + internal + view + returns (IRelay) + { return IRelay( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("Relay")) - ) - ); + keccak256(abi.encode("Relay")) + ) + ); } - function getWNatDelegationFee() internal view returns (IWNatDelegationFee) { + function getWNatDelegationFee() + internal + view + returns (IWNatDelegationFee) + { return IWNatDelegationFee( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("WNatDelegationFee")) - ) - ); + keccak256(abi.encode("WNatDelegationFee")) + ) + ); } function getFtsoInflationConfigurations() @@ -307,9 +359,9 @@ library ContractRegistry { return IFtsoInflationConfigurations( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoInflationConfigurations")) - ) - ); + keccak256(abi.encode("FtsoInflationConfigurations")) + ) + ); } function getFtsoRewardOffersManager() @@ -320,27 +372,35 @@ library ContractRegistry { return IFtsoRewardOffersManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoRewardOffersManager")) - ) - ); + keccak256(abi.encode("FtsoRewardOffersManager")) + ) + ); } - function getFtsoFeedDecimals() internal view returns (IFtsoFeedDecimals) { + function getFtsoFeedDecimals() + internal + view + returns (IFtsoFeedDecimals) + { return IFtsoFeedDecimals( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoFeedDecimals")) - ) - ); + keccak256(abi.encode("FtsoFeedDecimals")) + ) + ); } - function getFtsoFeedPublisher() internal view returns (IFtsoFeedPublisher) { + function getFtsoFeedPublisher() + internal + view + returns (IFtsoFeedPublisher) + { return IFtsoFeedPublisher( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoFeedPublisher")) - ) - ); + keccak256(abi.encode("FtsoFeedPublisher")) + ) + ); } function getFtsoFeedIdConverter() @@ -351,9 +411,9 @@ library ContractRegistry { return IFtsoFeedIdConverter( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoFeedIdConverter")) - ) - ); + keccak256(abi.encode("FtsoFeedIdConverter")) + ) + ); } function getFastUpdateIncentiveManager() @@ -364,18 +424,22 @@ library ContractRegistry { return IFastUpdateIncentiveManager( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FastUpdateIncentiveManager")) - ) - ); + keccak256(abi.encode("FastUpdateIncentiveManager")) + ) + ); } - function getFastUpdater() internal view returns (IFastUpdater) { + function getFastUpdater() + internal + view + returns (IFastUpdater) + { return IFastUpdater( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FastUpdater")) - ) - ); + keccak256(abi.encode("FastUpdater")) + ) + ); } function getFastUpdatesConfiguration() @@ -386,45 +450,61 @@ library ContractRegistry { return IFastUpdatesConfiguration( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FastUpdatesConfiguration")) - ) - ); + keccak256(abi.encode("FastUpdatesConfiguration")) + ) + ); } - function getFeeCalculator() internal view returns (IFeeCalculator) { + function getFeeCalculator() + internal + view + returns (IFeeCalculator) + { return IFeeCalculator( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FeeCalculator")) - ) - ); + keccak256(abi.encode("FeeCalculator")) + ) + ); } - function getFtsoV2() internal view returns (FtsoV2Interface) { + function getFtsoV2() + internal + view + returns (FtsoV2Interface) + { return FtsoV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoV2")) - ) - ); + keccak256(abi.encode("FtsoV2")) + ) + ); } - function getTestFtsoV2() internal view returns (TestFtsoV2Interface) { + function getTestFtsoV2() + internal + view + returns (TestFtsoV2Interface) + { return TestFtsoV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FtsoV2")) - ) - ); + keccak256(abi.encode("FtsoV2")) + ) + ); } - function getProtocolsV2() internal view returns (ProtocolsV2Interface) { + function getProtocolsV2() + internal + view + returns (ProtocolsV2Interface) + { return ProtocolsV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("ProtocolsV2")) - ) - ); + keccak256(abi.encode("ProtocolsV2")) + ) + ); } function getRandomNumberV2() @@ -435,36 +515,48 @@ library ContractRegistry { return RandomNumberV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RandomNumberV2")) - ) - ); + keccak256(abi.encode("RandomNumberV2")) + ) + ); } - function getRewardsV2() internal view returns (RewardsV2Interface) { + function getRewardsV2() + internal + view + returns (RewardsV2Interface) + { return RewardsV2Interface( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("RewardsV2")) - ) - ); + keccak256(abi.encode("RewardsV2")) + ) + ); } - function getFdcVerification() internal view returns (IFdcVerification) { + function getFdcVerification() + internal + view + returns (IFdcVerification) + { return IFdcVerification( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcVerification")) - ) - ); + keccak256(abi.encode("FdcVerification")) + ) + ); } - function getFdcHub() internal view returns (IFdcHub) { + function getFdcHub() + internal + view + returns (IFdcHub) + { return IFdcHub( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcHub")) - ) - ); + keccak256(abi.encode("FdcHub")) + ) + ); } function getFdcRequestFeeConfigurations() @@ -475,10 +567,36 @@ library ContractRegistry { return IFdcRequestFeeConfigurations( FLARE_CONTRACT_REGISTRY.getContractAddressByHash( - keccak256(abi.encode("FdcRequestFeeConfigurations")) - ) - ); + keccak256(abi.encode("FdcRequestFeeConfigurations")) + ) + ); } - // END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE -} + function getAssetManagerController() + internal + view + returns (IAssetManagerController) + { + return + IAssetManagerController( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("AssetManagerController")) + ) + ); + } + + function getAssetManagerFXRP() + internal + view + returns (IAssetManager) + { + return + IAssetManager( + FLARE_CONTRACT_REGISTRY.getContractAddressByHash( + keccak256(abi.encode("AssetManagerFXRP")) + ) + ); + } + +// END AUTO GENERATED - DO NOT EDIT ABOVE THIS LINE +} \ No newline at end of file diff --git a/src/songbird/IAgentOwnerRegistry.sol b/src/songbird/IAgentOwnerRegistry.sol new file mode 100644 index 0000000..4075ba8 --- /dev/null +++ b/src/songbird/IAgentOwnerRegistry.sol @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +/** + * Agent owner management and work address management + */ +interface IAgentOwnerRegistry { + + event Whitelisted(address value); + event WhitelistingRevoked(address value); + + /** + * Agent owner's work address has been set. + */ + event WorkAddressChanged( + address indexed managementAddress, + address prevWorkAddress, + address workAddress); + + event AgentDataChanged( + address indexed managementAddress, + string name, + string description, + string iconUrl, + string termsOfUseUrl); + + error AgentNotWhitelisted(); + error WorkAddressInUse(); + + + /** + * Returns true if the address is whitelisted, false otherwise. + * @param _address address to check + */ + function isWhitelisted(address _address) external view returns (bool); + + /** + * Return agent owner's name. + * @param _managementAddress agent owner's management address + */ + function getAgentName(address _managementAddress) + external view + returns (string memory); + + /** + * Return agent owner's description. + * @param _managementAddress agent owner's management address + */ + function getAgentDescription(address _managementAddress) + external view + returns (string memory); + + /** + * Return url of the agent owner's icon. + * @param _managementAddress agent owner's management address + */ + function getAgentIconUrl(address _managementAddress) + external view + returns (string memory); + + /** + * Return url of the agent's page with terms of use. + * @param _managementAddress agent owner's management address + */ + function getAgentTermsOfUseUrl(address _managementAddress) + external view + returns (string memory); + + /** + * Get the (unique) work address for the given management address. + */ + function getWorkAddress(address _managementAddress) + external view + returns (address); + + /** + * Get the (unique) management address for the given work address. + */ + function getManagementAddress(address _workAddress) + external view + returns (address); +} \ No newline at end of file diff --git a/src/songbird/IAssetManager.sol b/src/songbird/IAssetManager.sol index 4bfe18a..60953d0 100644 --- a/src/songbird/IAssetManager.sol +++ b/src/songbird/IAssetManager.sol @@ -1,24 +1,26 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IFdcVerification.sol"; -import "@openzeppelin-contracts/utils/introspection/IERC165.sol"; -import "./diamond/interfaces/IDiamondLoupe.sol"; -import "./userInterfaces/data/AssetManagerSettings.sol"; -import "./userInterfaces/data/CollateralType.sol"; -import "./userInterfaces/data/AgentInfo.sol"; -import "./userInterfaces/data/AgentSettings.sol"; -import "./userInterfaces/data/AvailableAgentInfo.sol"; -import "./userInterfaces/data/RedemptionTicketInfo.sol"; -import "./userInterfaces/data/RedemptionRequestInfo.sol"; -import "./userInterfaces/data/CollateralReservationInfo.sol"; -import "./IAssetManagerEvents.sol"; -import "./IAgentPing.sol"; -import "./IRedemptionTimeExtension.sol"; -import "./ITransferFees.sol"; -import "./ICoreVault.sol"; -import "./ICoreVaultSettings.sol"; -import "./IAgentAlwaysAllowedMinters.sol"; +import {IConfirmedBlockHeightExists, IPayment, IAddressValidity, IReferencedPaymentNonexistence, + IBalanceDecreasingTransaction} + from ".//IFdcVerification.sol"; +import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; +import {IDiamondLoupe} from "./diamond/interfaces/IDiamondLoupe.sol"; +import {AssetManagerSettings} from "./data/AssetManagerSettings.sol"; +import {CollateralType} from "./data/CollateralType.sol"; +import {AgentInfo} from "./data/AgentInfo.sol"; +import {AgentSettings} from "./data/AgentSettings.sol"; +import {AvailableAgentInfo} from "./data/AvailableAgentInfo.sol"; +import {RedemptionTicketInfo} from "./data/RedemptionTicketInfo.sol"; +import {RedemptionRequestInfo} from "./data/RedemptionRequestInfo.sol"; +import {CollateralReservationInfo} from "./data/CollateralReservationInfo.sol"; +import {IAssetManagerEvents} from "./IAssetManagerEvents.sol"; +import {IAgentPing} from "./IAgentPing.sol"; +import {IRedemptionTimeExtension} from "./IRedemptionTimeExtension.sol"; +import {ICoreVaultClient} from "./ICoreVaultClient.sol"; +import {ICoreVaultClientSettings} from "./ICoreVaultClientSettings.sol"; +import {IAgentAlwaysAllowedMinters} from "./IAgentAlwaysAllowedMinters.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @@ -30,9 +32,8 @@ interface IAssetManager is IAssetManagerEvents, IAgentPing, IRedemptionTimeExtension, - ITransferFees, - ICoreVault, - ICoreVaultSettings, + ICoreVaultClient, + ICoreVaultClientSettings, IAgentAlwaysAllowedMinters { //////////////////////////////////////////////////////////////////////////////////// @@ -148,19 +149,6 @@ interface IAssetManager is external view returns (bool); - /** - * True if the asset manager is terminated. - * In terminated state almost all operations (minting, redeeming, liquidation) are disabled and f-assets are - * not transferable any more. The only operation still permitted is for agents to release the locked collateral - * by calling `buybackAgentCollateral`. - * An asset manager can be terminated after being paused for at least a month - * (to redeem as many f-assets as possible). - * The terminated asset manager can not be revived anymore. - */ - function terminated() - external view - returns (bool); - //////////////////////////////////////////////////////////////////////////////////// // Timekeeping for underlying chain @@ -207,20 +195,6 @@ interface IAssetManager is //////////////////////////////////////////////////////////////////////////////////// // Agent create / destroy - /** - * This method fixes the underlying address to be used by given agent owner. - * A proof of payment (can be minimal or to itself) from this address must be provided, - * with payment reference being equal to this method caller's address. - * NOTE: calling this method before `createAgentVault()` is optional on most chains, - * but is required on smart contract chains to make sure the agent is using EOA address - * (depends on setting `requireEOAAddressProof`). - * NOTE: may only be called by a whitelisted agent (management or work owner address). - * @param _payment proof of payment on the underlying chain - */ - function proveUnderlyingAddressEOA( - IPayment.Proof calldata _payment - ) external; - /** * Create an agent vault. * The agent will always be identified by `_agentVault` address. @@ -326,7 +300,7 @@ interface IAssetManager is ) external; /** - * When current pool collateral token contract (WNat) is replaced by the method setPoolCollateralType, + * When current pool collateral token contract (WNat) is replaced by the method setPoolWNatCollateralType, * pools don't switch automatically. Instead, the agent must call this method that swaps old WNat tokens for * new ones and sets it for use by the pool. * NOTE: may only be called by the agent vault owner. @@ -426,24 +400,6 @@ interface IAssetManager is address _agentVault ) external; - //////////////////////////////////////////////////////////////////////////////////// - // Terminated asset manager support - - /** - * When f-asset is terminated, an agent can burn the market price of backed f-assets with his collateral, - * to release the remaining collateral (and, formally, underlying assets). - * This method ONLY works when f-asset is terminated, which will only be done when the asset manager - * is already paused at least for a month and most f-assets are already burned and the only ones - * remaining are unrecoverable. - * NOTE: may only be called by the agent vault owner. - * NOTE: the agent (management address) receives the vault collateral and NAT is burned instead. Therefore - * this method is `payable` and the caller must provide enough NAT to cover the received vault collateral - * amount multiplied by `vaultCollateralBuyForFlareFactorBIPS`. - */ - function buybackAgentCollateral( - address _agentVault - ) external payable; - //////////////////////////////////////////////////////////////////////////////////// // Agent information @@ -455,7 +411,7 @@ interface IAssetManager is */ function getAllAgents(uint256 _start, uint256 _end) external view - returns (address[] memory _agentVaults, uint256 _totalLength); + returns (address[] memory _agents, uint256 _totalLength); /** * Return detailed info about an agent, typically needed by a minter. @@ -473,8 +429,7 @@ interface IAssetManager is * @param _agentVault agent vault address * @param _name setting name, one of: `feeBIPS`, `poolFeeShareBIPS`, `redemptionPoolFeeShareBIPS`, * `mintingVaultCollateralRatioBIPS`, `mintingPoolCollateralRatioBIPS`,`buyFAssetByAgentFactorBIPS`, - * `poolExitCollateralRatioBIPS`, `poolTopupCollateralRatioBIPS`, `poolTopupTokenPriceFactorBIPS`, - * `handshakeType` + * `poolExitCollateralRatioBIPS` */ function getAgentSetting(address _agentVault, string memory _name) external view @@ -582,7 +537,7 @@ interface IAssetManager is */ function getAvailableAgentsList(uint256 _start, uint256 _end) external view - returns (address[] memory _agentVaults, uint256 _totalLength); + returns (address[] memory _agents, uint256 _totalLength); /** * Get (a part of) the list of available agents with extra information about agents' fee, min collateral ratio @@ -604,15 +559,11 @@ interface IAssetManager is * Before paying underlying assets for minting, minter has to reserve collateral and * pay collateral reservation fee. Collateral is reserved at ratio of agent's agentMinCollateralRatio * to requested lots NAT market price. - * If the agent requires handshake, then HandshakeRequired event is emitted and - * the minter has to wait for the agent to approve or reject the reservation. If there is no response within - * the `cancelCollateralReservationAfterSeconds`, the minter can cancel the reservation and get the fee back. - * If handshake is not required, the minter receives instructions for underlying payment + * The minter receives instructions for underlying payment * (value, fee and payment reference) in event CollateralReserved. * Then the minter has to pay `value + fee` on the underlying chain. - * If the minter pays the underlying amount, the collateral reservation fee is burned and minter obtains - * f-assets. Otherwise the agent collects the collateral reservation fee. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. + * If the minter pays the underlying amount, minter obtains f-assets. + * The collateral reservation fee is split between the agent and the collateral pool. * NOTE: the owner of the agent vault must be in the AgentOwnerRegistry. * @param _agentVault agent vault address * @param _lots the number of lots for which to reserve collateral @@ -621,45 +572,14 @@ interface IAssetManager is * and increasing fee (that would mean that the minter would have to pay raised fee or forfeit * collateral reservation fee) * @param _executor the account that is allowed to execute minting (besides minter and agent) - * @param _minterUnderlyingAddresses array of minter's underlying addresses - needed only if handshake is required */ function reserveCollateral( address _agentVault, uint256 _lots, uint256 _maxMintingFeeBIPS, - address payable _executor, - string[] calldata _minterUnderlyingAddresses - ) external payable; - - /** - * Agent approves the collateral reservation request after checking the minter's identity. - * NOTE: may only be called by the agent vault owner. - * @param _collateralReservationId collateral reservation id - */ - function approveCollateralReservation( - uint256 _collateralReservationId - ) external; - - /** - * Agent rejects the collateral reservation request after checking the minter's identity. - * The collateral reservation fee is returned to the minter. - * NOTE: may only be called by the agent vault owner. - * @param _collateralReservationId collateral reservation id - */ - function rejectCollateralReservation( - uint256 _collateralReservationId - ) external; - - /** - * Minter cancels the collateral reservation request if the agent didn't respond in time. - * The collateral reservation fee is returned to the minter. - * It can only be called after `cancelCollateralReservationAfterSeconds` from the collateral reservation request. - * NOTE: may only be called by the minter. - * @param _collateralReservationId collateral reservation id - */ - function cancelCollateralReservation( - uint256 _collateralReservationId - ) external; + address payable _executor + ) external payable + returns (uint256 _collateralReservationId); /** * Return the collateral reservation fee amount that has to be passed to the `reserveCollateral` method. @@ -686,8 +606,6 @@ interface IAssetManager is /** * After obtaining proof of underlying payment, the minter calls this method to finish the minting * and collect the minted f-assets. - * NOTE: In case handshake was required, the payment must be done using only all provided addresses, - * so `sourceAddressesRoot` matches the calculated Merkle root, otherwise the proof will be rejected. * NOTE: may only be called by the minter (= creator of CR, the collateral reservation request), * the executor appointed by the minter, or the agent owner (= owner of the agent vault in CR). * @param _payment proof of the underlying payment (must contain exact `value + fee` amount and correct @@ -703,9 +621,7 @@ interface IAssetManager is * When the time for the minter to pay the underlying amount is over (i.e. the last underlying block has passed), * the agent can declare payment default. Then the agent collects the collateral reservation fee * (it goes directly to the vault), and the reserved collateral is unlocked. - * NOTE: In case handshake was required, the attestation request must be done using `checkSourceAddresses=true` - * and correct `sourceAddressesRoot`, otherwise the proof will be rejected. If there was no handshake required, - * the attestation request must be done with `checkSourceAddresses=false`. + * NOTE: The attestation request must be done with `checkSourceAddresses=false`. * NOTE: may only be called by the owner of the agent vault in the collateral reservation request. * @param _proof proof that the minter didn't pay with correct payment reference on the underlying chain * @param _collateralReservationId id of a collateral reservation created by the minter @@ -750,7 +666,7 @@ interface IAssetManager is ) external; /** - * If an agent has enough free underlying, they can mint immediatelly without any underlying payment. + * If an agent has enough free underlying, they can mint immediately without any underlying payment. * This is a one-step process, skipping collateral reservation and collateral reservation fee payment. * Moreover, the agent doesn't have to be on the publicly available agents list to self-mint. * NOTE: may only be called by the agent vault owner. @@ -777,7 +693,6 @@ interface IAssetManager is * of remaining lots. * Agent receives redemption request id and instructions for underlying payment in * RedemptionRequested event and has to pay `value - fee` and use the provided payment reference. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _lots number of lots to redeem * @param _redeemerUnderlyingAddressString the address to which the agent must transfer underlying amount * @param _executor the account that is allowed to execute redemption default (besides redeemer and agent) @@ -791,28 +706,6 @@ interface IAssetManager is ) external payable returns (uint256 _redeemedAmountUBA); - /** - * In case agent requires handshake the redemption request can be rejected by the agent. - * Any other agent can take over the redemption request. - * If no agent takes over the redemption, the redeemer can request the default payment. - * NOTE: may only be called by the owner of the agent vault in the redemption request - * @param _redemptionRequestId id of an existing redemption request - */ - function rejectRedemptionRequest( - uint256 _redemptionRequestId - ) external; - - /** - * The agent can take over the rejected redemption request - it cannot be rejected again. - * NOTE: may only be called by the owner of the agent vault - * @param _agentVault agent vault address - * @param _redemptionRequestId id of an existing redemption request - */ - function takeOverRedemptionRequest( - address _agentVault, - uint256 _redemptionRequestId - ) external; - /** * If the redeemer provides invalid address, the agent should provide the proof of address invalidity from the * Flare data connector. With this, the agent's obligations are fulfilled and they can keep the underlying. @@ -864,20 +757,6 @@ interface IAssetManager is uint256 _redemptionRequestId ) external; - /** - * If the agent rejected the redemption request and no other agent took over the redemption, - * the redeemer calls this method and receives payment in collateral (with some extra). - * The agent can also call default if the redeemer is unresponsive, to payout the redeemer and free the - * remaining collateral. - * NOTE: may only be called by the redeemer (= creator of the redemption request), - * the executor appointed by the redeemer, - * or the agent owner (= owner of the agent vault in the redemption request) - * @param _redemptionRequestId id of an existing redemption request - */ - function rejectedRedemptionPaymentDefault( - uint256 _redemptionRequestId - ) external; - /** * If the agent hasn't performed the payment, the agent can close the redemption request to free underlying funds. * It can be done immediately after the redeemer or agent calls `redemptionPaymentDefault`, @@ -975,18 +854,15 @@ interface IAssetManager is // Liquidation /** - * Checks that the agent's collateral is too low and if true, starts the agent's liquidation. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. - * NOTE: always succeeds and returns the new liquidation status. + * Checks that the agent's collateral is too low and if true, starts agent's liquidation. + * If the agent is already in liquidation, returns the timestamp when liquidation started. * @param _agentVault agent vault address - * @return _liquidationStatus 0=no liquidation, 1=CCB, 2=liquidation - * @return _liquidationStartTs if the status is LIQUIDATION, the timestamp when liquidation started; - * if the status is CCB, the timestamp when liquidation will start; otherwise 0 + * @return _liquidationStartTs timestamp when liquidation started */ function startLiquidation( address _agentVault ) external - returns (uint8 _liquidationStatus, uint256 _liquidationStartTs); + returns (uint256 _liquidationStartTs); /** * Burns up to `_amountUBA` f-assets owned by the caller and pays @@ -994,7 +870,6 @@ interface IAssetManager is * (premium depends on the liquidation state). * If the agent isn't in liquidation yet, but satisfies conditions, * automatically puts the agent in liquidation status. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _agentVault agent vault address * @param _amountUBA the amount of f-assets to liquidate * @return _liquidatedAmountUBA liquidated amount of f-asset @@ -1028,12 +903,11 @@ interface IAssetManager is * no valid payment reference exists (valid payment references are from redemption and * underlying withdrawal announcement calls). * On success, immediately triggers full agent liquidation and rewards the caller. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. - * @param _transaction proof of a transaction from the agent's underlying address + * @param _payment proof of a transaction from the agent's underlying address * @param _agentVault agent vault address */ function illegalPaymentChallenge( - IBalanceDecreasingTransaction.Proof calldata _transaction, + IBalanceDecreasingTransaction.Proof calldata _payment, address _agentVault ) external; @@ -1041,7 +915,6 @@ interface IAssetManager is * Called with proofs of two payments made from the agent's underlying address * with the same payment reference (each payment reference is valid for only one payment). * On success, immediately triggers full agent liquidation and rewards the caller. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _payment1 proof of first payment from the agent's underlying address * @param _payment2 proof of second payment from the agent's underlying address * @param _agentVault agent vault address @@ -1057,7 +930,6 @@ interface IAssetManager is * underlying free balance negative (i.e. the underlying address balance is less than * the total amount of backed f-assets). * On success, immediately triggers full agent liquidation and rewards the caller. - * NOTE: may only be called by a whitelisted caller when whitelisting is enabled. * @param _payments proofs of several distinct payments from the agent's underlying address * @param _agentVault agent vault address */ diff --git a/src/songbird/IAssetManagerController.sol b/src/songbird/IAssetManagerController.sol new file mode 100644 index 0000000..be64480 --- /dev/null +++ b/src/songbird/IAssetManagerController.sol @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {IAssetManager} from "./IAssetManager.sol"; + + +interface IAssetManagerController { + /** + * Return the list of all asset managers managed by this controller. + */ + function getAssetManagers() + external view + returns (IAssetManager[] memory); + + /** + * Check whether the asset manager is managed by this controller. + * @param _assetManager an asset manager address + */ + function assetManagerExists(address _assetManager) + external view + returns (bool); +} diff --git a/src/songbird/IAssetManagerEvents.sol b/src/songbird/IAssetManagerEvents.sol index 032d711..e9dd216 100644 --- a/src/songbird/IAssetManagerEvents.sol +++ b/src/songbird/IAssetManagerEvents.sol @@ -18,9 +18,7 @@ interface IAssetManagerEvents { uint256 mintingPoolCollateralRatioBIPS; uint256 buyFAssetByAgentFactorBIPS; uint256 poolExitCollateralRatioBIPS; - uint256 poolTopupCollateralRatioBIPS; - uint256 poolTopupTokenPriceFactorBIPS; - uint256 handshakeType; + uint256 redemptionPoolFeeShareBIPS; } /** @@ -115,18 +113,6 @@ interface IAssetManagerEvents { uint8 collateralClass, address token); - /** - * Minter reserved collateral, paid the reservation fee. Agent's collateral was reserved. - * Agent needs to approve or reject the reservation according to the minter's identity. - */ - event HandshakeRequired( - address indexed agentVault, - address indexed minter, - uint256 indexed collateralReservationId, - string[] minterUnderlyingAddresses, - uint256 valueUBA, - uint256 feeUBA); - /** * Minter reserved collateral, paid the reservation fee, and is expected to pay the underlying funds. * Agent's collateral was reserved. @@ -145,24 +131,6 @@ interface IAssetManagerEvents { address executor, uint256 executorFeeNatWei); - /** - * Agent rejected the collateral reservation request because of the minter's identity. - * Reserved collateral was released. - */ - event CollateralReservationRejected( - address indexed agentVault, - address indexed minter, - uint256 indexed collateralReservationId); - - /** - * Minter cancelled the collateral reservation request because of the agent's inactivity. - * Reserved collateral was released. - */ - event CollateralReservationCancelled( - address indexed agentVault, - address indexed minter, - uint256 indexed collateralReservationId); - /** * Minter paid underlying funds in time and received the fassets. * The agent's collateral is locked. @@ -227,34 +195,13 @@ interface IAssetManagerEvents { address executor, uint256 executorFeeNatWei); - /** - * Agent rejected the redemption request because of the redeemer's identity. - */ - event RedemptionRequestRejected( - address indexed agentVault, - address indexed redeemer, - uint64 indexed requestId, - string paymentAddress, - uint256 valueUBA); - - /** - * Agent's rejected redemption request was taken over by another agent. - */ - event RedemptionRequestTakenOver( - address indexed agentVault, - address indexed redeemer, - uint64 indexed requestId, - uint256 valueTakenOverUBA, - address newAgentVault, - uint64 newRequestId); - /** * Agent rejected the redemption payment because the redeemer's address is invalid. */ event RedemptionRejected( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, uint256 redemptionAmountUBA); /** @@ -273,7 +220,7 @@ interface IAssetManagerEvents { event RedemptionPerformed( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, bytes32 transactionHash, uint256 redemptionAmountUBA, int256 spentUnderlyingUBA); @@ -288,7 +235,7 @@ interface IAssetManagerEvents { event RedemptionDefault( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, uint256 redemptionAmountUBA, uint256 redeemedVaultCollateralWei, uint256 redeemedPoolCollateralWei); @@ -302,7 +249,7 @@ interface IAssetManagerEvents { event RedemptionPaymentBlocked( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, bytes32 transactionHash, uint256 redemptionAmountUBA, int256 spentUnderlyingUBA); @@ -314,7 +261,7 @@ interface IAssetManagerEvents { event RedemptionPaymentFailed( address indexed agentVault, address indexed redeemer, - uint64 indexed requestId, + uint256 indexed requestId, bytes32 transactionHash, int256 spentUnderlyingUBA, string failureReason); @@ -325,7 +272,7 @@ interface IAssetManagerEvents { */ event RedemptionPoolFeeMinted( address indexed agentVault, - uint64 indexed requestId, + uint256 indexed requestId, uint256 poolFeeUBA); /** @@ -379,14 +326,6 @@ interface IAssetManagerEvents { address indexed agentVault, uint256 dustUBA); - /** - * Agent entered CCB (collateral call band) due to being on the border of unhealthy. - * Agent has limited time to topup the collateral, otherwise liquidation starts. - */ - event AgentInCCB( - address indexed agentVault, - uint256 timestamp); - /** * Agent entered liquidation state due to unhealthy position. * The liquidation ends when the agent is again healthy or the agent's position is fully liquidated. @@ -434,7 +373,7 @@ interface IAssetManagerEvents { */ event UnderlyingWithdrawalAnnounced( address indexed agentVault, - uint64 indexed announcementId, + uint256 indexed announcementId, bytes32 paymentReference); /** @@ -445,7 +384,7 @@ interface IAssetManagerEvents { */ event UnderlyingWithdrawalConfirmed( address indexed agentVault, - uint64 indexed announcementId, + uint256 indexed announcementId, int256 spentUBA, bytes32 transactionHash); @@ -456,7 +395,7 @@ interface IAssetManagerEvents { */ event UnderlyingWithdrawalCancelled( address indexed agentVault, - uint64 indexed announcementId); + uint256 indexed announcementId); /** * Emitted when the agent tops up the underlying address balance. @@ -542,17 +481,15 @@ interface IAssetManagerEvents { string assetFtsoSymbol, string tokenFtsoSymbol, uint256 minCollateralRatioBIPS, - uint256 ccbMinCollateralRatioBIPS, uint256 safetyMinCollateralRatioBIPS); /** - * System defined collateral ratios for the token have changed (minimal, CCB and safety collateral ratio). + * System defined collateral ratios for the token have changed (minimal and safety collateral ratio). */ event CollateralRatiosChanged( uint8 collateralClass, address collateralToken, uint256 minCollateralRatioBIPS, - uint256 ccbMinCollateralRatioBIPS, uint256 safetyMinCollateralRatioBIPS); /** diff --git a/src/songbird/IClaimSetupManager.sol b/src/songbird/IClaimSetupManager.sol index 384de98..17cc70c 100644 --- a/src/songbird/IClaimSetupManager.sol +++ b/src/songbird/IClaimSetupManager.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IDelegationAccount.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IClaimSetupManager { diff --git a/src/songbird/ICoreVaultClient.sol b/src/songbird/ICoreVaultClient.sol new file mode 100644 index 0000000..9340e57 --- /dev/null +++ b/src/songbird/ICoreVaultClient.sol @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {IPayment} from ".//IFdcVerification.sol"; + + +/** + * Core vault + */ +interface ICoreVaultClient { + /** + * Agent has requested transfer of (some of) their backing to the core vault. + */ + event TransferToCoreVaultStarted( + address indexed agentVault, + uint256 indexed transferRedemptionRequestId, + uint256 valueUBA); + + /** + * Agent has cancelled transfer to the core vault without paying. + * The amount of `valueUBA` has been re-minted./ + */ + event TransferToCoreVaultDefaulted( + address indexed agentVault, + uint256 indexed transferRedemptionRequestId, + uint256 remintedUBA); + + /** + * The transfer of underlying to the core vault was successfully completed. + */ + event TransferToCoreVaultSuccessful( + address indexed agentVault, + uint256 indexed transferRedemptionRequestId, + uint256 valueUBA); + + /** + * The agent has requested return of some of the underlying from the core vault to the agent's underlying address. + */ + event ReturnFromCoreVaultRequested( + address indexed agentVault, + uint256 indexed requestId, + bytes32 paymentReference, + uint256 valueUBA); + + /** + * The agent has cancelled the return request. + */ + event ReturnFromCoreVaultCancelled( + address indexed agentVault, + uint256 indexed requestId); + + /** + * The payment from core vault to the agent's underlying address has been confirmed. + */ + event ReturnFromCoreVaultConfirmed( + address indexed agentVault, + uint256 indexed requestId, + uint256 receivedUnderlyingUBA, + uint256 remintedUBA); + + /** + * Redemption was requested from a core vault. + * Can only be redeemed to a payment address from to the `allowedDestinations` list in the core vault manager. + */ + event CoreVaultRedemptionRequested( + address indexed redeemer, + string paymentAddress, + bytes32 paymentReference, + uint256 valueUBA, + uint256 feeUBA); + + /** + * Agent can transfer their backing to core vault. + * They then get a redemption requests which the owner pays just like any other redemption request. + * After that, the agent's collateral is released. + * NOTE: only agent vault owner can call + * @param _agentVault the agent vault address + * @param _amountUBA the amount to transfer to the core vault + */ + function transferToCoreVault(address _agentVault, uint256 _amountUBA) + external; + + /** + * Request that core vault transfers funds to the agent's underlying address, + * which makes them available for redemptions. This method reserves agent's collateral. + * This may be sent by an agent when redemptions dominate mintings, so that the agents + * are empty but want to earn from redemptions. + * NOTE: only agent vault owner can call + * NOTE: there can be only one active return request (until it is confirmed or cancelled). + * @param _agentVault the agent vault address + * @param _lots number of lots (same lots as for minting and redemptions) + */ + function requestReturnFromCoreVault(address _agentVault, uint256 _lots) + external; + + /** + * Before the return request is processed, it can be cancelled, releasing the agent's reserved collateral. + * @param _agentVault the agent vault address + */ + function cancelReturnFromCoreVault(address _agentVault) + external; + + /** + * Confirm the payment from core vault to the agent's underlying address. + * This adds the reserved funds to the agent's backing. + * @param _payment FDC payment proof + * @param _agentVault the agent vault address + */ + function confirmReturnFromCoreVault(IPayment.Proof calldata _payment, address _agentVault) + external; + + /** + * Directly redeem from core vault by a user holding FAssets. + * This is like ordinary redemption, but the redemption time is much longer (a day or more) + * and there is no possibility of redemption default. + * @param _lots the number of lots, must be larger than `coreVaultMinimumRedeemLots` setting + * @param _redeemerUnderlyingAddress the underlying address to which the assets will be redeemed; + * must have been added to the `allowedDestinations` list in the core vault manager by + * the governance before the redemption request. + */ + function redeemFromCoreVault(uint256 _lots, string memory _redeemerUnderlyingAddress) + external; + + /** + * Return the maximum amount that can be transferred and the minimum amount that + * has to remain on the agent vault's underlying address. + * @param _agentVault the agent vault address + * @return _maximumTransferUBA maximum amount that can be transferred + * @return _minimumLeftAmountUBA the minimum amount that has to remain on the agent vault's underlying address + * after the transfer + */ + function maximumTransferToCoreVault( + address _agentVault + ) external view + returns (uint256 _maximumTransferUBA, uint256 _minimumLeftAmountUBA); + + /** + * Returns the amount available on the core vault - this is the maximum amount that can be returned to agent or + * redeemed directly from the core vault. + * @return _immediatelyAvailableUBA the amount on the core vault operating account - returns and redemptions + * within this amount will be paid out quickly + * @return _totalAvailableUBA the total amount on the core vault, including all escrows + */ + function coreVaultAvailableAmount() + external view + returns (uint256 _immediatelyAvailableUBA, uint256 _totalAvailableUBA); +} diff --git a/src/songbird/ICoreVaultClientSettings.sol b/src/songbird/ICoreVaultClientSettings.sol new file mode 100644 index 0000000..c708303 --- /dev/null +++ b/src/songbird/ICoreVaultClientSettings.sol @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +/** + * Core vault settings + */ +interface ICoreVaultClientSettings { + function setCoreVaultManager(address _coreVaultManager) + external; + + function setCoreVaultNativeAddress(address payable _nativeAddress) + external; + + function setCoreVaultTransferTimeExtensionSeconds(uint256 _transferTimeExtensionSeconds) + external; + + function setCoreVaultRedemptionFeeBIPS(uint256 _redemptionFeeBIPS) + external; + + function setCoreVaultMinimumAmountLeftBIPS(uint256 _minimumAmountLeftBIPS) + external; + + function setCoreVaultMinimumRedeemLots(uint256 _minimumRedeemLots) + external; + + function getCoreVaultManager() + external view + returns (address); + + function getCoreVaultNativeAddress() + external view + returns (address); + + function getCoreVaultTransferTimeExtensionSeconds() + external view + returns (uint256); + + function getCoreVaultRedemptionFeeBIPS() + external view + returns (uint256); + + function getCoreVaultMinimumAmountLeftBIPS() + external view + returns (uint256); + + function getCoreVaultMinimumRedeemLots() + external view + returns (uint256); +} diff --git a/src/songbird/IDelegationAccount.sol b/src/songbird/IDelegationAccount.sol index 2093b99..815a909 100644 --- a/src/songbird/IDelegationAccount.sol +++ b/src/songbird/IDelegationAccount.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IClaimSetupManager.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDelegationAccount { diff --git a/src/songbird/IFdcVerification.sol b/src/songbird/IFdcVerification.sol index d7e51cd..b37662c 100644 --- a/src/songbird/IFdcVerification.sol +++ b/src/songbird/IFdcVerification.sol @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +import "./IRelay.sol"; import "./IAddressValidityVerification.sol"; import "./IBalanceDecreasingTransactionVerification.sol"; import "./IConfirmedBlockHeightExistsVerification.sol"; @@ -9,16 +10,25 @@ import "./IPaymentVerification.sol"; import "./IReferencedPaymentNonexistenceVerification.sol"; import "./IWeb2JsonVerification.sol"; - /** * FdcVerification interface. */ interface IFdcVerification is - IAddressValidityVerification, - IBalanceDecreasingTransactionVerification, - IConfirmedBlockHeightExistsVerification, - IEVMTransactionVerification, - IPaymentVerification, - IReferencedPaymentNonexistenceVerification, - IWeb2JsonVerification -{ } + IAddressValidityVerification, + IBalanceDecreasingTransactionVerification, + IConfirmedBlockHeightExistsVerification, + IEVMTransactionVerification, + IPaymentVerification, + IReferencedPaymentNonexistenceVerification, + IWeb2JsonVerification +{ + /** + * The FDC protocol id. + */ + function fdcProtocolId() external view returns (uint8 _fdcProtocolId); + + /** + * Relay contract address. + */ + function relay() external view returns (IRelay); +} diff --git a/src/songbird/IFtsoManager.sol b/src/songbird/IFtsoManager.sol index ed1c4c0..cfc7cc5 100644 --- a/src/songbird/IFtsoManager.sol +++ b/src/songbird/IFtsoManager.sol @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./ftso/interface/IIFtso.sol"; -import "./genesis/interface/IFtsoManagerGenesis.sol"; +import "./ftso/interfaces/IIFtso.sol"; +import "./genesis/interfaces/IFtsoManagerGenesis.sol"; interface IFtsoManager is IFtsoManagerGenesis { diff --git a/src/songbird/IFtsoRegistry.sol b/src/songbird/IFtsoRegistry.sol index f9d8c6a..46ab964 100644 --- a/src/songbird/IFtsoRegistry.sol +++ b/src/songbird/IFtsoRegistry.sol @@ -2,8 +2,8 @@ pragma solidity >=0.7.6 <0.9; pragma abicoder v2; -import "./ftso/interface/IIFtso.sol"; -import "./genesis/interface/IFtsoRegistryGenesis.sol"; +import "./ftso/interfaces/IIFtso.sol"; +import "./genesis/interfaces/IFtsoRegistryGenesis.sol"; interface IFtsoRegistry is IFtsoRegistryGenesis { diff --git a/src/songbird/IGovernor.sol b/src/songbird/IGovernor.sol index 48bdd0f..fff729f 100644 --- a/src/songbird/IGovernor.sol +++ b/src/songbird/IGovernor.sol @@ -1,14 +1,12 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; -/** - * Governor interface. - */ interface IGovernor { struct GovernorSettings { bool accept; - uint256 votingStartTs; + uint256 votingDelaySeconds; uint256 votingPeriodSeconds; uint256 vpBlockPeriodSeconds; uint256 thresholdConditionBIPS; @@ -18,15 +16,7 @@ interface IGovernor { } /** - * Enum describing a proposal state. - - * A proposal is: - * * `Pending` when first created, - * * `Active` when it’s being voted on, - * * `Defeated` or `Succeeded` as a result of the vote, - * * `Queued` when in the process of executing, - * * `Expired` when it times out or fails to execute upon a certain date, and - * * `Executed` when it goes live. + * @notice Enum describing a proposal state */ enum ProposalState { Pending, @@ -40,7 +30,7 @@ interface IGovernor { } /** - * Event emitted when a proposal is created. + * @notice Event emitted when a proposal is created */ event ProposalCreated( uint256 indexed proposalId, @@ -59,17 +49,17 @@ interface IGovernor { ); /** - * Event emitted when a proposal is canceled. + * @notice Event emitted when a proposal is canceled */ event ProposalCanceled(uint256 indexed proposalId); /** - * Event emitted when a proposal is executed. + * @notice Event emitted when a proposal is executed */ event ProposalExecuted(uint256 indexed proposalId); /** - * Event emitted when a vote is cast. + * @notice Event emitted when a vote is cast */ event VoteCast( address indexed voter, @@ -80,30 +70,30 @@ interface IGovernor { uint256 forVotePower, uint256 againstVotePower ); - + /** - * Cancels a proposal. - * @param _proposalId Unique identifier obtained by hashing proposal data. - * Emits a ProposalCanceled event + * @notice Cancels a proposal + * @param _proposalId Unique identifier obtained by hashing proposal data + * @notice Emits a ProposalCanceled event */ function cancel(uint256 _proposalId) external; /** - * Casts a vote on a proposal. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @return Vote power of the cast vote. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @return Vote power of the cast vote + * @notice Emits a VoteCast event */ function castVote(uint256 _proposalId, uint8 _support) external returns (uint256); /** - * Casts a vote on a proposal with a reason. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @param _reason Vote reason. - * @return Vote power of the cast vote. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal with a reason + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @param _reason Vote reason + * @return Vote power of the cast vote + * @notice Emits a VoteCast event */ function castVoteWithReason( uint256 _proposalId, @@ -112,13 +102,13 @@ interface IGovernor { ) external returns (uint256); /** - * Casts a vote on a proposal using the user cryptographic signature. - * @param _proposalId Id of the proposal. - * @param _support A value indicating vote type (against, for). - * @param _v v part of the signature. - * @param _r r part of the signature. - * @param _s s part of the signature. - * Emits a VoteCast event. + * @notice Casts a vote on a proposal using the user cryptographic signature + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @param _v v part of the signature + * @param _r r part of the signature + * @param _s s part of the signature + * @notice Emits a VoteCast event */ function castVoteBySig( uint256 _proposalId, @@ -129,84 +119,63 @@ interface IGovernor { ) external returns (uint256); /** - * Executes a successful proposal without execution parameters. - * @param _proposalId Id of the proposal. - * Emits a ProposalExecuted event. + * @notice Executes a successful proposal without execution parameters + * @param _description String description of the proposal + * @notice Emits a ProposalExecuted event */ - function execute(uint256 _proposalId) external; + function execute(string memory _description) external returns (uint256); /** - * Executes a successful proposal. - * @param _proposalId Id of the proposal. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * Emits a ProposalExecuted event. + * @notice Executes a successful proposal with execution parameters + * @param _targets Array of target addresses on which the calls are to be invoked + * @param _values Array of values with which the calls are to be invoked + * @param _calldatas Array of call data to be invoked + * @param _description String description of the proposal + * @notice Emits a ProposalExecuted event */ function execute( - uint256 _proposalId, address[] memory _targets, uint256[] memory _values, - bytes[] memory _calldatas - ) external payable; + bytes[] memory _calldatas, + string memory _description + ) external payable returns (uint256); /** - * Returns the current state of a proposal. - * @param _proposalId Id of the proposal. - * @return ProposalState enum. + * @notice Returns the current state of a proposal + * @param _proposalId Id of the proposal + * @return ProposalState enum */ function state(uint256 _proposalId) external view returns (ProposalState); /** - * Returns the vote power of a voter at a specific block number. - * @param _voter Address of the voter. - * @param _blockNumber The block number. - * @return Vote power of the voter at the block number. + * @notice Returns the vote power of a voter at a specific block number + * @param _voter Address of the voter + * @param _blockNumber The block number + * @return Vote power of the voter at the block number */ function getVotes(address _voter, uint256 _blockNumber) external view returns (uint256); /** - * Returns information if a voter has cast a vote on a specific proposal. - * @param _proposalId Id of the proposal. - * @param _voter Address of the voter. - * @return True if the voter has cast a vote on the proposal, and false otherwise. + * @notice Returns information if a voter has cast a vote on a specific proposal + * @param _proposalId Id of the proposal + * @param _voter Address of the voter + * @return True if the voter has cast a vote on the proposal, and false otherwise */ function hasVoted(uint256 _proposalId, address _voter) external view returns (bool); /** - * Returns proposal id determined by hashing proposal data. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * @param _description Description of the proposal. - * @return Proposal id. - */ - function getProposalId( - address[] memory _targets, - uint256[] memory _values, - bytes[] memory _calldatas, - string memory _description - ) external view returns (uint256); - - /** - * Returns the list of proposal ids. - */ - function getProposalIds() external view returns (uint256[] memory); - - /** - * Returns information of the specified proposal. - * @param _proposalId Id of the proposal. - * @return _proposer Address of the proposal submitter. - * @return _accept Type of the proposal - accept or reject. - * @return _votePowerBlock Block number used to determine the vote powers in voting process. - * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting. - * @return _voteEndTime End time (in seconds from epoch) of the proposal voting. - * @return _execStartTime Start time (in seconds from epoch) of the proposal execution window. - * @return _execEndTime End time (in seconds from epoch) of the proposal exectuion window. - * @return _thresholdConditionBIPS Percentage in BIPS of the total vote power required for proposal "quorum". - * @return _majorityConditionBIPS Percentage in BIPS of the proper relation between FOR and AGAINST votes. - * @return _circulatingSupply Circulating supply at votePowerBlock. - * @return _description Description of the proposal. + * @notice Returns information of the specified proposal + * @param _proposalId Id of the proposal + * @return _proposer Address of the proposal submitter + * @return _accept Type of the proposal - accept or reject + * @return _votePowerBlock Block number used to determine the vote powers in voting process + * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting + * @return _voteEndTime End time (in seconds from epoch) of the proposal voting + * @return _execStartTime Start time (in seconds from epoch) of the proposal execution window + * @return _execEndTime End time (in seconds from epoch) of the proposal exectuion window + * @return _thresholdConditionBIPS Percentage in BIPS of the total vote power required for proposal "quorum" + * @return _majorityConditionBIPS Percentage in BIPS of the proper relation between FOR and AGAINST votes + * @return _circulatingSupply Circulating supply at votePowerBlock */ function getProposalInfo( uint256 _proposalId @@ -222,20 +191,19 @@ interface IGovernor { uint256 _execEndTime, uint256 _thresholdConditionBIPS, uint256 _majorityConditionBIPS, - uint256 _circulatingSupply, - string memory _description + uint256 _circulatingSupply ); /** - * Returns votes (for, against) of the specified proposal. - * @param _proposalId Id of the proposal. - * @return _for Accumulated vote power for the proposal. - * @return _against Accumulated vote power against the proposal. + * @notice Returns votes (for, against) of the specified proposal + * @param _proposalId Id of the proposal + * @return _for Accumulated vote power for the proposal + * @return _against Accumulated vote power against the proposal */ function getProposalVotes( uint256 _proposalId ) - external view + external view returns ( uint256 _for, uint256 _against diff --git a/src/songbird/IPollingFtso.sol b/src/songbird/IPollingFtso.sol new file mode 100644 index 0000000..7bbf313 --- /dev/null +++ b/src/songbird/IPollingFtso.sol @@ -0,0 +1,295 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IPollingFtso { + + /** + * @notice Struct holding the information about proposal properties + */ + struct Proposal { + string description; // description of the proposal + address proposer; // address of the proposer + bool canceled; // flag indicating if proposal has been canceled + uint256 voteStartTime; // start time of voting window (in seconds from epoch) + uint256 voteEndTime; // end time of voting window (in seconds from epoch) + uint256 thresholdConditionBIPS; // percentage in BIPS of the total vote power required for proposal "quorum" + uint256 majorityConditionBIPS; // percentage in BIPS of the proper relation between FOR and AGAINST votes + mapping(address => bool) isEligible; // flag if an address is eligible to cast a vote in a proposal + uint256 noOfEligibleMembers; // number of addresses that can vote in the proposal + } + + /** + * @notice Struct holding the information about proposal voting + */ + struct ProposalVoting { + uint256 againstVotePower; // accumulated vote power against the proposal + uint256 forVotePower; // accumulated vote power for the proposal + mapping(address => bool) hasVoted; // flag if a voter has cast a vote + } + + /** + * @notice Enum describing a proposal state + */ + enum ProposalState { + Canceled, + Pending, + Active, + Defeated, + Succeeded + } + + /** + * @notice Enum that determines vote (support) type + * @dev 0 = Against, 1 = For + */ + enum VoteType { + Against, + For + } + + /** + * @notice Event emitted when a proposal is created + */ + event FtsoProposalCreated( + uint256 indexed proposalId, + address proposer, + string description, + uint256 voteStartTime, + uint256 voteEndTime, + uint256 thresholdConditionBIPS, + uint256 majorityConditionBIPS, + address[] eligibleMembers + ); + + /** + * @notice Event emitted when a vote is cast + */ + event VoteCast( + address indexed voter, + uint256 indexed proposalId, + uint8 support, + uint256 forVotePower, + uint256 againstVotePower + ); + + /** + * @notice Event emitted when a proposal is canceled + */ + event ProposalCanceled(uint256 indexed proposalId); + + /** + * @notice Event emitted when parameters are set + */ + event ParametersSet( + uint256 votingDelaySeconds, + uint256 votingPeriodSeconds, + uint256 thresholdConditionBIPS, + uint256 majorityConditionBIPS, + uint256 proposalFeeValueWei, + uint256 addAfterRewardedEpochs, + uint256 addAfterNotChilledEpochs, + uint256 removeAfterNotRewardedEpochs, + uint256 removeAfterEligibleProposals, + uint256 removeAfterNonParticipatingProposals, + uint256 removeForDays + ); + + /** + * @notice Event emitted when management group member is added + */ + event ManagementGroupMemberAdded(address addedMember); + + /** + * @notice Event emitted when management group member is removed + */ + event ManagementGroupMemberRemoved(address removedMember); + + /** + * @notice Event emitted when maintainer is set + */ + event MaintainerSet(address newMaintainer); + + /** + * @notice Event emitted when proxy voter is set + */ + event ProxyVoterSet(address account, address proxyVoter); + + /** + * @notice Sets (or changes) contract's parameters. It is called after deployment of the contract + * and every time one of the parameters changes. + */ + function setParameters( + uint256 _votingDelaySeconds, + uint256 _votingPeriodSeconds, + uint256 _thresholdConditionBIPS, + uint256 _majorityConditionBIPS, + uint256 _proposalFeeValueWei, + uint256 _addAfterRewardedEpochs, + uint256 _addAfterNotChilledEpochs, + uint256 _removeAfterNotRewardedEpochs, + uint256 _removeAfterEligibleProposals, + uint256 _removeAfterNonParticipatingProposals, + uint256 _removeForDays + ) + external; + + /** + * @notice Cancels an existing proposal + * @param _proposalId Unique identifier of a proposal + * @notice Emits a ProposalCanceled event + */ + function cancel(uint256 _proposalId) external; + + /** + * @notice Creates a new proposal + * @param _description String description of the proposal + * @return _proposalId Unique identifier of the proposal + * @notice Emits a FtsoProposalCreated event + */ + function propose( + string memory _description + ) external payable returns (uint256); + + /** + * @notice Casts a vote on a proposal + * @param _proposalId Id of the proposal + * @param _support A value indicating vote type (against, for) + * @notice Emits a VoteCast event + */ + function castVote(uint256 _proposalId, uint8 _support) external; + + /** + * @notice Changes list of management group members + * @param _providersToAdd Array of addresses to add to the list + * @param _providersToRemove Array of addresses to remove from the list + * @notice This operation can only be performed through a maintainer + * (mostly used for manually adding KYCed providers) + */ + function changeManagementGroupMembers( + address[] memory _providersToAdd, + address[] memory _providersToRemove + ) external; + + /** + * @notice Sets a proxy voter for data provider (i.e. address that can vote in his name) + * @param _proxyVoter Address to register as a proxy (use address(0) to remove proxy) + * @notice Emits a ProxyVoterSet event + */ + function setProxyVoter(address _proxyVoter) external; + + /** + * @notice Adds msg.sender to the management group + */ + function addMember() external; + + /** + * @notice Removes member from the management group + * @param _account Account to remove from the management group + */ + function removeMember(address _account) external; + + /** + * @notice Returns the current state of a proposal + * @param _proposalId Id of the proposal + * @return ProposalState enum + */ + function state(uint256 _proposalId) external view returns (ProposalState); + + /** + * @notice Returns whether a voter has cast a vote on a specific proposal + * @param _proposalId Id of the proposal + * @param _voter Address of the voter + * @return True if the voter has cast a vote on the proposal, and false otherwise + */ + function hasVoted(uint256 _proposalId, address _voter) external view returns (bool); + + /** + * @notice Returns information about the specified proposal + * @param _proposalId Id of the proposal + * @return _description Description of the proposal + * @return _proposer Address of the proposal submitter + * @return _voteStartTime Start time (in seconds from epoch) of the proposal voting + * @return _voteEndTime End time (in seconds from epoch) of the proposal voting + * @return _thresholdConditionBIPS Total number of cast votes, as a percentage in BIPS of the + total vote power, required for the proposal to pass (quorum) + * @return _majorityConditionBIPS Number of FOR votes, as a percentage in BIPS of the + total cast votes, requires for the proposal to pass + * @return _noOfEligibleMembers Number of members that are eligible to vote in the specified proposal + */ + function getProposalInfo( + uint256 _proposalId + ) + external view + returns ( + string memory _description, + address _proposer, + uint256 _voteStartTime, + uint256 _voteEndTime, + uint256 _thresholdConditionBIPS, + uint256 _majorityConditionBIPS, + uint256 _noOfEligibleMembers + ); + + /** + * @notice Returns the description string that was supplied when the specified proposal was created + * @param _proposalId Id of the proposal + * @return _description Description of the proposal + */ + function getProposalDescription(uint256 _proposalId) external view + returns (string memory _description); + + /** + * @notice Returns id and description of the last created proposal + * @return _proposalId Id of the last proposal + * @return _description Description of the last proposal + */ + function getLastProposal() external view + returns ( uint256 _proposalId, string memory _description); + + /** + * @notice Returns number of votes for and against the specified proposal + * @param _proposalId Id of the proposal + * @return _for Accumulated vote power for the proposal + * @return _against Accumulated vote power against the proposal + */ + function getProposalVotes( + uint256 _proposalId + ) + external view + returns ( + uint256 _for, + uint256 _against + ); + + /** + * @notice Returns list of current management group members + * @return _list List of management group members + */ + function getManagementGroupMembers() external view returns (address[] memory _list); + + /** + * @notice Returns whether an account can create proposals + * @notice An address can make proposals if it is a member of the management group, + * one of their proxies or the maintainer of the contract + * @param _account Address of a queried account + * @return True if a queried account can propose, false otherwise + */ + function canPropose(address _account) external view returns (bool); + + /** + * @notice Returns whether an account can vote for a given proposal + * @param _account Address of the queried account + * @param _proposalId Id of the queried proposal + * @return True if account is eligible to vote, and false otherwise + */ + function canVote(address _account, uint256 _proposalId) external view returns (bool); + + /** + * @notice Returns whether an account is member of the management group + * @param _account Address of the queried account + * @return True if the queried account is member, false otherwise + */ + function isMember(address _account) external view returns (bool); +} diff --git a/src/songbird/IPriceSubmitter.sol b/src/songbird/IPriceSubmitter.sol index 781735f..1e6ebd1 100644 --- a/src/songbird/IPriceSubmitter.sol +++ b/src/songbird/IPriceSubmitter.sol @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./genesis/interface/IFtsoGenesis.sol"; -import "./genesis/interface/IFtsoRegistryGenesis.sol"; +import "./genesis/interfaces/IFtsoGenesis.sol"; +import "./genesis/interfaces/IFtsoRegistryGenesis.sol"; interface IPriceSubmitter { /** diff --git a/src/songbird/IRNat.sol b/src/songbird/IRNat.sol index b710fd2..76bf5bc 100644 --- a/src/songbird/IRNat.sol +++ b/src/songbird/IRNat.sol @@ -3,7 +3,7 @@ pragma solidity >=0.7.6 <0.9; import "./IRNatAccount.sol"; import "./IWNat.sol"; -import "@openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol"; +import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IRNat is IERC20Metadata { diff --git a/src/songbird/IRNatAccount.sol b/src/songbird/IRNatAccount.sol index d8c465d..fea1340 100644 --- a/src/songbird/IRNatAccount.sol +++ b/src/songbird/IRNatAccount.sol @@ -2,7 +2,7 @@ pragma solidity >=0.7.6 <0.9; import "./IRNat.sol"; -import "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRNatAccount { diff --git a/src/songbird/ITransferFees.sol b/src/songbird/ITransferFees.sol deleted file mode 100644 index bdbbb1d..0000000 --- a/src/songbird/ITransferFees.sol +++ /dev/null @@ -1,115 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity >=0.7.6 <0.9; - - -/** - * FAsset transfer (trailing) fees. - */ -interface ITransferFees { - /** - * An agent has claimed their share of transfer fees. - */ - event TransferFeesClaimed( - address indexed agentVault, - address recipient, - uint256 agentClaimedUBA, - uint256 poolClaimedUBA, - uint256 remainingUnclaimedEpochs); - - /** - * Transfer fee will change at timestamp `scheduledAt`. - */ - event TransferFeeChangeScheduled( - uint256 nextTransferFeeMillionths, - uint256 scheduledAt); - - /** - * Claim FAsset transfer fees by an agent. - * NOTE: may only be called by the agent vault owner - * @param _agentVault the agent vault for which to claim - * @param _recipient the account that will receive agent's share of fasset fees - * @param _maxEpochsToClaim limit the number of epochs to claim, to avoid using too much gas - * @return _agentClaimedUBA agent's share of total claimed amount in FAsset UBA - * @return _poolClaimedUBA pool share of total claimed amount in FAsset UBA - * @return _remainingUnclaimedEpochs nonzero when _maxEpochsToClaim is smaller then the number of unclaimed epochs - */ - function claimTransferFees(address _agentVault, address _recipient, uint256 _maxEpochsToClaim) - external - returns (uint256 _agentClaimedUBA, uint256 _poolClaimedUBA, uint256 _remainingUnclaimedEpochs); - - function currentTransferFeeEpoch() - external view - returns (uint256); - - function firstClaimableTransferFeeEpoch() - external view - returns (uint256); - - function agentUnclaimedTransferFeeEpochs(address _agentVault) - external view - returns (uint256 _first, uint256 _count); - - function agentTransferFeeShare(address _agentVault, uint256 _maxEpochsToClaim) - external view - returns (uint256 _feeShareUBA); - - function agentTransferFeeShareForEpoch(address _agentVault, uint256 _epoch) - external view - returns (uint256); - - function transferFeeMillionths() - external view - returns (uint256); - - function setTransferFeeMillionths(uint256 _value, uint256 _scheduledAt) - external; - - //////////////////////////////////////////////////////////////////////////////////// - // Internal methods - - function fassetTransferFeePaid(uint256 _fee) - external; - - function initAgentsMintingHistory(address[] calldata _agentVaults) - external; - - //////////////////////////////////////////////////////////////////////////////////// - // Methods for testing and inspection - - struct TransferFeeSettings { - uint256 transferFeeMillionths; - uint256 firstEpochStartTs; - uint256 epochDuration; - uint256 maxUnexpiredEpochs; - uint256 firstClaimableEpoch; - } - - struct TransferFeeEpochData { - uint256 startTs; - uint256 endTs; - uint256 totalFees; - uint256 claimedFees; - bool claimable; - bool expired; - } - - struct TransferFeeCalculationDataForAgent { - uint256 totalFees; - uint256 cumulativeMinted; - uint256 totalCumulativeMinted; - bool claimable; - bool claimed; - } - - function transferFeeSettings() - external view - returns (TransferFeeSettings memory); - - function transferFeeEpochData(uint256 _epoch) - external view - returns (TransferFeeEpochData memory); - - function transferFeeCalculationDataForAgent(address _agentVault, uint256 _epoch) - external view - returns (TransferFeeCalculationDataForAgent memory); -} diff --git a/src/songbird/IVPToken.sol b/src/songbird/IVPToken.sol index c9cf5b2..21593c0 100644 --- a/src/songbird/IVPToken.sol +++ b/src/songbird/IVPToken.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import {IERC20} from "@openzeppelin-contracts/token/ERC20/IERC20.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IGovernanceVotePower} from "./IGovernanceVotePower.sol"; import {IVPContractEvents} from "./IVPContractEvents.sol"; diff --git a/src/songbird/IVoterPreRegistry.sol b/src/songbird/IVoterPreRegistry.sol index c7d09c9..6e0a524 100644 --- a/src/songbird/IVoterPreRegistry.sol +++ b/src/songbird/IVoterPreRegistry.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./protocol/interface/IIVoterRegistry.sol"; +import "./protocol/interfaces/IIVoterRegistry.sol"; interface IVoterPreRegistry { diff --git a/src/songbird/IWNat.sol b/src/songbird/IWNat.sol index ade3c7a..59cee8e 100644 --- a/src/songbird/IWNat.sol +++ b/src/songbird/IWNat.sol @@ -1,42 +1,34 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "./IVPToken.sol"; -import "./token/interface/IICleanable.sol"; - - -/** - * @title Wrapped Native token - * Accept native token deposits and mint ERC20 WNAT (wrapped native) tokens 1-1. - */ -interface IWNat is IVPToken, IICleanable { +interface IWNat { /** - * Deposit Native and mint wNat ERC20. + * @notice Deposit native token and mint WNAT ERC20. */ function deposit() external payable; /** - * Deposit Native from msg.sender and mints WNAT ERC20 to recipient address. - * @param recipient An address to receive minted WNAT. + * @notice Withdraw native token and burn WNAT ERC20. + * @param _amount The amount to withdraw. */ - function depositTo(address recipient) external payable; - + function withdraw(uint256 _amount) external; + /** - * Withdraw Native and burn WNAT ERC20. - * @param amount The amount to withdraw. + * @notice Deposit native token from msg.sender and mint WNAT ERC20. + * @param _recipient An address to receive minted WNAT. */ - function withdraw(uint256 amount) external; - + function depositTo(address _recipient) external payable; + /** - * Withdraw WNAT from an owner and send native tokens to msg.sender given an allowance. - * @param owner An address spending the Native tokens. - * @param amount The amount to spend. + * @notice Withdraw WNAT from an owner and send NAT to msg.sender given an allowance. + * @param _owner An address spending the native tokens. + * @param _amount The amount to spend. * * Requirements: * - * - `owner` must have a balance of at least `amount`. - * - the caller must have allowance for `owners`'s tokens of at least - * `amount`. + * - `_owner` must have a balance of at least `_amount`. + * - the caller must have allowance for `_owners`'s tokens of at least + * `_amount`. */ - function withdrawFrom(address owner, uint256 amount) external; + function withdrawFrom(address _owner, uint256 _amount) external; } diff --git a/src/songbird/IWeb2JsonVerification.sol b/src/songbird/IWeb2JsonVerification.sol index 8369e1a..d0a5d25 100644 --- a/src/songbird/IWeb2JsonVerification.sol +++ b/src/songbird/IWeb2JsonVerification.sol @@ -4,5 +4,5 @@ pragma solidity >=0.7.6 <0.9; import "./IWeb2Json.sol"; interface IWeb2JsonVerification { - function verifyJsonApi(IWeb2Json.Proof calldata _proof) external view returns (bool _proved); + function verifyWeb2Json(IWeb2Json.Proof calldata _proof) external view returns (bool _proved); } diff --git a/src/songbird/addressUpdater/interfaces/IIAddressUpdatable.sol b/src/songbird/addressUpdater/interfaces/IIAddressUpdatable.sol new file mode 100644 index 0000000..e8bd84e --- /dev/null +++ b/src/songbird/addressUpdater/interfaces/IIAddressUpdatable.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IIAddressUpdatable { + /** + * @notice Updates contract addresses - should be called only from AddressUpdater contract + * @param _contractNameHashes list of keccak256(abi.encode(...)) contract names + * @param _contractAddresses list of contract addresses corresponding to the contract names + */ + function updateContractAddresses( + bytes32[] memory _contractNameHashes, + address[] memory _contractAddresses + ) external; +} diff --git a/src/songbird/addressUpdater/interfaces/IIAddressUpdater.sol b/src/songbird/addressUpdater/interfaces/IIAddressUpdater.sol new file mode 100644 index 0000000..9973368 --- /dev/null +++ b/src/songbird/addressUpdater/interfaces/IIAddressUpdater.sol @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IIAddressUpdater { + + /** + * @notice Returns all contract names and corresponding addresses + */ + function getContractNamesAndAddresses() external view returns( + string[] memory _contractNames, + address[] memory _contractAddresses + ); + + /** + * @notice Returns contract address for the given name - might be address(0) + * @param _name name of the contract + */ + function getContractAddress(string calldata _name) external view returns(address); + + /** + * @notice Returns contract address for the given name hash - might be address(0) + * @param _nameHash hash of the contract name (keccak256(abi.encode(name)) + */ + function getContractAddressByHash(bytes32 _nameHash) external view returns(address); + + /** + * @notice Returns contract addresses for the given names - might be address(0) + * @param _names names of the contracts + */ + function getContractAddresses(string[] calldata _names) external view returns(address[] memory); + + /** + * @notice Returns contract addresses for the given name hashes - might be address(0) + * @param _nameHashes hashes of the contract names (keccak256(abi.encode(name)) + */ + function getContractAddressesByHash(bytes32[] calldata _nameHashes) external view returns(address[] memory); +} diff --git a/src/songbird/assetRegistry/interfaces/IIERC20WithMetadata.sol b/src/songbird/assetRegistry/interfaces/IIERC20WithMetadata.sol new file mode 100644 index 0000000..68a9631 --- /dev/null +++ b/src/songbird/assetRegistry/interfaces/IIERC20WithMetadata.sol @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + + +/** + * The methods of this interface are optional in ERC20 standard, so they are left out of IERC20 interface. + * However, any sane implementation includes them, and they are mandatory for the tokens in FlareAssetRegistry. + */ +interface IIERC20WithMetadata is IERC20 { + /** + * Returns the name of the token. + */ + function name() external view returns (string memory); + + /** + * Returns the symbol of the token, usually a shorter version of the name. + */ + function symbol() external view returns (string memory); + + /** + * Returns the number of decimals used to get its user representation. + * For example, if `decimals` equals `2`, a balance of `505` tokens should + * be displayed to a user as `5,05` (`505 / 10 ** 2`). + * + * Tokens usually opt for a value of 18, imitating the relationship between + * Ether and Wei. + * + * NOTE: This information is only used for _display_ purposes: the methods + * of the contract should always work with the smallest unit (e.g. wei). + */ + function decimals() external view returns (uint8); +} diff --git a/src/songbird/assetRegistry/interfaces/IIFlareAssetRegistry.sol b/src/songbird/assetRegistry/interfaces/IIFlareAssetRegistry.sol new file mode 100644 index 0000000..daa0284 --- /dev/null +++ b/src/songbird/assetRegistry/interfaces/IIFlareAssetRegistry.sol @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../IFlareAssetRegistry.sol"; + + +interface IIFlareAssetRegistry is IFlareAssetRegistry { + /** + * Allows a provider contract to register assets. + * @param _provider address of the provider (a contract implementing IIFlareAssetRegistryProvider) + * @param _registerAssets if true, all the assets held by the provider are immediately registered; + * should usually be true, but can be false to avoid unbounded work in some cases + * @dev Only governance can call. + */ + function registerProvider(address _provider, bool _registerAssets) external; + + /** + * Remove the provider contract from known providers (e.g. when a new version of the provider is deployed, the + * old one will be removed). + * @param _provider address of the provider (a contract implementing IIFlareAssetRegistryProvider) + * @param _unregisterAssets if true, all the assets belonging to the provider are automatically unregistered; + * should usually be true, but can be false to avoid unbounded work in some cases - in this case, + * all the assets must be unregistered before calling this method + * @dev Only governance can call. + */ + function unregisterProvider(address _provider, bool _unregisterAssets) external; + + /** + * Unregisters and re-registers all the assets belonging to the given provider. + * @param _provider address of the provider (a contract implementing IIFlareAssetRegistryProvider) + * @dev Only governance can call (without timelock). + */ + function refreshProviderAssets(address _provider) external; + + /** + * Register a new asset. + * @param _token address of the asset (a contract implementing IERC20 interface with implemented symbol()) + * @dev Can only be called by a registered provider. + */ + function registerAsset(address _token) external; + + /** + * Unregister an asset. + * @param _token address of the asset (a contract implementing IERC20 interface with implemented symbol()) + * @dev Can only be called by the provider which registered the token. + */ + function unregisterAsset(address _token) external; +} diff --git a/src/songbird/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol b/src/songbird/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol new file mode 100644 index 0000000..6d9cde2 --- /dev/null +++ b/src/songbird/assetRegistry/interfaces/IIFlareAssetRegistryProvider.sol @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + + +interface IIFlareAssetRegistryProvider { + /** + * Returns a unique hash identifying this provider and its assets. + */ + function assetType() external view returns (bytes32); + + /** + * @notice Returns the addresses of all Flare Assets + */ + function allAssets() external view returns (address[] memory); + + /** + * @notice Returns a generic asset attribute value. + * @param _token The token's address + * @param _nameHash attributes name's hash + * @return _defined true if the attribute is defined for this token + * @return _value attribute value, may have to be cast into some other type + */ + function getAttribute(address _token, bytes32 _nameHash) external view returns (bool _defined, bytes32 _value); + +} diff --git a/src/songbird/customFeeds/interface/IICustomFeed.sol b/src/songbird/customFeeds/interfaces/IICustomFeed.sol similarity index 100% rename from src/songbird/customFeeds/interface/IICustomFeed.sol rename to src/songbird/customFeeds/interfaces/IICustomFeed.sol diff --git a/src/songbird/data/AgentInfo.sol b/src/songbird/data/AgentInfo.sol new file mode 100644 index 0000000..d105789 --- /dev/null +++ b/src/songbird/data/AgentInfo.sol @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +library AgentInfo { + enum Status { + // agent is operating normally + NORMAL, + // liquidation due to collateral ratio - ends when agent is healthy + LIQUIDATION, + // illegal payment liquidation - always liquidates all and then agent must close vault + FULL_LIQUIDATION, + // agent announced destroy, cannot mint again; all existing mintings have been redeemed before + DESTROYING, + // agent has been destroyed, cannot do anything except return info + // owner can still withdraw tokens from the vault + DESTROYED + } + + struct Info { + // Current agent's status. + AgentInfo.Status status; + // Agent vault owner's management address, used for occasional administration. + // Immutable. + address ownerManagementAddress; + // Agent vault owner's work address, used for automatic operations. + // Can be changed by a call from the owner's management address. + address ownerWorkAddress; + // Agent's collateral pool address + address collateralPool; + // Agent collateral pool's pool token address + address collateralPoolToken; + // Underlying address as string - to be used for minting payments. + // For most other purposes, you use underlyingAddressHash, which is `keccak256(underlyingAddressString)`. + string underlyingAddressString; + // If true, anybody can mint against this agent. + // If false, the agent can only self-mint. + // Once minted, all redemption tickets go to the same (public) queue, regardless of this flag. + bool publiclyAvailable; + // Current fee the agent charges for minting (paid in underlying currency). + uint256 feeBIPS; + // Share of the minting fee that goes to the pool as percentage of the minting fee. + // This share of fee is minted as f-assets and belongs to the pool. + uint256 poolFeeShareBIPS; + // The token identifier of the agent's current vault collateral. + // Token identifier can be used to call AssetManager.getCollateralType(). + IERC20 vaultCollateralToken; + // Amount, set by agent, at which locked and free collateral are calculated for new mintings. + // For agent's vault collateral. + uint256 mintingVaultCollateralRatioBIPS; + // Amount, set by agent, at which locked and free collateral are calculated for new mintings. + // For pool collateral. + uint256 mintingPoolCollateralRatioBIPS; + // The maximum number of lots that the agent can mint. + // This can change any moment due to minting, redemption or price changes. + uint256 freeCollateralLots; + // Total amount of vault collateral in agent's vault. + uint256 totalVaultCollateralWei; + // Free collateral, available for new mintings. + // Note: this value doesn't tell you anything about agent being near liquidation, since it is + // calculated at agentMinCollateralRatio, not minCollateralRatio. + // Use collateralRatioBIPS to see whether the agent is near liquidation. + uint256 freeVaultCollateralWei; + // The actual agent's collateral ratio, as it is used in liquidation. + // For calculation, the system checks both FTSO prices and trusted provider's prices and uses + // the ones that give higher ratio. + uint256 vaultCollateralRatioBIPS; + // The token identifier of the agent's current vault collateral. + // Token identifier can be used to call AssetManager.getCollateralType(). + IERC20 poolWNatToken; + // Total amount of NAT collateral in agent's pool. + uint256 totalPoolCollateralNATWei; + // Free NAT pool collateral (see vault collateral for details). + uint256 freePoolCollateralNATWei; + // The actual pool collateral ratio (see vault collateral for details). + uint256 poolCollateralRatioBIPS; + // The amount of pool tokens that belong to agent's vault. This limits the amount of possible + // minting: to be able to mint, the NAT value of all backed fassets together with new ones, times + // mintingPoolHoldingsRequiredBIPS, must be smaller than the agent's pool tokens amount converted to NAT. + // Note: the amount of agent's pool tokens only affects minting, not liquidation. + uint256 totalAgentPoolTokensWei; + // The amount of vault collateral that will be withdrawn by the agent. + uint256 announcedVaultCollateralWithdrawalWei; + // The amount of pool tokens that will be withdrawn by the agent. + uint256 announcedPoolTokensWithdrawalWei; + // Free agent's pool tokens. + uint256 freeAgentPoolTokensWei; + // Total amount of minted f-assets. + uint256 mintedUBA; + // Total amount reserved for ongoing mintings. + uint256 reservedUBA; + // Total amount of ongoing redemptions. + uint256 redeemingUBA; + // Total amount of ongoing redemptions that lock the pool collateral. + // (In pool self-close exits, pool collateral is not locked. So the amount of locked + // collateral in the pool can be less than the amount of locked vault collateral.) + uint256 poolRedeemingUBA; + // Total amount of dust (unredeemable minted f-assets). + // Note: dustUBA is part of mintedUBA, so the amount of redeemable f-assets is calculated as + // `mintedUBA - dustUBA` + uint256 dustUBA; + // Liquidation info + // If the agent is in LIQUIDATION or FULL_LIQUIDATION, the time agent entered liquidation. + // If status is neither of that, returns 0. + // Can be used for calculating current liquidation premium, which depends on time since liquidation started. + uint256 liquidationStartTimestamp; + // When agent is in liquidation, this is the amount o FAssets that need to be liquidated to bring the agent's + // position to safety. When performing liquidation, only up to this amount of FAssets will be liquidated. + // If not in liquidation, this value is 0. + // Since the liquidation state may need to be upgraded by, call `startLiquidation` before + // `getAgentInfo` to get the value that will actually be used in liquidation. + uint256 maxLiquidationAmountUBA; + // When agent is in liquidation, this is the factor (in BIPS) of the converted value of the liquidated + // FAssets paid by the vault collateral. If not in liquidation, this value is 0. + uint256 liquidationPaymentFactorVaultBIPS; + // When agent is in liquidation, this is the factor (in BIPS) of the converted value of the liquidated + // FAssets paid by the pool collateral. If not in liquidation, this value is 0. + uint256 liquidationPaymentFactorPoolBIPS; + // Total underlying balance (backing and free). + int256 underlyingBalanceUBA; + // The minimum underlying balance that has to be held by the agent. Below this, agent is liquidated. + uint256 requiredUnderlyingBalanceUBA; + // Underlying balance not backing anything (can be used for gas/fees or withdrawn after announcement). + int256 freeUnderlyingBalanceUBA; + // Current underlying withdrawal announcement (or 0 if no announcement was made). + uint256 announcedUnderlyingWithdrawalId; + // The factor set by the agent to multiply the price at which agent buys f-assets from pool + // token holders on self-close exit (when requested or the redeemed amount is less than 1 lot). + uint256 buyFAssetByAgentFactorBIPS; + // The minimum collateral ratio above which a staker can exit the pool + // (this is CR that must be left after exit). + // Must be higher than system minimum collateral ratio for pool collateral. + uint256 poolExitCollateralRatioBIPS; + // The redemption fee share paid to the pool (as FAssets). + // In redemption dominated situations (when agent requests return from core vault to earn + // from redemption fees), pool can get some share to make it sustainable for pool users. + // NOTE: the pool fee share is locked at the redemption request time, but is charged at the redemption + // confirmation time. If agent uses all the redemption fee for transaction fees, this could make the + // agent's free underlying balance negative. + uint256 redemptionPoolFeeShareBIPS; + } +} diff --git a/src/songbird/data/AgentSettings.sol b/src/songbird/data/AgentSettings.sol new file mode 100644 index 0000000..98cb936 --- /dev/null +++ b/src/songbird/data/AgentSettings.sol @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +library AgentSettings { + struct Data { + // The token used as vault collateral. Must be one of the tokens obtained by `getCollateralTypes()`, + // with class VAULT. + IERC20 vaultCollateralToken; + // The suffix to pool token name and symbol that identifies new vault's collateral pool token. + // Must be unique within an asset manager. + string poolTokenSuffix; + // Minting fee. Normally charged to minters for publicly available agents, but must be set + // also for self-minting agents to pay part of it to collateral pool. + // Fee is paid in underlying currency along with backing assets. + uint256 feeBIPS; + // Share of the minting fee that goes to the pool as percentage of the minting fee. + // This share of fee is minted as f-assets and belongs to the pool. + uint256 poolFeeShareBIPS; + // Collateral ratio at which we calculate locked collateral and collateral available for minting. + // Agent may set own value for minting collateral ratio on creation. + // The value must always be greater than system minimum collateral ratio for vault collateral. + // Warning: having this value near global min collateral ratio can quickly lead to liquidation for public + // agents, so it is advisable to set it significantly higher. + uint256 mintingVaultCollateralRatioBIPS; + // Collateral ratio at which we calculate locked collateral and collateral available for minting. + // Agent may set own value for minting collateral ratio on creation. + // The value must always be greater than system minimum collateral ratio for pool collateral. + // Warning: having this value near global min collateral ratio can quickly lead to liquidation for public + // agents, so it is advisable to set it significantly higher. + uint256 mintingPoolCollateralRatioBIPS; + // The factor set by the agent to multiply the price at which agent buys f-assets from pool + // token holders on self-close exit (when requested or the redeemed amount is less than 1 lot). + uint256 buyFAssetByAgentFactorBIPS; + // The minimum collateral ratio above which a staker can exit the pool + // (this is CR that must be left after exit). + // Must be higher than system minimum collateral ratio for pool collateral. + uint256 poolExitCollateralRatioBIPS; + // The redemption fee share paid to the pool (as FAssets). + // In redemption dominated situations (when agent requests return from core vault to earn + // from redemption fees), pool can get some share to make it sustainable for pool users. + // NOTE: the pool fee share is locked at the redemption request time, but is charged at the redemption + // confirmation time. If agent uses all the redemption fee for transaction fees, this could make the + // agent's free underlying balance negative. + uint256 redemptionPoolFeeShareBIPS; + } +} diff --git a/src/songbird/data/AssetManagerSettings.sol b/src/songbird/data/AssetManagerSettings.sol new file mode 100644 index 0000000..831efbe --- /dev/null +++ b/src/songbird/data/AssetManagerSettings.sol @@ -0,0 +1,311 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +library AssetManagerSettings { + struct Data { + // Required contracts. + // Only used to verify that calls come from assetManagerController. + // Type: AssetManagerController + // changed via address updater + address assetManagerController; + + // The f-asset contract managed by this asset manager. + // Type: IIFAsset + // immutable + address fAsset; + + // Factory for creating new agent vaults. + // Type: IIAgentVaultFactory + // timelocked + address agentVaultFactory; + + // Factory for creating new agent collateral pools. + // Type: IICollateralPoolFactory + // timelocked + address collateralPoolFactory; + + // Factory for creating new agent collateral pool tokens. + // Type: IICollateralPoolTokenFactory + // timelocked + address collateralPoolTokenFactory; + + // The suffix to pool token name and symbol that identifies new vault's collateral pool token. + // When vault is created, the owner passes own suffix which will be appended to this. + string poolTokenSuffix; + + // If set, the whitelist contains a list of accounts that can call public methods + // (minting, redeeming, challenging, etc.) + // This can be `address(0)`, in which case no whitelist checks are done. + // Type: IWhitelist + // timelocked + address __whitelist; // only storage placeholder + + // If set, the owner address registry contains a list of allowed agent owner's + // management addresses and mappings from management to work address. + // Type: IAgentOwnerRegistry + // timelocked + address agentOwnerRegistry; + + // Attestation client verifies and decodes attestation proofs. + // Type: IFdcVerification + // changed via address updater + address fdcVerification; + + // The address where burned NAT is sent. + // immutable + address payable burnAddress; + + // The contract that reads prices from FTSO system in an FTSO version independent way. + // Type: IPriceReader + // timelocked + address priceReader; + + // Same as assetToken.decimals() + // immutable + uint8 assetDecimals; + + // Number of decimals of precision of minted amounts. + // assetMintingGranularityUBA = 10 ** (assetDecimals - assetMintingDecimals) + // immutable + uint8 assetMintingDecimals; + + // Must match attestation data chainId. + // immutable + bytes32 chainId; + + // Average time between two successive blocks on the underlying chain, in milliseconds. + // rate-limited + uint32 averageBlockTimeMS; + + // The minimum amount of pool tokens the agent must hold to be able to mint. + // To be able to mint, the NAT value of all backed fassets together with new ones times this percentage + // must be smaller than the agent's pool tokens' amount converted to NAT. + // rate-limited + uint32 mintingPoolHoldingsRequiredBIPS; + + // Collateral reservation fee that must be paid by the minter. + // Payment is in NAT, but is proportional to the value of assets to be minted. + // rate-limited + uint16 collateralReservationFeeBIPS; + + // Asset unit value (e.g. 1 BTC or 1 ETH) in UBA = 10 ** assetToken.decimals() + // immutable + uint64 assetUnitUBA; + + // The granularity in which lots are measured = the value of AMG (asset minting granularity) in UBA. + // Can only be changed via redeploy of AssetManager. + // AMG is used internally instead of UBA so that minted quantities fit into 64bits to reduce storage. + // So assetMintingGranularityUBA should be set so that the max supply in AMG of this currency + // in foreseeable time (say 100yr) cannot overflow 64 bits. + // immutable + uint64 assetMintingGranularityUBA; + + // Lot size in asset minting granularity. May change, which affects subsequent mintings and redemptions. + // timelocked + uint64 lotSizeAMG; + + // The percentage of minted f-assets that the agent must hold in his underlying address. + uint16 __minUnderlyingBackingBIPS; // only storage placeholder + + // for some chains (e.g. Ethereum) we require that agent proves that underlying address is an EOA address + // this must be done by presenting a payment proof from that address + // immutable + bool __requireEOAAddressProof; // only storage placeholder + + // Maximum minted amount of the f-asset. + // rate-limited + uint64 mintingCapAMG; + + // Number of underlying blocks that the minter or agent is allowed to pay underlying value. + // If payment not reported in that time, minting/redemption can be challenged and default action triggered. + // CAREFUL: Count starts from the current proved block height, so the minters and agents should + // make sure that current block height is fresh, otherwise they might not have enough time for payment. + // timelocked + uint64 underlyingBlocksForPayment; + + // Minimum time to allow agent to pay for redemption or minter to pay for minting. + // This is useful for fast chains, when there can be more than one block per second. + // Redemption/minting payment failure can be called only after underlyingSecondsForPayment have elapsed + // on underlying chain. + // CAREFUL: Count starts from the current proved block timestamp, so the minters and agents should + // make sure that current block timestamp is fresh, otherwise they might not have enough time for payment. + // This is partially mitigated by adding local duration since the last block height update to + // the current underlying block timestamp. + // timelocked + uint64 underlyingSecondsForPayment; + + // Redemption fee in underlying currency base amount (UBA). + // rate-limited + uint16 redemptionFeeBIPS; + + // On redemption underlying payment failure, redeemer is compensated with + // redemption value recalculated in flare/sgb times redemption failure factor. + // Expressed in BIPS, e.g. 12000 for factor of 1.2. + // This is the part of factor paid from agent's vault collateral. + // rate-limited + uint32 redemptionDefaultFactorVaultCollateralBIPS; + + // This is the part of redemption factor paid from agent's pool collateral. + // rate-limited + uint32 __redemptionDefaultFactorPoolBIPS; // only storage placeholder + + // If the agent or redeemer becomes unresponsive, we still need payment or non-payment confirmations + // to be presented eventually to properly track agent's underlying balance. + // Therefore we allow anybody to confirm payments/non-payments this many seconds after request was made. + // rate-limited + uint64 confirmationByOthersAfterSeconds; + + // The user who makes abandoned redemption confirmations gets rewarded by the following amount. + // rate-limited + uint128 confirmationByOthersRewardUSD5; + + // To prevent unbounded work, the number of tickets redeemed in a single request is limited. + // rate-limited + // >= 1 + uint16 maxRedeemedTickets; + + // Challenge reward can be composed of two part - fixed and proportional (any of them can be zero). + // This is the proportional part (in BIPS). + // rate-limited + uint16 paymentChallengeRewardBIPS; + + // Challenge reward can be composed of two part - fixed and proportional (any of them can be zero). + // This is the fixed part (in vault collateral token wei). + // rate-limited + uint128 paymentChallengeRewardUSD5; + + // Agent has to announce any collateral withdrawal ar vault destroy and then wait for at least + // withdrawalWaitMinSeconds. This prevents challenged agent to remove all collateral before + // challenge can be proved. + // rate-limited + uint64 withdrawalWaitMinSeconds; + + // Maximum age that trusted price feed is valid. + // Otherwise (if there were no trusted votes for that long) just use generic ftso price feed. + // rate-limited + uint64 maxTrustedPriceAgeSeconds; + + // Agent can remain in CCB for this much time, after that liquidation starts automatically. + // rate-limited + uint64 __ccbTimeSeconds; // only storage placeholder + + // Amount of seconds (typically 1 day) that the payment/non-payment proofs must be available. + // This setting is used in `unstickMinting` and `finishRedemptionWithoutPayment` to prove that the time when + // payment/non-payment could be proved has already passed. + // rate-limited + uint64 attestationWindowSeconds; + + // Minimum time after an update of a setting before the same setting can be updated again. + // timelocked + uint64 minUpdateRepeatTimeSeconds; + + // Ratio at which the agents can buy back their collateral when f-asset is terminated. + // Typically a bit more than 1 to incentivize agents to buy f-assets and self-close instead. + // immutable + uint64 __buybackCollateralFactorBIPS; // only storage placeholder + + // Minimum time that has to pass between underlying withdrawal announcement and the confirmation. + // Any value is ok, but higher values give more security against multiple announcement attack by a miner. + // Shouldn't be much bigger than Flare data connector response time, so that payments can be confirmed without + // extra wait. Should be smaller than confirmationByOthersAfterSeconds (e.g. less than 1 hour). + // rate-limited + uint64 __announcedUnderlyingConfirmationMinSeconds; + + // Minimum time from the moment token is deprecated to when it becomes invalid and agents still using + // it as vault collateral get liquidated. + // timelocked + uint64 tokenInvalidationTimeMinSeconds; + + // On some rare occasions (stuck minting), the agent has to unlock collateral. + // For this, part of collateral corresponding to FTSO asset value is burned and the rest is released. + // However, we cannot burn typical vault collateral (stablecoins), so the agent must buy them for NAT + // at FTSO price multiplied with this factor (should be a bit above 1) and then we burn the NATs. + // timelocked + uint32 vaultCollateralBuyForFlareFactorBIPS; + + // Amount of seconds that have to pass between available list exit announcement and execution. + // rate-limited + uint64 agentExitAvailableTimelockSeconds; + + // Amount of seconds that have to pass between agent fee and pool fee share change announcement and execution. + // rate-limited + uint64 agentFeeChangeTimelockSeconds; + + // Amount of seconds that have to pass between agent-set minting collateral ratio (vault or pool) + // change announcement and execution. + // rate-limited + uint64 agentMintingCRChangeTimelockSeconds; + + // Amount of seconds that have to pass between agent-set settings for pool exit collateral ratio + // change announcement and execution. + // rate-limited + uint64 poolExitCRChangeTimelockSeconds; + + // Amount of seconds that an agent is allowed to execute an update once it is allowed. + // rate-limited + uint64 agentTimelockedOperationWindowSeconds; + + // duration of the timelock for collateral pool tokens after minting + uint32 collateralPoolTokenTimelockSeconds; + + // If there was no liquidator for the current liquidation offer, + // go to the next step of liquidation after a certain period of time. + // rate-limited + uint64 liquidationStepSeconds; + + // Factor with which to multiply the asset price in native currency to obtain the payment + // to the liquidator. + // Expressed in BIPS, e.g. [12000, 16000, 20000] means that the liquidator will be paid 1.2, 1.6 and 2.0 + // times the market price of the liquidated assets after each `liquidationStepSeconds`. + // Values in the array must increase and be greater than 100%. + // rate-limited + uint256[] liquidationCollateralFactorBIPS; + + // How much of the liquidation is paid in vault collateral. + // The remainder will be paid in pool NAT collateral. + uint256[] liquidationFactorVaultCollateralBIPS; + + // Minimum time that the system must wait before performing diamond cut. + // The actual timelock is the maximum of this setting and GovernanceSettings.timelock. + uint64 diamondCutMinTimelockSeconds; + + // The maximum total pause that can be triggered by non-governance (but governance allowed) caller. + // The duration count can be reset by the governance. + uint64 maxEmergencyPauseDurationSeconds; + + // The amount of time since last emergency pause after which the total pause duration counter + // will reset automatically. + uint64 emergencyPauseDurationResetAfterSeconds; + + // The amount of time after which the collateral reservation can be cancelled if the + // handshake is not completed. + // rate-limited + uint64 __cancelCollateralReservationAfterSeconds; // only storage placeholder + + // The amount of collateral reservation fee returned to the minter in case of rejection or cancellation. + // Expressed in BIPS, e.g. 9500 for factor of 0.95, max 10000 for factor of 1.0. + // rate-limited + uint16 __rejectOrCancelCollateralReservationReturnFactorBIPS; // only storage placeholder + + // Time window inside which the agent can reject the redemption request. + // rate-limited + uint64 __rejectRedemptionRequestWindowSeconds; // only storage placeholder + + // Time window inside which the agent can take over the redemption request from another agent + // that has rejected it. + // rate-limited + uint64 __takeOverRedemptionRequestWindowSeconds; // only storage placeholder + + // On redemption rejection, without take over, redeemer is compensated with + // redemption value recalculated in flare/sgb times redemption failure factor. + // Expressed in BIPS, e.g. 12000 for factor of 1.2. + // This is the part of factor paid from agent's vault collateral. + // rate-limited + uint32 __rejectedRedemptionDefaultFactorVaultCollateralBIPS; // only storage placeholder + + // This is the part of rejected redemption factor paid from agent's pool collateral. + // rate-limited + uint32 __rejectedRedemptionDefaultFactorPoolBIPS; // only storage placeholder + } +} diff --git a/src/songbird/data/AvailableAgentInfo.sol b/src/songbird/data/AvailableAgentInfo.sol new file mode 100644 index 0000000..29510f1 --- /dev/null +++ b/src/songbird/data/AvailableAgentInfo.sol @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {AgentInfo} from "./AgentInfo.sol"; + +library AvailableAgentInfo { + struct Data { + // Agent vault address. + address agentVault; + // The management address of the agent vault's owner. + address ownerManagementAddress; + // Agent's minting fee in BIPS. + uint256 feeBIPS; + // Minimum agent vault collateral ratio needed for minting. + uint256 mintingVaultCollateralRatioBIPS; + // Minimum pool collateral ratio needed for minting. + uint256 mintingPoolCollateralRatioBIPS; + // The number of lots that can be minted by this agent. + // Note: the value is only informative since it can can change at any time + // due to price changes, reservation, minting, redemption, or even lot size change. + uint256 freeCollateralLots; + // The agent status, as for getAgentInfo(). + AgentInfo.Status status; + } +} diff --git a/src/songbird/data/CollateralReservationInfo.sol b/src/songbird/data/CollateralReservationInfo.sol new file mode 100644 index 0000000..65c3595 --- /dev/null +++ b/src/songbird/data/CollateralReservationInfo.sol @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +library CollateralReservationInfo { + enum Status { + ACTIVE, // the minting process hasn't finished yet + SUCCESSFUL, // the payment has been confirmed and the FAssets minted + DEFAULTED, // the payment has defaulted and the agent received the collateral reservation fee + EXPIRED // the confirmation time has expired and the agent called unstickMinting + } + + struct Data { + // The id used for executing or defaulting the minting. + uint64 collateralReservationId; + + // The agent vault whose collateral is reserved. + address agentVault; + + // The minter address - the address that will receive the minted FAssets. + address minter; + + // The agent's underlying address to which the underlying assets should be paid by the minter. + string paymentAddress; + + // Payment reference that must be part of the agent's redemption payment. + bytes32 paymentReference; + + // The amount of FAssets that the minter will receive. Always a whole number of lots. + uint256 valueUBA; + + // The underlying fee. The total amount the minter has to deposit is `valueUBA + mintingFeeUBA`. + // Part of the fee is minted as pool fee share and the rest becomes agent's free underlying. + uint128 mintingFeeUBA; + + // The fee that was paid at the collateral reservation time. + // Part of the fee is goes to the pool and the rest to the agent vault as WNAT. + uint128 reservationFeeNatWei; + + // Proportion of the mintingFeeUBA and reservationFeeNatWei that belongs to the collateral pool. + uint16 poolFeeShareBIPS; + + // The underlying block (approximate - as known by the asset manager) when the reservation occurred. + uint64 firstUnderlyingBlock; + + // The last underlying block and timestamp for redemption payment. Redemption is defaulted if + // there is no payment by the time BOTH lastUnderlyingBlock and lastUnderlyingTimestamp have passed. + uint64 lastUnderlyingBlock; + uint64 lastUnderlyingTimestamp; + + // The executor, optionally assigned by the minter to execute the minting. + // (Only minter, agent or executor may execute the minting.) + address executor; + + // The fee in NAT that the executor receives if they successfully execute the minting. + uint256 executorFeeNatWei; + + // If the minting process has finished, indication of success/default. Otherwise ACTIVE. + CollateralReservationInfo.Status status; + } +} diff --git a/src/songbird/data/CollateralType.sol b/src/songbird/data/CollateralType.sol new file mode 100644 index 0000000..711b4a1 --- /dev/null +++ b/src/songbird/data/CollateralType.sol @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + + +library CollateralType { + enum Class { + NONE, // unused + POOL, // pool collateral type + VAULT // usable as vault collateral + } + + // Collateral token is uniquely identified by the pair (collateralClass, token). + struct Data { + // The kind of collateral for this token. + CollateralType.Class collateralClass; + + // The ERC20 token contract for this collateral type. + IERC20 token; + + // Same as token.decimals(), when that exists. + uint256 decimals; + + // Token invalidation time. Must be 0 on creation. + uint256 validUntil; + + // When `true`, the FTSO with symbol `assetFtsoSymbol` returns asset price relative to this token + // (such FTSO's will probably exist for major stablecoins). + // When `false`, the FTSOs with symbols `assetFtsoSymbol` and `tokenFtsoSymbol` give asset and token + // price relative to the same reference currency and the asset/token price is calculated as their ratio. + bool directPricePair; + + // FTSO symbol for the asset, relative to this token or a reference currency + // (it depends on the value of `directPricePair`). + string assetFtsoSymbol; + + // FTSO symbol for this token in reference currency. + // Used for asset/token price calculation when `directPricePair` is `false`. + // Otherwise it is irrelevant to asset/token price calculation, but if it is nonempty, + // it is still used in calculation of challenger and confirmation rewards + // (otherwise we assume it approximates the value of USD and pay directly the USD amount in vault collateral). + string tokenFtsoSymbol; + + // Minimum collateral ratio for healthy agents. + uint256 minCollateralRatioBIPS; + + // Minimum collateral ratio required to get agent out of liquidation. + // Will always be greater than minCollateralRatioBIPS. + uint256 safetyMinCollateralRatioBIPS; + } +} diff --git a/src/songbird/data/RedemptionRequestInfo.sol b/src/songbird/data/RedemptionRequestInfo.sol new file mode 100644 index 0000000..e850ec1 --- /dev/null +++ b/src/songbird/data/RedemptionRequestInfo.sol @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +library RedemptionRequestInfo { + enum Status { + ACTIVE, // waiting for confirmation/default + DEFAULTED_UNCONFIRMED, // default called, failed or late payment can still be confirmed + // final statuses - there can be no valid payment for this redemption anymore + SUCCESSFUL, // successful payment confirmed + DEFAULTED_FAILED, // payment failed (default was paid) + BLOCKED, // payment blocked + REJECTED // redemption request rejected due to invalid redeemer's address + } + + struct Data { + // The id used for confirming or defaulting the request. + uint64 redemptionRequestId; + + // Redemption status. Note that on payment confirmation the request is deleted, so there is no success status. + RedemptionRequestInfo.Status status; + + // The redeemed agent vault. + address agentVault; + + // Native redeemer address - the address that receives collateral in case of default. + address redeemer; + + // The underlying address to which the redeemed assets should be paid by the agent. + string paymentAddress; + + // Payment reference that must be part of the agent's redemption payment. + bytes32 paymentReference; + + // The amount of the FAsset the redeemer has burned. Note that this is not the amount of underlying + // the redeemer will receive - the redemption payment amount is this minus the underlyingFeeUBA. + uint128 valueUBA; + + // The redemption fee that remain on agent's underlying address. + // Part of it will be reminted as pool fee share and the rest becomes the agent's free underlying. + uint128 feeUBA; + + // Proportional part of the underlyingFeeUBA that is re-minted on successful redemption + // and goes to the collateral pool. + uint16 poolFeeShareBIPS; + + // The underlying block (approximate - as known by the asset manager) when the request occurred. + uint64 firstUnderlyingBlock; + + // The last underlying block and timestamp for redemption payment. Redemption is defaulted if + // there is no payment by the time BOTH lastUnderlyingBlock and lastUnderlyingTimestamp have passed. + uint64 lastUnderlyingBlock; + uint64 lastUnderlyingTimestamp; + + // The native (Flare/Songbird) chain timestamp when the request occurred. + uint64 timestamp; + + // True if redemption was created by a selfCloseExit on the collateral pool. + bool poolSelfClose; + + // True if redemption was initiated by an agent for transfer to core vault. + bool transferToCoreVault; + + // The executor, optionally assigned by the redeemer to execute the default if needed. + // (Only redeemer, agent or executor may execute the default.) + address executor; + + // The fee in NAT that the executor receives if they successfully call default. + uint256 executorFeeNatWei; + } +} diff --git a/src/songbird/data/RedemptionTicketInfo.sol b/src/songbird/data/RedemptionTicketInfo.sol new file mode 100644 index 0000000..eb97c5c --- /dev/null +++ b/src/songbird/data/RedemptionTicketInfo.sol @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +library RedemptionTicketInfo { + struct Data { + // The id of the ticket, same as returned in RedemptionTicketCreated/Updated/Deleted events. + uint256 redemptionTicketId; + + // Backing agent vault address. + address agentVault; + + // The amount of FAsset on the ticket. + uint256 ticketValueUBA; + } +} diff --git a/src/songbird/fdc/interface/ITypeTemplate.sol b/src/songbird/fdc/interfaces/ITypeTemplate.sol similarity index 100% rename from src/songbird/fdc/interface/ITypeTemplate.sol rename to src/songbird/fdc/interfaces/ITypeTemplate.sol diff --git a/src/songbird/fdc/interface/ITypeTemplateVerification.sol b/src/songbird/fdc/interfaces/ITypeTemplateVerification.sol similarity index 100% rename from src/songbird/fdc/interface/ITypeTemplateVerification.sol rename to src/songbird/fdc/interfaces/ITypeTemplateVerification.sol diff --git a/src/songbird/fscV1/interface/IIFastUpdaterView.sol b/src/songbird/fscV1/interfaces/IIFastUpdaterView.sol similarity index 100% rename from src/songbird/fscV1/interface/IIFastUpdaterView.sol rename to src/songbird/fscV1/interfaces/IIFastUpdaterView.sol diff --git a/src/songbird/fscV1/interface/IIFtsoManagerProxy.sol b/src/songbird/fscV1/interfaces/IIFtsoManagerProxy.sol similarity index 100% rename from src/songbird/fscV1/interface/IIFtsoManagerProxy.sol rename to src/songbird/fscV1/interfaces/IIFtsoManagerProxy.sol diff --git a/src/coston/ftso/interface/IIFtso.sol b/src/songbird/ftso/interfaces/IIFtso.sol similarity index 98% rename from src/coston/ftso/interface/IIFtso.sol rename to src/songbird/ftso/interfaces/IIFtso.sol index e2beb8f..d93d935 100644 --- a/src/coston/ftso/interface/IIFtso.sol +++ b/src/songbird/ftso/interfaces/IIFtso.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; -import "../../genesis/interface/IFtsoGenesis.sol"; +import "../../genesis/interfaces/IFtsoGenesis.sol"; import "../../IFtso.sol"; -import "../../token/interface/IIVPToken.sol"; +import "../../token/interfaces/IIVPToken.sol"; interface IIFtso is IFtso, IFtsoGenesis { diff --git a/src/songbird/ftso/interface/IIFtsoFeedPublisher.sol b/src/songbird/ftso/interfaces/IIFtsoFeedPublisher.sol similarity index 100% rename from src/songbird/ftso/interface/IIFtsoFeedPublisher.sol rename to src/songbird/ftso/interfaces/IIFtsoFeedPublisher.sol diff --git a/src/songbird/ftso/interfaces/IIFtsoManager.sol b/src/songbird/ftso/interfaces/IIFtsoManager.sol new file mode 100644 index 0000000..b11605f --- /dev/null +++ b/src/songbird/ftso/interfaces/IIFtsoManager.sol @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../ftso/interfaces/IIFtso.sol"; +import "../../IFtsoManager.sol"; +import "../../genesis/interfaces/IFlareDaemonize.sol"; +import "../../token/interfaces/IIVPToken.sol"; + + +interface IIFtsoManager is IFtsoManager, IFlareDaemonize { + + struct RewardEpochData { + uint256 votepowerBlock; + uint256 startBlock; + uint256 startTimestamp; + } + + event ClosingExpiredRewardEpochFailed(uint256 rewardEpoch); + event CleanupBlockNumberManagerFailedForBlock(uint256 blockNumber); + event UpdatingActiveValidatorsTriggerFailed(uint256 rewardEpoch); + event FtsoDeactivationFailed(IIFtso ftso); + event ChillingNonrevealingDataProvidersFailed(); + + function activate() external; + + function setInitialRewardData( + uint256 _nextRewardEpochToExpire, + uint256 _rewardEpochsLength, + uint256 _currentRewardEpochEnds + ) external; + + function setGovernanceParameters( + uint256 _updateTs, + uint256 _maxVotePowerNatThresholdFraction, + uint256 _maxVotePowerAssetThresholdFraction, + uint256 _lowAssetUSDThreshold, + uint256 _highAssetUSDThreshold, + uint256 _highAssetTurnoutThresholdBIPS, + uint256 _lowNatTurnoutThresholdBIPS, + uint256 _elasticBandRewardBIPS, + uint256 _rewardExpiryOffsetSeconds, + address[] memory _trustedAddresses + ) external; + + + function addFtso(IIFtso _ftso) external; + + function addFtsosBulk(IIFtso[] memory _ftsos) external; + + function removeFtso(IIFtso _ftso) external; + + function replaceFtso( + IIFtso _ftsoToAdd, + bool copyCurrentPrice, + bool copyAssetOrAssetFtsos + ) external; + + function replaceFtsosBulk( + IIFtso[] memory _ftsosToAdd, + bool copyCurrentPrice, + bool copyAssetOrAssetFtsos + ) external; + + function setFtsoAsset(IIFtso _ftso, IIVPToken _asset) external; + + function setFtsoAssetFtsos(IIFtso _ftso, IIFtso[] memory _assetFtsos) external; + + function setFallbackMode(bool _fallbackMode) external; + + function setFtsoFallbackMode(IIFtso _ftso, bool _fallbackMode) external; + + function notInitializedFtsos(IIFtso) external view returns (bool); + + function getRewardEpochData(uint256 _rewardEpochId) external view returns (RewardEpochData memory); + + function currentRewardEpochEnds() external view returns (uint256); + + function getLastUnprocessedPriceEpochData() external view + returns( + uint256 _lastUnprocessedPriceEpoch, + uint256 _lastUnprocessedPriceEpochRevealEnds, + bool _lastUnprocessedPriceEpochInitialized + ); + + function rewardEpochsStartTs() external view returns(uint256); + + function rewardEpochDurationSeconds() external view returns(uint256); + + function rewardEpochs(uint256 _rewardEpochId) external view + returns ( + uint256 _votepowerBlock, + uint256 _startBlock, + uint256 _startTimestamp + ); + + function getRewardExpiryOffsetSeconds() external view returns (uint256); + + /** + * @notice Returns elastic band width in PPM (parts-per-million) for given ftso + */ + function getElasticBandWidthPPMFtso(IIFtso _ftso) external view returns (uint256); +} diff --git a/src/songbird/ftso/interfaces/IIFtsoManagerV1.sol b/src/songbird/ftso/interfaces/IIFtsoManagerV1.sol new file mode 100644 index 0000000..44cf4cc --- /dev/null +++ b/src/songbird/ftso/interfaces/IIFtsoManagerV1.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +// interface for the first version of ftso manger (V1 = oldest version) - last version is always without any Vx +interface IIFtsoManagerV1 { + function rewardEpochsStartTs() external view returns(uint256); + function rewardEpochDurationSeconds() external view returns(uint256); + + function getCurrentRewardEpoch() external view returns(uint256); + + function rewardEpochs(uint256 _rewardEpochId) external view returns ( + uint256 _votepowerBlock, + uint256 _startBlock, + uint256 _startTimestamp + ); + + function getPriceEpochConfiguration() external view + returns ( + uint256 _firstPriceEpochStartTs, + uint256 _priceEpochDurationSeconds, + uint256 _revealEpochDurationSeconds + ); +} diff --git a/src/songbird/genesis/interface/IFlareDaemonize.sol b/src/songbird/genesis/interfaces/IFlareDaemonize.sol similarity index 100% rename from src/songbird/genesis/interface/IFlareDaemonize.sol rename to src/songbird/genesis/interfaces/IFlareDaemonize.sol diff --git a/src/songbird/genesis/interface/IFtsoGenesis.sol b/src/songbird/genesis/interfaces/IFtsoGenesis.sol similarity index 100% rename from src/songbird/genesis/interface/IFtsoGenesis.sol rename to src/songbird/genesis/interfaces/IFtsoGenesis.sol diff --git a/src/songbird/genesis/interface/IFtsoManagerGenesis.sol b/src/songbird/genesis/interfaces/IFtsoManagerGenesis.sol similarity index 100% rename from src/songbird/genesis/interface/IFtsoManagerGenesis.sol rename to src/songbird/genesis/interfaces/IFtsoManagerGenesis.sol diff --git a/src/songbird/genesis/interface/IFtsoRegistryGenesis.sol b/src/songbird/genesis/interfaces/IFtsoRegistryGenesis.sol similarity index 100% rename from src/songbird/genesis/interface/IFtsoRegistryGenesis.sol rename to src/songbird/genesis/interfaces/IFtsoRegistryGenesis.sol diff --git a/src/songbird/genesis/interfaces/IIPriceSubmitter.sol b/src/songbird/genesis/interfaces/IIPriceSubmitter.sol new file mode 100644 index 0000000..b1135c6 --- /dev/null +++ b/src/songbird/genesis/interfaces/IIPriceSubmitter.sol @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IPriceSubmitter.sol"; +interface IIPriceSubmitter is IPriceSubmitter { + + /** + * Sets ftso registry, voter whitelist and ftso manager contracts. + * Only governance can call this method. + * If replacing the registry or the whitelist and the old one is not empty, make sure to replicate the state, + * otherwise internal whitelist bitmaps won't match. + */ + function setContractAddresses( + IFtsoRegistryGenesis _ftsoRegistry, + address _voterWhitelister, + address _ftsoManager + ) external; + + /** + * Set trusted addresses that are always allowed to submit and reveal. + * Only ftso manager can call this method. + */ + function setTrustedAddresses(address[] memory _trustedAddresses) external; + + /** + * Called from whitelister when new voter has been whitelisted. + */ + function voterWhitelisted(address _voter, uint256 _ftsoIndex) external; + + /** + * Called from whitelister when one or more voters have been removed. + */ + function votersRemovedFromWhitelist(address[] memory _voters, uint256 _ftsoIndex) external; + + /** + * Returns a list of trusted addresses that are always allowed to submit and reveal. + */ + function getTrustedAddresses() external view returns (address[] memory); +} diff --git a/src/songbird/genesis/interfaces/IInflationGenesis.sol b/src/songbird/genesis/interfaces/IInflationGenesis.sol new file mode 100644 index 0000000..eb0e98c --- /dev/null +++ b/src/songbird/genesis/interfaces/IInflationGenesis.sol @@ -0,0 +1,15 @@ + +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IInflationGenesis { + /** + * @notice Receive newly minted native tokens from the FlareDaemon. + * @dev Assume that the amount received will be >= last topup requested across all services. + * If there is not enough balance sent to cover the topup request, expect library method will revert. + * Also assume that any balance received greater than the topup request calculated + * came from self-destructor sending a balance to this contract. + */ + function receiveMinting() external payable; +} diff --git a/src/flare/governance/interface/IIGovernorProposer.sol b/src/songbird/governance/interfaces/IIGovernorProposer.sol similarity index 58% rename from src/flare/governance/interface/IIGovernorProposer.sol rename to src/songbird/governance/interfaces/IIGovernorProposer.sol index adb6c4c..8e7dc87 100644 --- a/src/flare/governance/interface/IIGovernorProposer.sol +++ b/src/songbird/governance/interfaces/IIGovernorProposer.sol @@ -1,12 +1,13 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; interface IIGovernorProposer { /** - * Determines if account is eligible to submit a proposal. - * @param _account Address of the queried account. - * @return True if account is eligible for proposal submission, and false otherwise. + * @notice Determines if account is eligible to submit a proposal + * @param _account Address of the queried account + * @return True if account is eligible for proposal submission, and false otherwise */ function isProposer(address _account) external view returns (bool); diff --git a/src/flare/governance/interface/IIPollingFoundation.sol b/src/songbird/governance/interfaces/IIPollingFoundation.sol similarity index 53% rename from src/flare/governance/interface/IIPollingFoundation.sol rename to src/songbird/governance/interfaces/IIPollingFoundation.sol index 9fe2fd4..59f9854 100644 --- a/src/flare/governance/interface/IIPollingFoundation.sol +++ b/src/songbird/governance/interfaces/IIPollingFoundation.sol @@ -1,5 +1,6 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; import "../../IGovernor.sol"; import "./IIGovernorProposer.sol"; @@ -8,7 +9,7 @@ interface IIPollingFoundation is IGovernor, IIGovernorProposer { struct GovernorSettingsWithoutExecParams { bool accept; - uint256 votingStartTs; + uint256 votingDelaySeconds; uint256 votingPeriodSeconds; uint256 vpBlockPeriodSeconds; uint256 thresholdConditionBIPS; @@ -16,11 +17,11 @@ interface IIPollingFoundation is IGovernor, IIGovernorProposer { } /** - * Creates a new proposal without execution parameters. - * @param _description String description of the proposal. - * @param _settings Settings of the poposal. - * @return Proposal id (unique identifier obtained by hashing proposal data). - * Emits a ProposalCreated event. + * @notice Creates a new proposal without execution parameters + * @param _description String description of the proposal + * @param _settings Settings of the poposal + * @return Proposal id (unique identifier obtained by hashing proposal data) + * @notice Emits a ProposalCreated event */ function propose( string memory _description, @@ -28,14 +29,14 @@ interface IIPollingFoundation is IGovernor, IIGovernorProposer { ) external returns (uint256); /** - * Creates a new proposal with execution parameters. - * @param _targets Array of target addresses on which the calls are to be invoked. - * @param _values Array of values with which the calls are to be invoked. - * @param _calldatas Array of call data to be invoked. - * @param _description String description of the proposal. - * @param _settings Settings of the poposal. - * @return Proposal id (unique identifier obtained by hashing proposal data). - * Emits a ProposalCreated event. + * @notice Creates a new proposal with execution parameters + * @param _targets Array of target addresses on which the calls are to be invoked + * @param _values Array of values with which the calls are to be invoked + * @param _calldatas Array of call data to be invoked + * @param _description String description of the proposal + * @param _settings Settings of the poposal + * @return Proposal id (unique identifier obtained by hashing proposal data) + * @notice Emits a ProposalCreated event */ function propose( address[] memory _targets, diff --git a/src/songbird/governance/interface/IIPollingManagementGroup.sol b/src/songbird/governance/interfaces/IIPollingManagementGroup.sol similarity index 100% rename from src/songbird/governance/interface/IIPollingManagementGroup.sol rename to src/songbird/governance/interfaces/IIPollingManagementGroup.sol diff --git a/src/songbird/inflation/interfaces/IIInflationAllocation.sol b/src/songbird/inflation/interfaces/IIInflationAllocation.sol new file mode 100644 index 0000000..da5305a --- /dev/null +++ b/src/songbird/inflation/interfaces/IIInflationAllocation.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIInflationReceiver.sol"; + +struct SharingPercentage { + IIInflationReceiver inflationReceiver; + uint256 percentBips; +} + +interface IIInflationAllocation { + /** + * Return the time slot inflation rate in bips. + */ + function getTimeSlotPercentageBips() external returns(uint256); + + /** + * Return the shared percentage per inflation receiver. + * @dev Assumption is that implementer edited that percents sum to 100 pct and + * that receiver addresses are valid. + */ + function getSharingPercentages() external returns(SharingPercentage[] memory); +} diff --git a/src/songbird/inflation/interfaces/IIInflationReceiver.sol b/src/songbird/inflation/interfaces/IIInflationReceiver.sol new file mode 100644 index 0000000..dd7c4b5 --- /dev/null +++ b/src/songbird/inflation/interfaces/IIInflationReceiver.sol @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIInflationReceiver { + /** + * Notify the receiver that it is entitled to receive `_toAuthorizeWei` inflation amount. + * @param _toAuthorizeWei the amount of inflation that can be awarded in the coming day + */ + function setDailyAuthorizedInflation(uint256 _toAuthorizeWei) external; + + /** + * Receive native tokens from inflation. + */ + function receiveInflation() external payable; + + /** + * Inflation receivers have a reference to the Inflation contract. + */ + function getInflationAddress() external returns(address); + + /** + * Inflation receivers have a method to get their expected balance + * (actual balance can be higher due to self-destruct funds) + */ + function getExpectedBalance() external view returns(uint256); + + /** + * Implement this function for updating inflation receiver contracts through AddressUpdater. + */ + function getContractName() external view returns (string memory); +} diff --git a/src/songbird/inflation/interfaces/IIInflationReceiverV1.sol b/src/songbird/inflation/interfaces/IIInflationReceiverV1.sol new file mode 100644 index 0000000..a75342a --- /dev/null +++ b/src/songbird/inflation/interfaces/IIInflationReceiverV1.sol @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIInflationReceiverV1 { + /** + * Notify the receiver that it is entitled to receive `_toAuthorizeWei` inflation amount. + * @param _toAuthorizeWei the amount of inflation that can be awarded in the coming day + */ + function setDailyAuthorizedInflation(uint256 _toAuthorizeWei) external; + + /** + * Receive native tokens from inflation. + */ + function receiveInflation() external payable; + + /** + * Inflation receivers have a reference to the Inflation contract. + */ + function getInflationAddress() external returns(address); + + /** + * Implement this function for updating inflation receiver contracts through AddressUpdater. + */ + function getContractName() external view returns (string memory); +} diff --git a/src/songbird/inflation/interfaces/IIInflationV1.sol b/src/songbird/inflation/interfaces/IIInflationV1.sol new file mode 100644 index 0000000..529920a --- /dev/null +++ b/src/songbird/inflation/interfaces/IIInflationV1.sol @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "./IIInflationReceiver.sol"; + + +// interface for the first version of inflation (V1 = oldest version) - last version is always without any Vx +interface IIInflationV1 { + + struct RewardServiceState { + IIInflationReceiver inflationReceiver; // The target rewarding contract + uint256 authorizedInflationWei; // Total authorized inflation for this reward service + uint256 lastDailyAuthorizedInflationWei; // Last daily authorized inflation amount + uint256 inflationTopupRequestedWei; // Total inflation topup requested to be minted + uint256 inflationTopupReceivedWei; // Total inflation minting received + uint256 inflationTopupWithdrawnWei; // Total inflation minting sent to rewarding service contract + } + + struct RewardServicesState { + // Collection of annums + RewardServiceState[] rewardServices; + // Balances + uint256 totalAuthorizedInflationWei; + uint256 totalInflationTopupRequestedWei; + uint256 totalInflationTopupReceivedWei; + uint256 totalInflationTopupWithdrawnWei; + } + + struct InflationAnnumState { + uint256 recognizedInflationWei; + uint16 daysInAnnum; + uint256 startTimeStamp; + uint256 endTimeStamp; + RewardServicesState rewardServices; + } + + + function lastAuthorizationTs() external returns(uint256); + function rewardEpochStartedTs() external returns(uint256); + function getAnnum(uint256 _index) external view returns(InflationAnnumState memory); + +} diff --git a/src/songbird/inflation/interfaces/IIPreInflationCalculation.sol b/src/songbird/inflation/interfaces/IIPreInflationCalculation.sol new file mode 100644 index 0000000..29e5043 --- /dev/null +++ b/src/songbird/inflation/interfaces/IIPreInflationCalculation.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IIPreInflationCalculation { + /** + * @notice A method that is triggered before new inflation is calculated + */ + function trigger() external; +} diff --git a/src/songbird/inflation/interfaces/IISupply.sol b/src/songbird/inflation/interfaces/IISupply.sol new file mode 100644 index 0000000..0090891 --- /dev/null +++ b/src/songbird/inflation/interfaces/IISupply.sol @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IISupply { + + /** + * @notice Updates circulating supply + * @dev Also updates the burn address amount + */ + function updateCirculatingSupply() external; + + /** + * @notice Updates authorized inflation and circulating supply - emits event if error + * @param _inflationAuthorizedWei Authorized inflation + * @dev Also updates the burn address amount + */ + function updateAuthorizedInflationAndCirculatingSupply(uint256 _inflationAuthorizedWei) external; + + /** + * @notice Get approximate circulating supply for given block number from cache - only past block + * @param _blockNumber Block number + * @return _circulatingSupplyWei Return approximate circulating supply for last known block <= _blockNumber + */ + function getCirculatingSupplyAtCached(uint256 _blockNumber) external returns(uint256 _circulatingSupplyWei); + + /** + * @notice Get approximate circulating supply for given block number + * @param _blockNumber Block number + * @return _circulatingSupplyWei Return approximate circulating supply for last known block <= _blockNumber + */ + function getCirculatingSupplyAt(uint256 _blockNumber) external view returns(uint256 _circulatingSupplyWei); + + /** + * @notice Get total inflatable balance (initial genesis amount + total authorized inflation) + * @return _inflatableBalanceWei Return inflatable balance + */ + function getInflatableBalance() external view returns(uint256 _inflatableBalanceWei); +} diff --git a/src/songbird/mockXAsset/interfaces/ICollateralizable.sol b/src/songbird/mockXAsset/interfaces/ICollateralizable.sol new file mode 100644 index 0000000..3ed5a99 --- /dev/null +++ b/src/songbird/mockXAsset/interfaces/ICollateralizable.sol @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface ICollateralizable { + + enum FeeHandling { + DEPOSIT_TO_POSITION, + SEND_TO_AGENT + } + + /// addRewardToAgentPosition function will be triggered by the reward contract per reward allocation. + /// Function will claim rewards for last epoch, and allocate to relevant agents + /// Flow: + /// - check which FTSO won. + /// - claim relevant reward from reward contract. + /// - iterate list of current delegators to this FTSO + /// - per the list, check weight agent delegated to this FTSO + /// - add native token reward to this Agent position. + function addRewardToAgentPosition(uint256 epochID) external returns (bool succeess); + + function deposit( + uint256 amount, + uint256 freshMint, // amount to add to fresh minting pool + uint256 agentPosition, // amount to add to position pool + uint256 freshMintMinRatio, // if position pool collateral ratio < min, no new mints + address natAddress, + FeeHandling handling + ) external; + + /// note: must send collateral reservation fee as msg.value. or approve to this contract + function mintRequest ( // AKA collateral reservation + uint256 mintAmountTwei, + address mintDestination, + bytes32 underlyingAddress + ) + external + returns ( + uint256 mintRequestId, + address[] calldata agents, // agent list + uint256[] calldata assetAmounts, // amount to send to agent in underlying chain + bytes32[] calldata assetAddress // underlying chain address + ); + + function proveMintPayment ( // AKA mint + uint256 mintRequestId, + bytes32 minterSourceAddress, //do we need this? + bytes32 agentAssetAddress, + bytes32 destinationTag, + uint256 assetAmount, + bytes32[] calldata merkleProof + ) + external + returns ( + uint256 mintedAmount + ); + + function assetRedemptionRequest ( + uint256 amount, + bytes32 assetAddress // address in underlying chain[] + ) + external + returns ( + uint256 redemptionId, + address[] calldata agents, // agent list + uint256[] calldata assetAmounts // amount agent should in underlying chain + ); + + function proveRedemptionPayment ( // same as prove mint payment? + uint256 redemptionRequestId, + bytes32 agentSourceAssetAddress, //do we need this? + bytes32 redeemerAssetAddress, + bytes32 destinationTag, + uint256 assetAmount, + bytes32[] calldata merkleProof + ) + external + returns ( + uint256 redeemedAmount + ); +} diff --git a/src/songbird/protocol/interface/IIClaimSetupManager.sol b/src/songbird/protocol/interfaces/IIClaimSetupManager.sol similarity index 100% rename from src/songbird/protocol/interface/IIClaimSetupManager.sol rename to src/songbird/protocol/interfaces/IIClaimSetupManager.sol diff --git a/src/songbird/protocol/interface/IICleanupBlockNumberManager.sol b/src/songbird/protocol/interfaces/IICleanupBlockNumberManager.sol similarity index 100% rename from src/songbird/protocol/interface/IICleanupBlockNumberManager.sol rename to src/songbird/protocol/interfaces/IICleanupBlockNumberManager.sol diff --git a/src/songbird/protocol/interface/IIEntityManager.sol b/src/songbird/protocol/interfaces/IIEntityManager.sol similarity index 100% rename from src/songbird/protocol/interface/IIEntityManager.sol rename to src/songbird/protocol/interfaces/IIEntityManager.sol diff --git a/src/songbird/protocol/interface/IIFlareSystemsCalculator.sol b/src/songbird/protocol/interfaces/IIFlareSystemsCalculator.sol similarity index 100% rename from src/songbird/protocol/interface/IIFlareSystemsCalculator.sol rename to src/songbird/protocol/interfaces/IIFlareSystemsCalculator.sol diff --git a/src/songbird/protocol/interface/IIFlareSystemsManager.sol b/src/songbird/protocol/interfaces/IIFlareSystemsManager.sol similarity index 100% rename from src/songbird/protocol/interface/IIFlareSystemsManager.sol rename to src/songbird/protocol/interfaces/IIFlareSystemsManager.sol diff --git a/src/songbird/protocol/interface/IINodePossessionVerifier.sol b/src/songbird/protocol/interfaces/IINodePossessionVerifier.sol similarity index 100% rename from src/songbird/protocol/interface/IINodePossessionVerifier.sol rename to src/songbird/protocol/interfaces/IINodePossessionVerifier.sol diff --git a/src/songbird/protocol/interface/IIPublicKeyVerifier.sol b/src/songbird/protocol/interfaces/IIPublicKeyVerifier.sol similarity index 100% rename from src/songbird/protocol/interface/IIPublicKeyVerifier.sol rename to src/songbird/protocol/interfaces/IIPublicKeyVerifier.sol diff --git a/src/songbird/protocol/interface/IIRelay.sol b/src/songbird/protocol/interfaces/IIRelay.sol similarity index 100% rename from src/songbird/protocol/interface/IIRelay.sol rename to src/songbird/protocol/interfaces/IIRelay.sol diff --git a/src/songbird/protocol/interface/IIRewardEpochSwitchoverTrigger.sol b/src/songbird/protocol/interfaces/IIRewardEpochSwitchoverTrigger.sol similarity index 100% rename from src/songbird/protocol/interface/IIRewardEpochSwitchoverTrigger.sol rename to src/songbird/protocol/interfaces/IIRewardEpochSwitchoverTrigger.sol diff --git a/src/songbird/protocol/interface/IIRewardManager.sol b/src/songbird/protocol/interfaces/IIRewardManager.sol similarity index 100% rename from src/songbird/protocol/interface/IIRewardManager.sol rename to src/songbird/protocol/interfaces/IIRewardManager.sol diff --git a/src/songbird/protocol/interface/IISubmission.sol b/src/songbird/protocol/interfaces/IISubmission.sol similarity index 100% rename from src/songbird/protocol/interface/IISubmission.sol rename to src/songbird/protocol/interfaces/IISubmission.sol diff --git a/src/songbird/protocol/interface/IIVoterRegistrationTrigger.sol b/src/songbird/protocol/interfaces/IIVoterRegistrationTrigger.sol similarity index 100% rename from src/songbird/protocol/interface/IIVoterRegistrationTrigger.sol rename to src/songbird/protocol/interfaces/IIVoterRegistrationTrigger.sol diff --git a/src/songbird/protocol/interface/IIVoterRegistry.sol b/src/songbird/protocol/interfaces/IIVoterRegistry.sol similarity index 100% rename from src/songbird/protocol/interface/IIVoterRegistry.sol rename to src/songbird/protocol/interfaces/IIVoterRegistry.sol diff --git a/src/songbird/rNat/interface/IIRNat.sol b/src/songbird/rNat/interfaces/IIRNat.sol similarity index 100% rename from src/songbird/rNat/interface/IIRNat.sol rename to src/songbird/rNat/interfaces/IIRNat.sol diff --git a/src/songbird/rNat/interface/IIRNatAccount.sol b/src/songbird/rNat/interfaces/IIRNatAccount.sol similarity index 98% rename from src/songbird/rNat/interface/IIRNatAccount.sol rename to src/songbird/rNat/interfaces/IIRNatAccount.sol index 0a7d05e..017902d 100644 --- a/src/songbird/rNat/interface/IIRNatAccount.sol +++ b/src/songbird/rNat/interfaces/IIRNatAccount.sol @@ -3,7 +3,7 @@ pragma solidity >=0.7.6 <0.9; import "../../IRNatAccount.sol"; -import "../../protocol/interface/IIClaimSetupManager.sol"; +import "../../protocol/interfaces/IIClaimSetupManager.sol"; interface IIRNatAccount is IRNatAccount { diff --git a/src/songbird/token/interface/IICleanable.sol b/src/songbird/token/interfaces/IICleanable.sol similarity index 100% rename from src/songbird/token/interface/IICleanable.sol rename to src/songbird/token/interfaces/IICleanable.sol diff --git a/src/songbird/token/interface/IIGovernanceVotePower.sol b/src/songbird/token/interfaces/IIGovernanceVotePower.sol similarity index 100% rename from src/songbird/token/interface/IIGovernanceVotePower.sol rename to src/songbird/token/interfaces/IIGovernanceVotePower.sol diff --git a/src/songbird/token/interface/IIVPContract.sol b/src/songbird/token/interfaces/IIVPContract.sol similarity index 100% rename from src/songbird/token/interface/IIVPContract.sol rename to src/songbird/token/interfaces/IIVPContract.sol diff --git a/src/songbird/token/interface/IIVPToken.sol b/src/songbird/token/interfaces/IIVPToken.sol similarity index 100% rename from src/songbird/token/interface/IIVPToken.sol rename to src/songbird/token/interfaces/IIVPToken.sol diff --git a/src/songbird/tokenPools/interfaces/IIFtsoRewardManager.sol b/src/songbird/tokenPools/interfaces/IIFtsoRewardManager.sol new file mode 100644 index 0000000..f7907a3 --- /dev/null +++ b/src/songbird/tokenPools/interfaces/IIFtsoRewardManager.sol @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IFtsoRewardManager.sol"; +import "../interfaces/IITokenPool.sol"; +import "../../inflation/interfaces/IIInflationReceiverV1.sol"; + +interface IIFtsoRewardManager is IFtsoRewardManager, IIInflationReceiverV1, IITokenPool { + + event DailyAuthorizedInflationSet(uint256 authorizedAmountWei); + event InflationReceived(uint256 amountReceivedWei); + event RewardsBurned(uint256 amountBurnedWei); + + function activate() external; + function enableClaims() external; + function deactivate() external; + function closeExpiredRewardEpoch(uint256 _rewardEpochId) external; + + function distributeRewards( + address[] memory addresses, + uint256[] memory weights, + uint256 totalWeight, + uint256 epochId, + address ftso, + uint256 priceEpochDurationSeconds, + uint256 currentRewardEpoch, + uint256 priceEpochEndTime, + uint256 votePowerBlock + ) external; + + function accrueUnearnedRewards( + uint256 epochId, + uint256 priceEpochDurationSeconds, + uint256 priceEpochEndTime + ) external; + + function firstClaimableRewardEpoch() external view returns (uint256); + + /** + * @notice Returns the information on unclaimed reward of `_dataProvider` for `_rewardEpoch` + * @param _rewardEpoch reward epoch number + * @param _dataProvider address representing the data provider + * @return _amount number representing the unclaimed amount + * @return _weight number representing the share that has not yet been claimed + */ + function getUnclaimedReward( + uint256 _rewardEpoch, + address _dataProvider + ) + external view + returns ( + uint256 _amount, + uint256 _weight + ); +} diff --git a/src/songbird/tokenPools/interfaces/IITokenPool.sol b/src/songbird/tokenPools/interfaces/IITokenPool.sol new file mode 100644 index 0000000..5007dfe --- /dev/null +++ b/src/songbird/tokenPools/interfaces/IITokenPool.sol @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IITokenPool { + + /** + * @notice Return token pool supply data + * @return _foundationAllocatedFundsWei Foundation allocated funds (wei) + * @return _totalInflationAuthorizedWei Total inflation authorized amount (wei) + * @return _totalClaimedWei Total claimed amount (wei) + */ + function getTokenPoolSupplyData() external view returns ( + uint256 _foundationAllocatedFundsWei, + uint256 _totalInflationAuthorizedWei, + uint256 _totalClaimedWei + ); +} diff --git a/src/songbird/utils/interfaces/IIFtsoRegistry.sol b/src/songbird/utils/interfaces/IIFtsoRegistry.sol new file mode 100644 index 0000000..82d239a --- /dev/null +++ b/src/songbird/utils/interfaces/IIFtsoRegistry.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../ftso/interfaces/IIFtso.sol"; +import "../../IFtsoRegistry.sol"; + + +interface IIFtsoRegistry is IFtsoRegistry { + + // returns ftso index + function addFtso(IIFtso _ftsoContract) external returns(uint256); + + function removeFtso(IIFtso _ftso) external; +} diff --git a/src/songbird/utils/interfaces/IIFtsoRegistryV1.sol b/src/songbird/utils/interfaces/IIFtsoRegistryV1.sol new file mode 100644 index 0000000..f44303e --- /dev/null +++ b/src/songbird/utils/interfaces/IIFtsoRegistryV1.sol @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; +pragma abicoder v2; + +import "../../ftso/interfaces/IIFtsoManager.sol"; + + +interface IIFtsoRegistryV1 { + + function setFtsoManagerAddress(IIFtsoManager _ftsoManager) external; + + // returns ftso index + function addFtso(IIFtso _ftsoContract) external returns(uint256); + + function removeFtso(IIFtso _ftso) external; + + function getFtsoBySymbol(string memory _symbol) external view returns(IIFtso _activeFtsoAddress); + function getSupportedSymbols() external view returns(string[] memory _supportedSymbols); + function getSupportedFtsos() external view returns(IIFtso[] memory _ftsos); + function getFtsoIndex(string memory _symbol) external view returns (uint256 _assetIndex); +} diff --git a/src/songbird/utils/interfaces/IIRandomProvider.sol b/src/songbird/utils/interfaces/IIRandomProvider.sol new file mode 100644 index 0000000..26b45cd --- /dev/null +++ b/src/songbird/utils/interfaces/IIRandomProvider.sol @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + + +interface IIRandomProvider { + + function chillNonrevealingDataProviders(uint256 _finalizingPriceEpochId, uint256 _currentPriceEpochId) external; + + function getCurrentRandom() external view returns(uint256 _currentRandom); + + function getCurrentRandomWithQuality() external view returns(uint256 _currentRandom, bool _goodRandom); +} diff --git a/src/songbird/utils/interfaces/IIVoterWhitelister.sol b/src/songbird/utils/interfaces/IIVoterWhitelister.sol new file mode 100644 index 0000000..34ff426 --- /dev/null +++ b/src/songbird/utils/interfaces/IIVoterWhitelister.sol @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +import "../../IVoterWhitelister.sol"; + + +interface IIVoterWhitelister is IVoterWhitelister { + /** + * @notice Used to chill voter - remove from whitelist for a specified number of reward epochs + * @dev Only governance can call this method. + */ + function chillVoter( + address _voter, + uint256 _noOfRewardEpochs, + uint256[] memory _ftsoIndices + ) + external + returns( + bool[] memory _removed, + uint256 _untilRewardEpoch + ); + + /** + * Set the maximum number of voters in the whitelist for FTSO at index `_ftsoIndex`. + * Possibly removes several voters with the least votepower from the whitelist. + * Only governance can call this method. + */ + function setMaxVotersForFtso(uint256 _ftsoIndex, uint256 _newMaxVoters) external; + + /** + * Set the maximum number of voters in the whitelist for a new FTSO. + * Only governance can call this method. + */ + function setDefaultMaxVotersForFtso(uint256 _defaultMaxVotersForFtso) external; + + /** + * Create whitelist with default size for ftso. + * Only ftso manager can call this method. + */ + function addFtso(uint256 _ftsoIndex) external; + + /** + * Clear whitelist for ftso at `_ftsoIndex`. + * Only ftso manager can call this method. + */ + function removeFtso(uint256 _ftsoIndex) external; + + /** + * Remove `_trustedAddress` from whitelist for ftso at `_ftsoIndex`. + */ + function removeTrustedAddressFromWhitelist(address _trustedAddress, uint256 _ftsoIndex) external; +} diff --git a/src/songbird/utils/interfaces/IUpdateValidators.sol b/src/songbird/utils/interfaces/IUpdateValidators.sol new file mode 100644 index 0000000..4788daf --- /dev/null +++ b/src/songbird/utils/interfaces/IUpdateValidators.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.7.6 <0.9; + +interface IUpdateValidators { + /** + update the validators after reward epoch + **/ + function updateActiveValidators() external; +}