diff --git a/Makefile b/Makefile index defd403..4bb137b 100644 --- a/Makefile +++ b/Makefile @@ -409,4 +409,4 @@ clean-all: # fmt & lint all directories fmt-all: - movefmt --config-path=./movefmt.toml --emit "files" -v \ No newline at end of file + movefmt --config-path=./movefmt.toml --emit "overwrite" -v \ No newline at end of file diff --git a/aave-core/Move.toml b/aave-core/Move.toml index df7af3b..1cf873f 100644 --- a/aave-core/Move.toml +++ b/aave-core/Move.toml @@ -10,7 +10,7 @@ aave_pool = '_' [dev-addresses] [dependencies] -AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "main" } +AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "mainnet" } AaveAcl = { local = "./aave-acl" } AaveConfig = { local = "./aave-config" } AaveMath = { local = "./aave-math" } diff --git a/aave-core/aave-acl/Move.toml b/aave-core/aave-acl/Move.toml index 2fb44fe..2dd588c 100644 --- a/aave-core/aave-acl/Move.toml +++ b/aave-core/aave-acl/Move.toml @@ -10,6 +10,6 @@ aave_acl = '_' [dev-addresses] [dependencies] -AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "main" } +AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "mainnet" } [dev-dependencies] \ No newline at end of file diff --git a/aave-core/aave-acl/doc/acl_manage.md b/aave-core/aave-acl/doc/acl_manage.md index 58fdaaf..933bcfd 100644 --- a/aave-core/aave-acl/doc/acl_manage.md +++ b/aave-core/aave-acl/doc/acl_manage.md @@ -1,74 +1,170 @@ - + + +# Module `0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage` + +@title ACLManager +@author Aave +@notice Access Control List Manager. Main registry of system roles and permissions. + +Roles are referred to by their vector<u8> identifier. These should be exposed +in the external API and be unique. The best way to achieve this is by +using const hash digests: +``` +const MY_ROLE = b"MY_ROLE"; +``` +Roles can be used to represent a set of permissions. To restrict access to a +function call, use {has_role}: +``` +public fun foo() { +assert!(has_role(MY_ROLE, error_code::ENOT_MANAGEMENT)); +... +} +``` +Roles can be granted and revoked dynamically via the {grant_role} and +{revoke_role} functions. Each role has an associated admin role, and only +accounts that have a role's admin role can call {grant_role} and {revoke_role}. + +By default, the admin role for all roles is DEFAULT_ADMIN_ROLE, which means +that only accounts with this role will be able to grant or revoke other +roles. More complex role relationships can be created by using +{set_role_admin}. + +WARNING: The DEFAULT_ADMIN_ROLE is also its own admin: it has permission to +grant and revoke this role. Extra precautions should be taken to secure +accounts that have been granted it. + + +- [Struct `RoleAdminChanged`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_RoleAdminChanged) +- [Struct `RoleGranted`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_RoleGranted) +- [Struct `RoleRevoked`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_RoleRevoked) +- [Struct `RoleData`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_RoleData) +- [Resource `Roles`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_Roles) +- [Constants](#@Constants_0) +- [Function `grant_default_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_grant_default_admin_role) +- [Function `default_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_default_admin_role) +- [Function `get_role_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_role_admin) +- [Function `set_role_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_set_role_admin) +- [Function `has_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_has_role) +- [Function `grant_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_grant_role) +- [Function `renounce_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_renounce_role) +- [Function `revoke_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_revoke_role) +- [Function `add_pool_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_pool_admin) +- [Function `remove_pool_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_pool_admin) +- [Function `is_pool_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_pool_admin) +- [Function `add_emergency_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_emergency_admin) +- [Function `remove_emergency_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_emergency_admin) +- [Function `is_emergency_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_emergency_admin) +- [Function `add_risk_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_risk_admin) +- [Function `remove_risk_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_risk_admin) +- [Function `is_risk_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_risk_admin) +- [Function `add_flash_borrower`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_flash_borrower) +- [Function `remove_flash_borrower`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_flash_borrower) +- [Function `is_flash_borrower`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_flash_borrower) +- [Function `add_bridge`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_bridge) +- [Function `remove_bridge`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_bridge) +- [Function `is_bridge`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_bridge) +- [Function `add_asset_listing_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_asset_listing_admin) +- [Function `remove_asset_listing_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_asset_listing_admin) +- [Function `is_asset_listing_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_asset_listing_admin) +- [Function `add_funds_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_funds_admin) +- [Function `remove_funds_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_funds_admin) +- [Function `is_funds_admin`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_funds_admin) +- [Function `add_emission_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_emission_admin_role) +- [Function `remove_emission_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_emission_admin_role) +- [Function `is_emission_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_emission_admin_role) +- [Function `add_admin_controlled_ecosystem_reserve_funds_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_admin_controlled_ecosystem_reserve_funds_admin_role) +- [Function `remove_admin_controlled_ecosystem_reserve_funds_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_admin_controlled_ecosystem_reserve_funds_admin_role) +- [Function `is_admin_controlled_ecosystem_reserve_funds_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_admin_controlled_ecosystem_reserve_funds_admin_role) +- [Function `add_rewards_controller_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_add_rewards_controller_admin_role) +- [Function `remove_rewards_controller_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_remove_rewards_controller_admin_role) +- [Function `is_rewards_controller_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_is_rewards_controller_admin_role) +- [Function `get_pool_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_pool_admin_role) +- [Function `get_emergency_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_emergency_admin_role) +- [Function `get_risk_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_risk_admin_role) +- [Function `get_flash_borrower_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_flash_borrower_role) +- [Function `get_bridge_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_bridge_role) +- [Function `get_asset_listing_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_asset_listing_admin_role) +- [Function `get_funds_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_funds_admin_role) +- [Function `get_emission_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_emission_admin_role) +- [Function `get_admin_controlled_ecosystem_reserve_funds_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_admin_controlled_ecosystem_reserve_funds_admin_role) +- [Function `get_rewards_controller_admin_role`](#0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9_acl_manage_get_rewards_controller_admin_role) + + +
use 0x1::event;
+use 0x1::signer;
+use 0x1::smart_table;
+use 0x1::string;
+
-# Module `0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage` + -- [Resource `Role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_Role) -- [Constants](#@Constants_0) -- [Function `default_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_default_admin_role) -- [Function `get_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_role) -- [Function `has_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_has_role) -- [Function `grant_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_grant_role) -- [Function `revoke_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_revoke_role) -- [Function `add_pool_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_pool_admin) -- [Function `remove_pool_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_pool_admin) -- [Function `is_pool_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_pool_admin) -- [Function `add_emergency_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_emergency_admin) -- [Function `remove_emergency_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_emergency_admin) -- [Function `is_emergency_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_emergency_admin) -- [Function `add_risk_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_risk_admin) -- [Function `remove_risk_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_risk_admin) -- [Function `is_risk_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_risk_admin) -- [Function `add_flash_borrower`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_flash_borrower) -- [Function `remove_flash_borrower`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_flash_borrower) -- [Function `is_flash_borrower`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_flash_borrower) -- [Function `add_bridge`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_bridge) -- [Function `remove_bridge`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_bridge) -- [Function `is_bridge`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_bridge) -- [Function `add_asset_listing_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_asset_listing_admin) -- [Function `remove_asset_listing_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_asset_listing_admin) -- [Function `is_asset_listing_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_asset_listing_admin) -- [Function `add_funds_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_funds_admin) -- [Function `remove_funds_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_funds_admin) -- [Function `is_funds_admin`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_funds_admin) -- [Function `add_emission_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_emission_admin_role) -- [Function `remove_emission_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_emission_admin_role) -- [Function `is_emission_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_emission_admin_role) -- [Function `add_admin_controlled_ecosystem_reserve_funds_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_admin_controlled_ecosystem_reserve_funds_admin_role) -- [Function `remove_admin_controlled_ecosystem_reserve_funds_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_admin_controlled_ecosystem_reserve_funds_admin_role) -- [Function `is_admin_controlled_ecosystem_reserve_funds_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_admin_controlled_ecosystem_reserve_funds_admin_role) -- [Function `add_rewards_controller_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_add_rewards_controller_admin_role) -- [Function `remove_rewards_controller_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_remove_rewards_controller_admin_role) -- [Function `is_rewards_controller_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_is_rewards_controller_admin_role) -- [Function `get_pool_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_pool_admin_role) -- [Function `get_emergency_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_emergency_admin_role) -- [Function `get_risk_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_risk_admin_role) -- [Function `get_flash_borrower_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_flash_borrower_role) -- [Function `get_bridge_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_bridge_role) -- [Function `get_asset_listing_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_asset_listing_admin_role) -- [Function `get_funds_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_funds_admin_role) -- [Function `get_emission_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_emission_admin_role) -- [Function `get_admin_controlled_ecosystem_reserve_funds_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_admin_controlled_ecosystem_reserve_funds_admin_role) -- [Function `get_rewards_controller_admin_role`](#0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753_acl_manage_get_rewards_controller_admin_role) - - -
use 0x1::signer;
-use 0x1::smart_table;
-use 0x1::string;
-use 0x1::vector;
+## Struct `RoleAdminChanged`
+
+@dev Emitted when newAdminRole is set as ```role```'s admin role, replacing previousAdminRole
+
+DEFAULT_ADMIN_ROLE is the starting admin for all roles, despite
+{RoleAdminChanged} not being emitted signaling this.
+
+
+
#[event]
+struct RoleAdminChanged has drop, store
+
+ + + + + +## Struct `RoleGranted` + +@dev Emitted when account is granted role. + +sender is the account that originated the contract call, an admin role + + +
#[event]
+struct RoleGranted has drop, store
+
+ + + + + +## Struct `RoleRevoked` + +@dev Emitted when account is revoked role. + +sender is the account that originated the contract call: +- if using revoke_role, it is the admin role bearer +- if using renounce_role, it is the role bearer (i.e. account) + + +
#[event]
+struct RoleRevoked has drop, store
 
- + -## Resource `Role` +## Struct `RoleData` -
struct Role has store, key
+
struct RoleData has store
+
+ + + + + +## Resource `Roles` + + + +
struct Roles has key
 
@@ -78,635 +174,716 @@ ## Constants - + + + + +
const ADMIN_CONTROLLED_ECOSYSTEM_RESERVE_FUNDS_ADMIN_ROLE: vector<u8> = [65, 68, 77, 73, 78, 95, 67, 79, 78, 84, 82, 79, 76, 76, 69, 68, 95, 69, 67, 79, 83, 89, 83, 84, 69, 77, 95, 82, 69, 83, 69, 82, 86, 69, 95, 70, 85, 78, 68, 83, 95, 65, 68, 77, 73, 78];
+
+ + + + -
const ADMIN_CONTROLLED_ECOSYSTEM_RESERVE_FUNDS_ADMIN_ROLE: vector<u8> = [65, 68, 77, 73, 78, 95, 67, 79, 78, 84, 82, 79, 76, 76, 69, 68, 95, 69, 67, 79, 83, 89, 83, 84, 69, 77, 95, 82, 69, 83, 69, 82, 86, 69, 95, 70, 85, 78, 68, 83, 95, 65, 68, 77, 73, 78];
+
const ASSET_LISTING_ADMIN_ROLE: vector<u8> = [65, 83, 83, 69, 84, 95, 76, 73, 83, 84, 73, 78, 71, 95, 65, 68, 77, 73, 78];
 
- + -
const ASSET_LISTING_ADMIN_ROLE: vector<u8> = [65, 83, 83, 69, 84, 95, 76, 73, 83, 84, 73, 78, 71, 95, 65, 68, 77, 73, 78];
+
const BRIDGE_ROLE: vector<u8> = [66, 82, 73, 68, 71, 69];
 
- + -
const BRIDGE_ROLE: vector<u8> = [66, 82, 73, 68, 71, 69];
+
const DEFAULT_ADMIN_ROLE: vector<u8> = [68, 69, 70, 65, 85, 76, 84, 95, 65, 68, 77, 73, 78];
 
- + -
const EMERGENCY_ADMIN_ROLE: vector<u8> = [69, 77, 69, 82, 71, 69, 78, 67, 89, 95, 65, 68, 77, 73, 78];
+
const EMERGENCY_ADMIN_ROLE: vector<u8> = [69, 77, 69, 82, 71, 69, 78, 67, 89, 95, 65, 68, 77, 73, 78];
 
- + -
const EMISSION_ADMIN_ROLE: vector<u8> = [69, 77, 73, 83, 83, 73, 79, 78, 95, 65, 68, 77, 73, 78, 95, 82, 79, 76, 69];
+
const EMISSION_ADMIN_ROLE: vector<u8> = [69, 77, 73, 83, 83, 73, 79, 78, 95, 65, 68, 77, 73, 78, 95, 82, 79, 76, 69];
 
- + -
const ENOT_MANAGEMENT: u64 = 1;
+
const ENOT_MANAGEMENT: u64 = 1;
 
- + -
const EROLE_ALREADY_EXISTS: u64 = 2;
+
const EROLE_CAN_ONLY_RENOUNCE_SELF: u64 = 4;
 
- + -
const EROLE_NOT_EXISTS: u64 = 3;
+
const EROLE_NOT_ADMIN: u64 = 3;
 
- + -
const FLASH_BORROWER_ROLE: vector<u8> = [70, 76, 65, 83, 72, 95, 66, 79, 82, 82, 79, 87, 69, 82];
+
const EROLE_NOT_EXISTS: u64 = 2;
 
- + -
const FUNDS_ADMIN_ROLE: vector<u8> = [70, 85, 78, 68, 83, 95, 65, 68, 77, 73, 78];
+
const FLASH_BORROWER_ROLE: vector<u8> = [70, 76, 65, 83, 72, 95, 66, 79, 82, 82, 79, 87, 69, 82];
 
- + -
const POOL_ADMIN_ROLE: vector<u8> = [80, 79, 79, 76, 95, 65, 68, 77, 73, 78];
+
const FUNDS_ADMIN_ROLE: vector<u8> = [70, 85, 78, 68, 83, 95, 65, 68, 77, 73, 78];
 
- + -
const REWARDS_CONTROLLER_ADMIN_ROLE: vector<u8> = [82, 69, 87, 65, 82, 68, 83, 95, 67, 79, 78, 84, 82, 79, 76, 76, 69, 82, 95, 65, 68, 77, 73, 78, 95, 82, 79, 76, 69];
+
const POOL_ADMIN_ROLE: vector<u8> = [80, 79, 79, 76, 95, 65, 68, 77, 73, 78];
 
- + -
const RISK_ADMIN_ROLE: vector<u8> = [82, 73, 83, 75, 95, 65, 68, 77, 73, 78];
+
const REWARDS_CONTROLLER_ADMIN_ROLE: vector<u8> = [82, 69, 87, 65, 82, 68, 83, 95, 67, 79, 78, 84, 82, 79, 76, 76, 69, 82, 95, 65, 68, 77, 73, 78, 95, 82, 79, 76, 69];
 
- + + + + +
const RISK_ADMIN_ROLE: vector<u8> = [82, 73, 83, 75, 95, 65, 68, 77, 73, 78];
+
+ + + + + +## Function `grant_default_admin_role` + + + +
public entry fun grant_default_admin_role(admin: &signer)
+
+ + + + ## Function `default_admin_role`
#[view]
-public fun default_admin_role(): address
+public fun default_admin_role(): string::String
 
- + -## Function `get_role` +## Function `get_role_admin` +@dev Returns the admin role that controls role.
#[view]
-public fun get_role(role: string::String, user: address): vector<address>
+public fun get_role_admin(role: string::String): string::String
+
+ + + + + +## Function `set_role_admin` + +@dev Sets adminRole as ```role```'s admin role. +Emits a {RoleAdminChanged} event. + + +
public entry fun set_role_admin(admin: &signer, role: string::String, admin_role: string::String)
 
- + ## Function `has_role` +@dev Returns true if account has been granted role.
#[view]
-public fun has_role(role: string::String, user: address): bool
+public fun has_role(role: string::String, user: address): bool
 
- + ## Function `grant_role` +@dev Grants role to account. + +If account had not been already granted role, emits a {RoleGranted} +event. + +Requirements: +- the caller must have ```role```'s admin role. -
public entry fun grant_role(admin: &signer, role: string::String, user: address)
+
+
public entry fun grant_role(admin: &signer, role: string::String, user: address)
 
- + + +## Function `renounce_role` + +@dev Revokes role from the calling account. +Roles are often managed via {grant_role} and {revoke_role}: this function's +purpose is to provide a mechanism for accounts to lose their privileges +if they are compromised (such as when a trusted device is misplaced). + +If the calling account had been granted role, emits a {role_revoked} +event. + +Requirements: + +- the caller must be account. + + +
public entry fun renounce_role(admin: &signer, role: string::String, user: address)
+
+ + + + ## Function `revoke_role` +@dev Revokes role from account. + +If account had been granted role, emits a {RoleRevoked} event. + +Requirements: + +- the caller must have ```role```'s admin role. -
public entry fun revoke_role(admin: &signer, role: string::String, user: address)
+
public entry fun revoke_role(admin: &signer, role: string::String, user: address)
 
- + ## Function `add_pool_admin` -
public entry fun add_pool_admin(admin: &signer, user: address)
+
public entry fun add_pool_admin(admin: &signer, user: address)
 
- + ## Function `remove_pool_admin` -
public entry fun remove_pool_admin(admin: &signer, user: address)
+
public entry fun remove_pool_admin(admin: &signer, user: address)
 
- + ## Function `is_pool_admin`
#[view]
-public fun is_pool_admin(admin: address): bool
+public fun is_pool_admin(admin: address): bool
 
- + ## Function `add_emergency_admin` -
public entry fun add_emergency_admin(admin: &signer, user: address)
+
public entry fun add_emergency_admin(admin: &signer, user: address)
 
- + ## Function `remove_emergency_admin` -
public entry fun remove_emergency_admin(admin: &signer, user: address)
+
public entry fun remove_emergency_admin(admin: &signer, user: address)
 
- + ## Function `is_emergency_admin`
#[view]
-public fun is_emergency_admin(admin: address): bool
+public fun is_emergency_admin(admin: address): bool
 
- + ## Function `add_risk_admin` -
public entry fun add_risk_admin(admin: &signer, user: address)
+
public entry fun add_risk_admin(admin: &signer, user: address)
 
- + ## Function `remove_risk_admin` -
public entry fun remove_risk_admin(admin: &signer, user: address)
+
public entry fun remove_risk_admin(admin: &signer, user: address)
 
- + ## Function `is_risk_admin`
#[view]
-public fun is_risk_admin(admin: address): bool
+public fun is_risk_admin(admin: address): bool
 
- + ## Function `add_flash_borrower` -
public entry fun add_flash_borrower(admin: &signer, borrower: address)
+
public entry fun add_flash_borrower(admin: &signer, borrower: address)
 
- + ## Function `remove_flash_borrower` -
public entry fun remove_flash_borrower(admin: &signer, borrower: address)
+
public entry fun remove_flash_borrower(admin: &signer, borrower: address)
 
- + ## Function `is_flash_borrower`
#[view]
-public fun is_flash_borrower(borrower: address): bool
+public fun is_flash_borrower(borrower: address): bool
 
- + ## Function `add_bridge` -
public entry fun add_bridge(admin: &signer, bridge: address)
+
public entry fun add_bridge(admin: &signer, bridge: address)
 
- + ## Function `remove_bridge` -
public entry fun remove_bridge(admin: &signer, bridge: address)
+
public entry fun remove_bridge(admin: &signer, bridge: address)
 
- + ## Function `is_bridge`
#[view]
-public fun is_bridge(bridge: address): bool
+public fun is_bridge(bridge: address): bool
 
- + ## Function `add_asset_listing_admin` -
public entry fun add_asset_listing_admin(admin: &signer, user: address)
+
public entry fun add_asset_listing_admin(admin: &signer, user: address)
 
- + ## Function `remove_asset_listing_admin` -
public entry fun remove_asset_listing_admin(admin: &signer, user: address)
+
public entry fun remove_asset_listing_admin(admin: &signer, user: address)
 
- + ## Function `is_asset_listing_admin`
#[view]
-public fun is_asset_listing_admin(admin: address): bool
+public fun is_asset_listing_admin(admin: address): bool
 
- + ## Function `add_funds_admin` -
public entry fun add_funds_admin(admin: &signer, user: address)
+
public entry fun add_funds_admin(admin: &signer, user: address)
 
- + ## Function `remove_funds_admin` -
public entry fun remove_funds_admin(admin: &signer, user: address)
+
public entry fun remove_funds_admin(admin: &signer, user: address)
 
- + ## Function `is_funds_admin`
#[view]
-public fun is_funds_admin(admin: address): bool
+public fun is_funds_admin(admin: address): bool
 
- + ## Function `add_emission_admin_role` -
public entry fun add_emission_admin_role(admin: &signer, user: address)
+
public entry fun add_emission_admin_role(admin: &signer, user: address)
 
- + ## Function `remove_emission_admin_role` -
public entry fun remove_emission_admin_role(admin: &signer, user: address)
+
public entry fun remove_emission_admin_role(admin: &signer, user: address)
 
- + ## Function `is_emission_admin_role`
#[view]
-public fun is_emission_admin_role(admin: address): bool
+public fun is_emission_admin_role(admin: address): bool
 
- + ## Function `add_admin_controlled_ecosystem_reserve_funds_admin_role` -
public entry fun add_admin_controlled_ecosystem_reserve_funds_admin_role(admin: &signer, user: address)
+
public entry fun add_admin_controlled_ecosystem_reserve_funds_admin_role(admin: &signer, user: address)
 
- + ## Function `remove_admin_controlled_ecosystem_reserve_funds_admin_role` -
public entry fun remove_admin_controlled_ecosystem_reserve_funds_admin_role(admin: &signer, user: address)
+
public entry fun remove_admin_controlled_ecosystem_reserve_funds_admin_role(admin: &signer, user: address)
 
- + ## Function `is_admin_controlled_ecosystem_reserve_funds_admin_role`
#[view]
-public fun is_admin_controlled_ecosystem_reserve_funds_admin_role(admin: address): bool
+public fun is_admin_controlled_ecosystem_reserve_funds_admin_role(admin: address): bool
 
- + ## Function `add_rewards_controller_admin_role` -
public entry fun add_rewards_controller_admin_role(admin: &signer, user: address)
+
public entry fun add_rewards_controller_admin_role(admin: &signer, user: address)
 
- + ## Function `remove_rewards_controller_admin_role` -
public entry fun remove_rewards_controller_admin_role(admin: &signer, user: address)
+
public entry fun remove_rewards_controller_admin_role(admin: &signer, user: address)
 
- + ## Function `is_rewards_controller_admin_role`
#[view]
-public fun is_rewards_controller_admin_role(admin: address): bool
+public fun is_rewards_controller_admin_role(admin: address): bool
 
- + ## Function `get_pool_admin_role`
#[view]
-public fun get_pool_admin_role(): string::String
+public fun get_pool_admin_role(): string::String
 
- + ## Function `get_emergency_admin_role`
#[view]
-public fun get_emergency_admin_role(): string::String
+public fun get_emergency_admin_role(): string::String
 
- + ## Function `get_risk_admin_role`
#[view]
-public fun get_risk_admin_role(): string::String
+public fun get_risk_admin_role(): string::String
 
- + ## Function `get_flash_borrower_role`
#[view]
-public fun get_flash_borrower_role(): string::String
+public fun get_flash_borrower_role(): string::String
 
- + ## Function `get_bridge_role`
#[view]
-public fun get_bridge_role(): string::String
+public fun get_bridge_role(): string::String
 
- + ## Function `get_asset_listing_admin_role`
#[view]
-public fun get_asset_listing_admin_role(): string::String
+public fun get_asset_listing_admin_role(): string::String
 
- + ## Function `get_funds_admin_role`
#[view]
-public fun get_funds_admin_role(): string::String
+public fun get_funds_admin_role(): string::String
 
- + ## Function `get_emission_admin_role`
#[view]
-public fun get_emission_admin_role(): string::String
+public fun get_emission_admin_role(): string::String
 
- + ## Function `get_admin_controlled_ecosystem_reserve_funds_admin_role`
#[view]
-public fun get_admin_controlled_ecosystem_reserve_funds_admin_role(): string::String
+public fun get_admin_controlled_ecosystem_reserve_funds_admin_role(): string::String
 
- + ## Function `get_rewards_controller_admin_role`
#[view]
-public fun get_rewards_controller_admin_role(): string::String
+public fun get_rewards_controller_admin_role(): string::String
 
diff --git a/aave-core/aave-acl/sources/acl_manage.move b/aave-core/aave-acl/sources/acl_manage.move index c40fc7a..fc9f555 100644 --- a/aave-core/aave-acl/sources/acl_manage.move +++ b/aave-core/aave-acl/sources/acl_manage.move @@ -1,9 +1,40 @@ +/// @title ACLManager +/// @author Aave +/// @notice Access Control List Manager. Main registry of system roles and permissions. +/// +/// Roles are referred to by their `vector` identifier. These should be exposed +/// in the external API and be unique. The best way to achieve this is by +/// using `const` hash digests: +/// ``` +/// const MY_ROLE = b"MY_ROLE"; +/// ``` +/// Roles can be used to represent a set of permissions. To restrict access to a +/// function call, use {has_role}: +/// ``` +/// public fun foo() { +/// assert!(has_role(MY_ROLE, error_code::ENOT_MANAGEMENT)); +/// ... +/// } +/// ``` +/// Roles can be granted and revoked dynamically via the {grant_role} and +/// {revoke_role} functions. Each role has an associated admin role, and only +/// accounts that have a role's admin role can call {grant_role} and {revoke_role}. +/// +/// By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means +/// that only accounts with this role will be able to grant or revoke other +/// roles. More complex role relationships can be created by using +/// {set_role_admin}. +/// +/// WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to +/// grant and revoke this role. Extra precautions should be taken to secure +/// accounts that have been granted it. module aave_acl::acl_manage { use std::signer; - use std::vector; use std::string::{Self, String}; use aptos_std::smart_table::{Self, SmartTable}; + use aptos_framework::event; + const DEFAULT_ADMIN_ROLE: vector = b"DEFAULT_ADMIN"; const POOL_ADMIN_ROLE: vector = b"POOL_ADMIN"; const EMERGENCY_ADMIN_ROLE: vector = b"EMERGENCY_ADMIN"; const RISK_ADMIN_ROLE: vector = b"RISK_ADMIN"; @@ -17,216 +48,357 @@ module aave_acl::acl_manage { // You are not an administrator and cannot initialize resources. const ENOT_MANAGEMENT: u64 = 1; - // Role already exists. - const EROLE_ALREADY_EXISTS: u64 = 2; // Role does not exist. - const EROLE_NOT_EXISTS: u64 = 3; - - struct Role has key, store { - acl_instance: SmartTable> + const EROLE_NOT_EXISTS: u64 = 2; + // The role must be admin + const EROLE_NOT_ADMIN: u64 = 3; + // can only renounce roles for self + const EROLE_CAN_ONLY_RENOUNCE_SELF: u64 = 4; + + #[event] + /// @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` + /// + /// `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite + /// {RoleAdminChanged} not being emitted signaling this. + struct RoleAdminChanged has store, drop { + role: String, + previous_admin_role: String, + new_admin_role: String + } + + #[event] + /// @dev Emitted when `account` is granted `role`. + /// + /// `sender` is the account that originated the contract call, an admin role + struct RoleGranted has store, drop { + role: String, + account: address, + sender: address + } + + #[event] + /// @dev Emitted when `account` is revoked `role`. + /// + /// `sender` is the account that originated the contract call: + /// - if using `revoke_role`, it is the admin role bearer + /// - if using `renounce_role`, it is the role bearer (i.e. `account`) + struct RoleRevoked has store, drop { + role: String, + account: address, + sender: address + } + + struct RoleData has store { + members: SmartTable, + admin_role: String + } + + struct Roles has key { + acl_instance: SmartTable } #[test_only] - public fun test_init_module(user: &signer) { + public fun test_init_module(user: &signer) acquires Roles { init_module(user); + grant_default_admin_role(user); } - fun init_module(user: &signer) { - check_super_admin(signer::address_of(user)); + fun init_module(admin: &signer) { + let admin_address = signer::address_of(admin); + check_super_admin(admin_address); + move_to(admin, Roles { acl_instance: smart_table::new() }); + } - move_to(user, Role { acl_instance: smart_table::new>() }) + public entry fun grant_default_admin_role(admin: &signer) acquires Roles { + let admin_address = signer::address_of(admin); + check_super_admin(admin_address); + grant_role_internal(admin, default_admin_role(), admin_address); } - fun check_super_admin(user: address) { - assert!(user == @aave_acl, ENOT_MANAGEMENT); + fun check_super_admin(admin: address) { + assert!(admin == @aave_acl, ENOT_MANAGEMENT); + } + + fun only_role(role: String, user: address) acquires Roles { + assert!(has_role(role, user), EROLE_NOT_ADMIN); } #[view] - public fun default_admin_role(): address { - @aave_acl + public fun default_admin_role(): String { + string::utf8(DEFAULT_ADMIN_ROLE) } #[view] - public fun get_role(role: String, user: address): vector
acquires Role { - check_super_admin(user); - let role_res = borrow_global(@aave_acl); + /// @dev Returns the admin role that controls `role`. + public fun get_role_admin(role: String): String acquires Roles { + let roles = borrow_global(@aave_acl); + if (!smart_table::contains(&roles.acl_instance, role)) { + return string::utf8(DEFAULT_ADMIN_ROLE) + }; - *smart_table::borrow(&role_res.acl_instance, role) + smart_table::borrow(&roles.acl_instance, role).admin_role + } + + /// @dev Sets `adminRole` as ``role``'s admin role. + /// Emits a {RoleAdminChanged} event. + public entry fun set_role_admin( + admin: &signer, role: String, admin_role: String + ) acquires Roles { + only_role(default_admin_role(), signer::address_of(admin)); + let previous_admin_role = get_role_admin(role); + + let role_res = borrow_global_mut(@aave_acl); + assert!(smart_table::contains(&mut role_res.acl_instance, role), EROLE_NOT_EXISTS); + + let role_data = smart_table::borrow_mut(&mut role_res.acl_instance, role); + role_data.admin_role = admin_role; + + event::emit( + RoleAdminChanged { role, previous_admin_role, new_admin_role: admin_role } + ); } #[view] - public fun has_role(role: String, user: address): bool acquires Role { - let role_res = borrow_global(@aave_acl); + /// @dev Returns `true` if `account` has been granted `role`. + public fun has_role(role: String, user: address): bool acquires Roles { + let role_res = borrow_global(@aave_acl); if (!smart_table::contains(&role_res.acl_instance, role)) { return false }; - let role_addr_list = smart_table::borrow(&role_res.acl_instance, role); - - vector::contains(role_addr_list, &user) - } - - public entry fun grant_role(admin: &signer, role: String, user: address) acquires Role { - check_super_admin(signer::address_of(admin)); - let role_res = borrow_global_mut(@aave_acl); - if (!smart_table::contains(&mut role_res.acl_instance, role)) { - let vector_addr_list = vector
[]; - vector::push_back(&mut vector_addr_list, user); - smart_table::add(&mut role_res.acl_instance, role, vector_addr_list); - } else { - let role_addr_list = smart_table::borrow_mut(&mut role_res.acl_instance, role); - assert!(!vector::contains(role_addr_list, &user), EROLE_ALREADY_EXISTS); - let role_addr_list = smart_table::borrow_mut(&mut role_res.acl_instance, role); - vector::push_back(role_addr_list, user); + let role_data = smart_table::borrow(&role_res.acl_instance, role); + if (!smart_table::contains(&role_data.members, user)) { + return false + }; + + *smart_table::borrow(&role_data.members, user) + } + + /// @dev Grants `role` to `account`. + /// + /// If `account` had not been already granted `role`, emits a {RoleGranted} + /// event. + /// + /// Requirements: + /// + /// - the caller must have ``role``'s admin role. + public entry fun grant_role( + admin: &signer, role: String, user: address + ) acquires Roles { + let admin_address = signer::address_of(admin); + only_role(get_role_admin(role), admin_address); + grant_role_internal(admin, role, user); + } + + fun grant_role_internal(admin: &signer, role: String, user: address) acquires Roles { + if (!has_role(role, user)) { + let role_res = borrow_global_mut(@aave_acl); + if (!smart_table::contains(&role_res.acl_instance, role)) { + let members = smart_table::new(); + smart_table::add(&mut members, user, true); + let role_data = RoleData { members, admin_role: default_admin_role() }; + smart_table::add(&mut role_res.acl_instance, role, role_data); + } else { + let role_data = smart_table::borrow_mut(&mut role_res.acl_instance, role); + smart_table::upsert(&mut role_data.members, user, true); + }; + + event::emit( + RoleGranted { role, account: user, sender: signer::address_of(admin) } + ); } } - public entry fun revoke_role(admin: &signer, role: String, user: address) acquires Role { - check_super_admin(signer::address_of(admin)); - assert!(has_role(role, user), EROLE_NOT_EXISTS); - - let role_res = borrow_global_mut(@aave_acl); - let role_addr_list = smart_table::borrow_mut(&mut role_res.acl_instance, role); - - let _ = vector::remove_value(role_addr_list, &user); + /// @dev Revokes `role` from the calling account. + /// Roles are often managed via {grant_role} and {revoke_role}: this function's + /// purpose is to provide a mechanism for accounts to lose their privileges + /// if they are compromised (such as when a trusted device is misplaced). + /// + /// If the calling account had been granted `role`, emits a {role_revoked} + /// event. + /// + /// Requirements: + /// + /// - the caller must be `account`. + public entry fun renounce_role( + admin: &signer, role: String, user: address + ) acquires Roles { + assert!(signer::address_of(admin) == user, EROLE_CAN_ONLY_RENOUNCE_SELF); + revoke_role_internal(admin, role, user); + } + + /// @dev Revokes `role` from `account`. + /// + /// If `account` had been granted `role`, emits a {RoleRevoked} event. + /// + /// Requirements: + /// + /// - the caller must have ``role``'s admin role. + /// + public entry fun revoke_role( + admin: &signer, role: String, user: address + ) acquires Roles { + let admin_address = signer::address_of(admin); + only_role(get_role_admin(role), admin_address); + revoke_role_internal(admin, role, user); + } + + fun revoke_role_internal(admin: &signer, role: String, user: address) acquires Roles { + if (has_role(role, user)) { + let role_res = borrow_global_mut(@aave_acl); + let role_data = smart_table::borrow_mut(&mut role_res.acl_instance, role); + smart_table::upsert(&mut role_data.members, user, false); + + event::emit( + RoleRevoked { role, account: user, sender: signer::address_of(admin) } + ); + } } - public entry fun add_pool_admin(admin: &signer, user: address) acquires Role { + public entry fun add_pool_admin(admin: &signer, user: address) acquires Roles { grant_role(admin, get_pool_admin_role(), user); } - public entry fun remove_pool_admin(admin: &signer, user: address) acquires Role { + public entry fun remove_pool_admin(admin: &signer, user: address) acquires Roles { revoke_role(admin, get_pool_admin_role(), user); } #[view] - public fun is_pool_admin(admin: address): bool acquires Role { + public fun is_pool_admin(admin: address): bool acquires Roles { has_role(get_pool_admin_role(), admin) } - public entry fun add_emergency_admin(admin: &signer, user: address) acquires Role { + public entry fun add_emergency_admin(admin: &signer, user: address) acquires Roles { grant_role(admin, get_emergency_admin_role(), user); } - public entry fun remove_emergency_admin(admin: &signer, user: address) acquires Role { + public entry fun remove_emergency_admin(admin: &signer, user: address) acquires Roles { revoke_role(admin, get_emergency_admin_role(), user); } #[view] - public fun is_emergency_admin(admin: address): bool acquires Role { + public fun is_emergency_admin(admin: address): bool acquires Roles { has_role(get_emergency_admin_role(), admin) } - public entry fun add_risk_admin(admin: &signer, user: address) acquires Role { + public entry fun add_risk_admin(admin: &signer, user: address) acquires Roles { grant_role(admin, get_risk_admin_role(), user); } - public entry fun remove_risk_admin(admin: &signer, user: address) acquires Role { + public entry fun remove_risk_admin(admin: &signer, user: address) acquires Roles { revoke_role(admin, get_risk_admin_role(), user); } #[view] - public fun is_risk_admin(admin: address): bool acquires Role { + public fun is_risk_admin(admin: address): bool acquires Roles { has_role(get_risk_admin_role(), admin) } - public entry fun add_flash_borrower(admin: &signer, borrower: address) acquires Role { + public entry fun add_flash_borrower(admin: &signer, borrower: address) acquires Roles { grant_role(admin, get_flash_borrower_role(), borrower); } - public entry fun remove_flash_borrower(admin: &signer, borrower: address) acquires Role { + public entry fun remove_flash_borrower( + admin: &signer, borrower: address + ) acquires Roles { revoke_role(admin, get_flash_borrower_role(), borrower); } #[view] - public fun is_flash_borrower(borrower: address): bool acquires Role { + public fun is_flash_borrower(borrower: address): bool acquires Roles { has_role(get_flash_borrower_role(), borrower) } - public entry fun add_bridge(admin: &signer, bridge: address) acquires Role { + public entry fun add_bridge(admin: &signer, bridge: address) acquires Roles { grant_role(admin, get_bridge_role(), bridge); } - public entry fun remove_bridge(admin: &signer, bridge: address) acquires Role { + public entry fun remove_bridge(admin: &signer, bridge: address) acquires Roles { revoke_role(admin, get_bridge_role(), bridge); } #[view] - public fun is_bridge(bridge: address): bool acquires Role { + public fun is_bridge(bridge: address): bool acquires Roles { has_role(get_bridge_role(), bridge) } - public entry fun add_asset_listing_admin(admin: &signer, user: address) acquires Role { + public entry fun add_asset_listing_admin(admin: &signer, user: address) acquires Roles { grant_role(admin, get_asset_listing_admin_role(), user); } - public entry fun remove_asset_listing_admin(admin: &signer, user: address) acquires Role { + public entry fun remove_asset_listing_admin( + admin: &signer, user: address + ) acquires Roles { revoke_role(admin, get_asset_listing_admin_role(), user); } #[view] - public fun is_asset_listing_admin(admin: address): bool acquires Role { + public fun is_asset_listing_admin(admin: address): bool acquires Roles { has_role(get_asset_listing_admin_role(), admin) } - public entry fun add_funds_admin(admin: &signer, user: address) acquires Role { + public entry fun add_funds_admin(admin: &signer, user: address) acquires Roles { grant_role(admin, get_funds_admin_role(), user); } - public entry fun remove_funds_admin(admin: &signer, user: address) acquires Role { + public entry fun remove_funds_admin(admin: &signer, user: address) acquires Roles { revoke_role(admin, get_funds_admin_role(), user); } #[view] - public fun is_funds_admin(admin: address): bool acquires Role { + public fun is_funds_admin(admin: address): bool acquires Roles { has_role(get_funds_admin_role(), admin) } - public entry fun add_emission_admin_role(admin: &signer, user: address) acquires Role { + public entry fun add_emission_admin_role(admin: &signer, user: address) acquires Roles { grant_role(admin, get_emission_admin_role(), user); } - public entry fun remove_emission_admin_role(admin: &signer, user: address) acquires Role { + public entry fun remove_emission_admin_role( + admin: &signer, user: address + ) acquires Roles { revoke_role(admin, get_emission_admin_role(), user); } #[view] - public fun is_emission_admin_role(admin: address): bool acquires Role { + public fun is_emission_admin_role(admin: address): bool acquires Roles { has_role(get_emission_admin_role(), admin) } public entry fun add_admin_controlled_ecosystem_reserve_funds_admin_role( admin: &signer, user: address - ) acquires Role { + ) acquires Roles { grant_role(admin, get_admin_controlled_ecosystem_reserve_funds_admin_role(), user); } public entry fun remove_admin_controlled_ecosystem_reserve_funds_admin_role( admin: &signer, user: address - ) acquires Role { - revoke_role(admin, get_admin_controlled_ecosystem_reserve_funds_admin_role(), user); + ) acquires Roles { + revoke_role( + admin, get_admin_controlled_ecosystem_reserve_funds_admin_role(), user + ); } #[view] public fun is_admin_controlled_ecosystem_reserve_funds_admin_role( admin: address - ): bool acquires Role { + ): bool acquires Roles { has_role(get_admin_controlled_ecosystem_reserve_funds_admin_role(), admin) } public entry fun add_rewards_controller_admin_role( admin: &signer, user: address - ) acquires Role { + ) acquires Roles { grant_role(admin, get_rewards_controller_admin_role(), user); } public entry fun remove_rewards_controller_admin_role( admin: &signer, user: address - ) acquires Role { + ) acquires Roles { revoke_role(admin, get_rewards_controller_admin_role(), user); } #[view] - public fun is_rewards_controller_admin_role(admin: address): bool acquires Role { + public fun is_rewards_controller_admin_role(admin: address): bool acquires Roles { has_role(get_rewards_controller_admin_role(), admin) } @@ -309,4 +481,24 @@ module aave_acl::acl_manage { public fun get_asset_listing_admin_role_for_testing(): String { string::utf8(ASSET_LISTING_ADMIN_ROLE) } + + #[test_only] + public fun get_funds_admin_role_for_testing(): String { + string::utf8(FUNDS_ADMIN_ROLE) + } + + #[test_only] + public fun get_emissions_admin_role_for_testing(): String { + string::utf8(EMISSION_ADMIN_ROLE) + } + + #[test_only] + public fun get_admin_controlled_ecosystem_reserve_funds_admin_role_for_testing(): String { + string::utf8(ADMIN_CONTROLLED_ECOSYSTEM_RESERVE_FUNDS_ADMIN_ROLE) + } + + #[test_only] + public fun get_rewards_controller_admin_role_for_testing(): String { + string::utf8(REWARDS_CONTROLLER_ADMIN_ROLE) + } } diff --git a/aave-core/aave-acl/tests/acl_manage_tests.move b/aave-core/aave-acl/tests/acl_manage_tests.move index 27b6ee7..f0f8f30 100644 --- a/aave-core/aave-acl/tests/acl_manage_tests.move +++ b/aave-core/aave-acl/tests/acl_manage_tests.move @@ -1,53 +1,64 @@ #[test_only] module aave_acl::acl_manage_tests { use std::signer; + use std::string::utf8; + use aave_acl::acl_manage::{ - test_init_module, - add_pool_admin, + add_admin_controlled_ecosystem_reserve_funds_admin_role, add_asset_listing_admin, - has_role, - grant_role, - is_pool_admin, - is_asset_listing_admin, - remove_risk_admin, - is_risk_admin, - add_risk_admin, - remove_flash_borrower, - is_flash_borrower, - add_flash_borrower, - is_emergency_admin, - remove_emergency_admin, - add_emergency_admin, - is_bridge, - remove_bridge, add_bridge, - remove_asset_listing_admin, - revoke_role, + add_emergency_admin, + add_emission_admin_role, + add_flash_borrower, + add_funds_admin, + add_pool_admin, + add_rewards_controller_admin_role, + add_risk_admin, get_asset_listing_admin_role, + get_asset_listing_admin_role_for_testing, get_bridge_role, + get_bridge_role_for_testing, get_emergency_admin_role, + get_emergency_admin_role_for_testing, get_flash_borrower_role, + get_flash_borrower_role_for_testing, get_pool_admin_role, - get_risk_admin_role, - remove_pool_admin, get_pool_admin_role_for_testing, - get_emergency_admin_role_for_testing, + get_risk_admin_role, get_risk_admin_role_for_testing, - get_flash_borrower_role_for_testing, - get_bridge_role_for_testing, - get_asset_listing_admin_role_for_testing, - add_funds_admin, - remove_funds_admin, - is_funds_admin, - add_emission_admin_role, - remove_emission_admin_role, + grant_role, + has_role, + is_admin_controlled_ecosystem_reserve_funds_admin_role, + is_asset_listing_admin, + is_bridge, + is_emergency_admin, is_emission_admin_role, - add_admin_controlled_ecosystem_reserve_funds_admin_role, + is_flash_borrower, + is_funds_admin, + is_pool_admin, + is_rewards_controller_admin_role, + is_risk_admin, remove_admin_controlled_ecosystem_reserve_funds_admin_role, - is_admin_controlled_ecosystem_reserve_funds_admin_role, - add_rewards_controller_admin_role, + remove_asset_listing_admin, + remove_bridge, + remove_emergency_admin, + remove_emission_admin_role, + remove_flash_borrower, + remove_funds_admin, + remove_pool_admin, remove_rewards_controller_admin_role, - is_rewards_controller_admin_role + remove_risk_admin, + revoke_role, + set_role_admin, + test_init_module, + get_funds_admin_role, + get_funds_admin_role_for_testing, + get_emission_admin_role, + get_emissions_admin_role_for_testing, + get_admin_controlled_ecosystem_reserve_funds_admin_role, + get_admin_controlled_ecosystem_reserve_funds_admin_role_for_testing, + get_rewards_controller_admin_role, + get_rewards_controller_admin_role_for_testing }; const TEST_SUCCESS: u64 = 1; @@ -56,8 +67,10 @@ module aave_acl::acl_manage_tests { // ========== TEST: BASIC GETTERS ============ #[test] fun test_asset_listing_admin_role() { - assert!(get_asset_listing_admin_role() == get_asset_listing_admin_role_for_testing(), - TEST_SUCCESS); + assert!( + get_asset_listing_admin_role() == get_asset_listing_admin_role_for_testing(), + TEST_SUCCESS, + ); } #[test] @@ -67,8 +80,10 @@ module aave_acl::acl_manage_tests { #[test] fun test_get_flash_borrower_role() { - assert!(get_flash_borrower_role() == get_flash_borrower_role_for_testing(), - TEST_SUCCESS); + assert!( + get_flash_borrower_role() == get_flash_borrower_role_for_testing(), + TEST_SUCCESS, + ); } #[test] @@ -78,8 +93,10 @@ module aave_acl::acl_manage_tests { #[test] fun test_get_emergency_admin_role() { - assert!(get_emergency_admin_role() == get_emergency_admin_role_for_testing(), - TEST_SUCCESS); + assert!( + get_emergency_admin_role() == get_emergency_admin_role_for_testing(), + TEST_SUCCESS, + ); } #[test] @@ -87,15 +104,53 @@ module aave_acl::acl_manage_tests { assert!(get_pool_admin_role() == get_pool_admin_role_for_testing(), TEST_SUCCESS); } + #[test] + fun test_funds_admin_role() { + assert!( + get_funds_admin_role() == get_funds_admin_role_for_testing(), TEST_SUCCESS + ); + } + + #[test] + fun test_emission_admin_role() { + assert!( + get_emission_admin_role() == get_emissions_admin_role_for_testing(), + TEST_SUCCESS, + ); + } + + #[test] + fun test_admin_controlled_ecosystem_reserve_funds_admin_role() { + assert!( + get_admin_controlled_ecosystem_reserve_funds_admin_role() + == get_admin_controlled_ecosystem_reserve_funds_admin_role_for_testing(), + TEST_SUCCESS, + ); + } + + #[test] + fun test_rewards_controller_admin_role() { + assert!( + get_rewards_controller_admin_role() + == get_rewards_controller_admin_role_for_testing(), + TEST_SUCCESS, + ); + } + // ========== TEST: TEST OWNER HOLDERS ============ #[test(super_admin = @aave_acl, test_addr = @0x01)] - fun test_is_asset_listing_admin(super_admin: &signer, test_addr: &signer) { + fun test_is_asset_listing_admin( + super_admin: &signer, test_addr: &signer + ) { // init the module test_init_module(super_admin); // add the asset listing role to some address - grant_role(super_admin, get_asset_listing_admin_role_for_testing(), - signer::address_of(test_addr)); + grant_role( + super_admin, + get_asset_listing_admin_role_for_testing(), + signer::address_of(test_addr), + ); // check the address has the role assigned assert!(is_asset_listing_admin(signer::address_of(test_addr)), TEST_SUCCESS); } @@ -105,7 +160,9 @@ module aave_acl::acl_manage_tests { // init the module test_init_module(super_admin); // add the asset listing role to some address - grant_role(super_admin, get_bridge_role_for_testing(), signer::address_of(test_addr)); + grant_role( + super_admin, get_bridge_role_for_testing(), signer::address_of(test_addr) + ); // check the address has the role assigned assert!(is_bridge(signer::address_of(test_addr)), TEST_SUCCESS); } @@ -115,8 +172,11 @@ module aave_acl::acl_manage_tests { // init the module test_init_module(super_admin); // add the asset listing role to some address - grant_role(super_admin, get_flash_borrower_role_for_testing(), - signer::address_of(test_addr)); + grant_role( + super_admin, + get_flash_borrower_role_for_testing(), + signer::address_of(test_addr), + ); // check the address has the role assigned assert!(is_flash_borrower(signer::address_of(test_addr)), TEST_SUCCESS); } @@ -126,8 +186,9 @@ module aave_acl::acl_manage_tests { // init the module test_init_module(super_admin); // add the asset listing role to some address - grant_role(super_admin, get_risk_admin_role_for_testing(), - signer::address_of(test_addr)); + grant_role( + super_admin, get_risk_admin_role_for_testing(), signer::address_of(test_addr) + ); // check the address has the role assigned assert!(is_risk_admin(signer::address_of(test_addr)), TEST_SUCCESS); } @@ -137,8 +198,11 @@ module aave_acl::acl_manage_tests { // init the module test_init_module(super_admin); // add the asset listing role to some address - grant_role(super_admin, get_emergency_admin_role_for_testing(), - signer::address_of(test_addr)); + grant_role( + super_admin, + get_emergency_admin_role_for_testing(), + signer::address_of(test_addr), + ); // check the address has the role assigned assert!(is_emergency_admin(signer::address_of(test_addr)), TEST_SUCCESS); } @@ -148,12 +212,81 @@ module aave_acl::acl_manage_tests { // init the module test_init_module(super_admin); // add the asset listing role to some address - grant_role(super_admin, get_pool_admin_role_for_testing(), - signer::address_of(test_addr)); + grant_role( + super_admin, get_pool_admin_role_for_testing(), signer::address_of(test_addr) + ); // check the address has the role assigned assert!(is_pool_admin(signer::address_of(test_addr)), TEST_SUCCESS); } + #[test(super_admin = @aave_acl, test_addr = @0x01)] + fun test_is_funds_admin(super_admin: &signer, test_addr: &signer) { + // init the module + test_init_module(super_admin); + // add the asset listing role to some address + grant_role( + super_admin, + get_funds_admin_role_for_testing(), + signer::address_of(test_addr), + ); + // check the address has the role assigned + assert!(is_funds_admin(signer::address_of(test_addr)), TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, test_addr = @0x01)] + fun test_is_emission_admin(super_admin: &signer, test_addr: &signer) { + // init the module + test_init_module(super_admin); + // add the asset listing role to some address + grant_role( + super_admin, + get_emissions_admin_role_for_testing(), + signer::address_of(test_addr), + ); + // check the address has the role assigned + assert!(is_emission_admin_role(signer::address_of(test_addr)), TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, test_addr = @0x01)] + fun test_is_admin_controlled_ecosystem_reserve_funds_admin( + super_admin: &signer, test_addr: &signer + ) { + // init the module + test_init_module(super_admin); + // add the asset listing role to some address + grant_role( + super_admin, + get_admin_controlled_ecosystem_reserve_funds_admin_role_for_testing(), + signer::address_of(test_addr), + ); + // check the address has the role assigned + assert!( + is_admin_controlled_ecosystem_reserve_funds_admin_role( + signer::address_of(test_addr) + ), + TEST_SUCCESS, + ); + } + + #[test(super_admin = @aave_acl, test_addr = @0x01)] + fun test_is_rewards_controller_admin( + super_admin: &signer, test_addr: &signer + ) { + // init the module + test_init_module(super_admin); + // add the asset listing role to some address + grant_role( + super_admin, + get_rewards_controller_admin_role_for_testing(), + signer::address_of(test_addr), + ); + // check the address has the role assigned + assert!( + is_rewards_controller_admin_role(signer::address_of(test_addr)), + TEST_SUCCESS, + ); + } + // ========== TEST: GRANT ROLE + HAS ROLE ============ #[test(super_admin = @aave_acl, test_addr = @0x01, other_addr = @0x02)] fun test_has_role( @@ -162,11 +295,14 @@ module aave_acl::acl_manage_tests { // init the module test_init_module(super_admin); // add the asset listing role to some address - grant_role(super_admin, get_pool_admin_role_for_testing(), - signer::address_of(test_addr)); + grant_role( + super_admin, get_pool_admin_role_for_testing(), signer::address_of(test_addr) + ); // check the address has no longer the role assigned - assert!(!has_role(get_pool_admin_role_for_testing(), signer::address_of(other_addr)), - TEST_SUCCESS); + assert!( + !has_role(get_pool_admin_role_for_testing(), signer::address_of(other_addr)), + TEST_SUCCESS, + ); } // ========== TEST: REVOKE + HAS ROLE ============ @@ -175,21 +311,34 @@ module aave_acl::acl_manage_tests { // init the module test_init_module(super_admin); // add the asset listing role to some address - grant_role(super_admin, get_pool_admin_role_for_testing(), - signer::address_of(test_addr)); + grant_role( + super_admin, get_pool_admin_role_for_testing(), signer::address_of(test_addr) + ); // check the address has the role assigned assert!(is_pool_admin(signer::address_of(test_addr)), TEST_SUCCESS); + + let role_admin = utf8(b"role_admin"); + // set role admin + set_role_admin(super_admin, get_pool_admin_role_for_testing(), role_admin); + // add the asset listing role to some address + grant_role(super_admin, role_admin, signer::address_of(test_addr)); + // now remove the role - revoke_role(super_admin, get_pool_admin_role_for_testing(), - signer::address_of(test_addr)); + revoke_role( + test_addr, get_pool_admin_role_for_testing(), signer::address_of(test_addr) + ); // check the address has no longer the role assigned - assert!(!has_role(get_pool_admin_role_for_testing(), signer::address_of(test_addr)), - TEST_SUCCESS); + assert!( + !has_role(get_pool_admin_role_for_testing(), signer::address_of(test_addr)), + TEST_SUCCESS, + ); } // ============== SPECIAL FUNCTIONS ============ // #[test(super_admin = @aave_acl, test_addr = @0x01)] - fun test_add_remove_pool_admin(super_admin: &signer, test_addr: &signer) { + fun test_add_remove_pool_admin( + super_admin: &signer, test_addr: &signer + ) { // init the module test_init_module(super_admin); // add the asset listing role to some address @@ -267,7 +416,9 @@ module aave_acl::acl_manage_tests { } #[test(super_admin = @aave_acl, test_addr = @0x01)] - fun test_add_remove_risk_admin(super_admin: &signer, test_addr: &signer) { + fun test_add_remove_risk_admin( + super_admin: &signer, test_addr: &signer + ) { // init the module test_init_module(super_admin); // add the asset listing role to some address @@ -281,7 +432,9 @@ module aave_acl::acl_manage_tests { } #[test(super_admin = @aave_acl, test_addr = @0x01)] - fun test_add_remove_funds_admin(super_admin: &signer, test_addr: &signer) { + fun test_add_remove_funds_admin( + super_admin: &signer, test_addr: &signer + ) { // init the module test_init_module(super_admin); // add the asset listing role to some address @@ -317,19 +470,27 @@ module aave_acl::acl_manage_tests { // init the module test_init_module(super_admin); // add the asset listing role to some address - add_admin_controlled_ecosystem_reserve_funds_admin_role(super_admin, - signer::address_of(test_addr)); + add_admin_controlled_ecosystem_reserve_funds_admin_role( + super_admin, signer::address_of(test_addr) + ); // check the address has the role assigned - assert!(is_admin_controlled_ecosystem_reserve_funds_admin_role(signer::address_of( - test_addr)), - TEST_SUCCESS); + assert!( + is_admin_controlled_ecosystem_reserve_funds_admin_role( + signer::address_of(test_addr) + ), + TEST_SUCCESS, + ); // remove pool admin - remove_admin_controlled_ecosystem_reserve_funds_admin_role(super_admin, - signer::address_of(test_addr)); + remove_admin_controlled_ecosystem_reserve_funds_admin_role( + super_admin, signer::address_of(test_addr) + ); // check the address has no longer the role assigned - assert!(!is_admin_controlled_ecosystem_reserve_funds_admin_role(signer::address_of( - test_addr)), - TEST_SUCCESS); + assert!( + !is_admin_controlled_ecosystem_reserve_funds_admin_role( + signer::address_of(test_addr) + ), + TEST_SUCCESS, + ); } #[test(super_admin = @aave_acl, test_addr = @0x01)] @@ -341,12 +502,16 @@ module aave_acl::acl_manage_tests { // add the asset listing role to some address add_rewards_controller_admin_role(super_admin, signer::address_of(test_addr)); // check the address has the role assigned - assert!(is_rewards_controller_admin_role(signer::address_of(test_addr)), - TEST_SUCCESS); + assert!( + is_rewards_controller_admin_role(signer::address_of(test_addr)), + TEST_SUCCESS, + ); // remove pool admin remove_rewards_controller_admin_role(super_admin, signer::address_of(test_addr)); // check the address has no longer the role assigned - assert!(!is_rewards_controller_admin_role(signer::address_of(test_addr)), - TEST_SUCCESS); + assert!( + !is_rewards_controller_admin_role(signer::address_of(test_addr)), + TEST_SUCCESS, + ); } } diff --git a/aave-core/aave-config/Move.toml b/aave-core/aave-config/Move.toml index bfacb8e..057a7df 100644 --- a/aave-core/aave-config/Move.toml +++ b/aave-core/aave-config/Move.toml @@ -10,6 +10,6 @@ aave_config = '_' [dev-addresses] [dependencies] -AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "main" } +AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "mainnet" } [dev-dependencies] diff --git a/aave-core/aave-config/doc/error_config.md b/aave-core/aave-config/doc/error_config.md index 01244d0..2fe0ec9 100644 --- a/aave-core/aave-config/doc/error_config.md +++ b/aave-core/aave-config/doc/error_config.md @@ -1,98 +1,103 @@ - + -# Module `0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error` +# Module `0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error` +@title Errors library +@author Aave +@notice Defines the error messages emitted by the different contracts of the Aave protocol - [Constants](#@Constants_0) -- [Function `get_ecaller_not_pool_admin`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecaller_not_pool_admin) -- [Function `get_ecaller_not_emergency_admin`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecaller_not_emergency_admin) -- [Function `get_ecaller_not_pool_or_emergency_admin`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecaller_not_pool_or_emergency_admin) -- [Function `get_ecaller_not_risk_or_pool_admin`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecaller_not_risk_or_pool_admin) -- [Function `get_ecaller_not_asset_listing_or_pool_admin`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecaller_not_asset_listing_or_pool_admin) -- [Function `get_ecaller_not_bridge`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecaller_not_bridge) -- [Function `get_eaddresses_provider_not_registered`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eaddresses_provider_not_registered) -- [Function `get_einvalid_addresses_provider_id`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_addresses_provider_id) -- [Function `get_enot_contract`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_enot_contract) -- [Function `get_ecaller_not_pool_configurator`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecaller_not_pool_configurator) -- [Function `get_ecaller_not_atoken`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecaller_not_atoken) -- [Function `get_einvalid_addresses_provider`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_addresses_provider) -- [Function `get_einvalid_flashloan_executor_return`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_flashloan_executor_return) -- [Function `get_ereserve_already_added`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ereserve_already_added) -- [Function `get_ereserves_storage_count_mismatch`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ereserves_storage_count_mismatch) -- [Function `get_eno_more_reserves_allowed`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eno_more_reserves_allowed) -- [Function `get_eemode_category_reserved`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eemode_category_reserved) -- [Function `get_einvalid_emode_category_assignment`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_emode_category_assignment) -- [Function `get_ereserve_liquidity_not_zero`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ereserve_liquidity_not_zero) -- [Function `get_eflashloan_premium_invalid`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eflashloan_premium_invalid) -- [Function `get_einvalid_reserve_params`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_reserve_params) -- [Function `get_einvalid_emode_category_params`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_emode_category_params) -- [Function `get_ebridge_protocol_fee_invalid`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ebridge_protocol_fee_invalid) -- [Function `get_ecaller_must_be_pool`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecaller_must_be_pool) -- [Function `get_einvalid_mint_amount`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_mint_amount) -- [Function `get_einvalid_burn_amount`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_burn_amount) -- [Function `get_einvalid_amount`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_amount) -- [Function `get_ereserve_inactive`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ereserve_inactive) -- [Function `get_ereserve_frozen`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ereserve_frozen) -- [Function `get_ereserve_paused`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ereserve_paused) -- [Function `get_eborrowing_not_enabled`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eborrowing_not_enabled) -- [Function `get_enot_enough_available_user_balance`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_enot_enough_available_user_balance) -- [Function `get_einvalid_interest_rate_mode_selected`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_interest_rate_mode_selected) -- [Function `get_ecollateral_balance_is_zero`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecollateral_balance_is_zero) -- [Function `get_ehealth_factor_lower_than_liquidation_threshold`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ehealth_factor_lower_than_liquidation_threshold) -- [Function `get_ecollateral_cannot_cover_new_borrow`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecollateral_cannot_cover_new_borrow) -- [Function `get_ecollateral_same_as_borrowing_currency`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecollateral_same_as_borrowing_currency) -- [Function `get_eno_debt_of_selected_type`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eno_debt_of_selected_type) -- [Function `get_eno_explicit_amount_to_repay_on_behalf`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eno_explicit_amount_to_repay_on_behalf) -- [Function `get_eno_outstanding_variable_debt`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eno_outstanding_variable_debt) -- [Function `get_eunderlying_balance_zero`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eunderlying_balance_zero) -- [Function `get_einterest_rate_rebalance_conditions_not_met`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einterest_rate_rebalance_conditions_not_met) -- [Function `get_ehealth_factor_not_below_threshold`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ehealth_factor_not_below_threshold) -- [Function `get_ecollateral_cannot_be_liquidated`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ecollateral_cannot_be_liquidated) -- [Function `get_especified_currency_not_borrowed_by_user`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_especified_currency_not_borrowed_by_user) -- [Function `get_einconsistent_flashloan_params`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einconsistent_flashloan_params) -- [Function `get_eborrow_cap_exceeded`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eborrow_cap_exceeded) -- [Function `get_esupply_cap_exceeded`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_esupply_cap_exceeded) -- [Function `get_eunbacked_mint_cap_exceeded`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eunbacked_mint_cap_exceeded) -- [Function `get_edebt_ceiling_exceeded`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_edebt_ceiling_exceeded) -- [Function `get_eunderlying_claimable_rights_not_zero`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eunderlying_claimable_rights_not_zero) -- [Function `get_evariable_debt_supply_not_zero`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_evariable_debt_supply_not_zero) -- [Function `get_eltv_validation_failed`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eltv_validation_failed) -- [Function `get_einconsistent_emode_category`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einconsistent_emode_category) -- [Function `get_eprice_oracle_sentinel_check_failed`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eprice_oracle_sentinel_check_failed) -- [Function `get_easset_not_borrowable_in_isolation`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_easset_not_borrowable_in_isolation) -- [Function `get_ereserve_already_initialized`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ereserve_already_initialized) -- [Function `get_euser_in_isolation_mode_or_ltv_zero`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_euser_in_isolation_mode_or_ltv_zero) -- [Function `get_einvalid_ltv`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_ltv) -- [Function `get_einvalid_liq_threshold`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_liq_threshold) -- [Function `get_einvalid_liq_bonus`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_liq_bonus) -- [Function `get_einvalid_decimals`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_decimals) -- [Function `get_einvalid_reserve_factor`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_reserve_factor) -- [Function `get_einvalid_borrow_cap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_borrow_cap) -- [Function `get_einvalid_supply_cap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_supply_cap) -- [Function `get_einvalid_liquidation_protocol_fee`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_liquidation_protocol_fee) -- [Function `get_einvalid_emode_category`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_emode_category) -- [Function `get_einvalid_unbacked_mint_cap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_unbacked_mint_cap) -- [Function `get_einvalid_debt_ceiling`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_debt_ceiling) -- [Function `get_einvalid_reserve_index`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_reserve_index) -- [Function `get_eacl_admin_cannot_be_zero`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eacl_admin_cannot_be_zero) -- [Function `get_einconsistent_params_length`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einconsistent_params_length) -- [Function `get_ezero_address_not_valid`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ezero_address_not_valid) -- [Function `get_einvalid_expiration`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_expiration) -- [Function `get_einvalid_signature`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_signature) -- [Function `get_eoperation_not_supported`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eoperation_not_supported) -- [Function `get_edebt_ceiling_not_zero`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_edebt_ceiling_not_zero) -- [Function `get_easset_not_listed`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_easset_not_listed) -- [Function `get_einvalid_optimal_usage_ratio`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_einvalid_optimal_usage_ratio) -- [Function `get_eunderlying_cannot_be_rescued`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eunderlying_cannot_be_rescued) -- [Function `get_eaddresses_provider_already_added`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eaddresses_provider_already_added) -- [Function `get_epool_addresses_do_not_match`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_epool_addresses_do_not_match) -- [Function `get_esiloed_borrowing_violation`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_esiloed_borrowing_violation) -- [Function `get_ereserve_debt_not_zero`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_ereserve_debt_not_zero) -- [Function `get_eflashloan_disabled`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_eflashloan_disabled) -- [Function `get_euser_not_listed`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_euser_not_listed) -- [Function `get_esigner_and_on_behalf_of_no_same`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_error_get_esigner_and_on_behalf_of_no_same) +- [Function `get_ecaller_not_pool_admin`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecaller_not_pool_admin) +- [Function `get_ecaller_not_emergency_admin`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecaller_not_emergency_admin) +- [Function `get_ecaller_not_pool_or_emergency_admin`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecaller_not_pool_or_emergency_admin) +- [Function `get_ecaller_not_risk_or_pool_admin`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecaller_not_risk_or_pool_admin) +- [Function `get_ecaller_not_asset_listing_or_pool_admin`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecaller_not_asset_listing_or_pool_admin) +- [Function `get_ecaller_not_bridge`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecaller_not_bridge) +- [Function `get_eaddresses_provider_not_registered`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eaddresses_provider_not_registered) +- [Function `get_einvalid_addresses_provider_id`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_addresses_provider_id) +- [Function `get_enot_contract`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_enot_contract) +- [Function `get_ecaller_not_pool_configurator`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecaller_not_pool_configurator) +- [Function `get_ecaller_not_atoken`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecaller_not_atoken) +- [Function `get_einvalid_addresses_provider`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_addresses_provider) +- [Function `get_einvalid_flashloan_executor_return`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_flashloan_executor_return) +- [Function `get_ereserve_already_added`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ereserve_already_added) +- [Function `get_ereserves_storage_count_mismatch`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ereserves_storage_count_mismatch) +- [Function `get_eno_more_reserves_allowed`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eno_more_reserves_allowed) +- [Function `get_eemode_category_reserved`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eemode_category_reserved) +- [Function `get_einvalid_emode_category_assignment`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_emode_category_assignment) +- [Function `get_ereserve_liquidity_not_zero`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ereserve_liquidity_not_zero) +- [Function `get_eflashloan_premium_invalid`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eflashloan_premium_invalid) +- [Function `get_einvalid_reserve_params`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_reserve_params) +- [Function `get_einvalid_emode_category_params`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_emode_category_params) +- [Function `get_ebridge_protocol_fee_invalid`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ebridge_protocol_fee_invalid) +- [Function `get_ecaller_must_be_pool`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecaller_must_be_pool) +- [Function `get_einvalid_mint_amount`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_mint_amount) +- [Function `get_einvalid_burn_amount`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_burn_amount) +- [Function `get_einvalid_amount`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_amount) +- [Function `get_ereserve_inactive`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ereserve_inactive) +- [Function `get_ereserve_frozen`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ereserve_frozen) +- [Function `get_ereserve_paused`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ereserve_paused) +- [Function `get_eborrowing_not_enabled`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eborrowing_not_enabled) +- [Function `get_enot_enough_available_user_balance`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_enot_enough_available_user_balance) +- [Function `get_einvalid_interest_rate_mode_selected`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_interest_rate_mode_selected) +- [Function `get_ecollateral_balance_is_zero`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecollateral_balance_is_zero) +- [Function `get_ehealth_factor_lower_than_liquidation_threshold`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ehealth_factor_lower_than_liquidation_threshold) +- [Function `get_ecollateral_cannot_cover_new_borrow`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecollateral_cannot_cover_new_borrow) +- [Function `get_ecollateral_same_as_borrowing_currency`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecollateral_same_as_borrowing_currency) +- [Function `get_eno_debt_of_selected_type`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eno_debt_of_selected_type) +- [Function `get_eno_explicit_amount_to_repay_on_behalf`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eno_explicit_amount_to_repay_on_behalf) +- [Function `get_eno_outstanding_variable_debt`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eno_outstanding_variable_debt) +- [Function `get_eunderlying_balance_zero`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eunderlying_balance_zero) +- [Function `get_einterest_rate_rebalance_conditions_not_met`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einterest_rate_rebalance_conditions_not_met) +- [Function `get_ehealth_factor_not_below_threshold`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ehealth_factor_not_below_threshold) +- [Function `get_ecollateral_cannot_be_liquidated`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ecollateral_cannot_be_liquidated) +- [Function `get_especified_currency_not_borrowed_by_user`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_especified_currency_not_borrowed_by_user) +- [Function `get_einconsistent_flashloan_params`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einconsistent_flashloan_params) +- [Function `get_eborrow_cap_exceeded`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eborrow_cap_exceeded) +- [Function `get_esupply_cap_exceeded`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_esupply_cap_exceeded) +- [Function `get_eunbacked_mint_cap_exceeded`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eunbacked_mint_cap_exceeded) +- [Function `get_edebt_ceiling_exceeded`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_edebt_ceiling_exceeded) +- [Function `get_eunderlying_claimable_rights_not_zero`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eunderlying_claimable_rights_not_zero) +- [Function `get_evariable_debt_supply_not_zero`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_evariable_debt_supply_not_zero) +- [Function `get_eltv_validation_failed`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eltv_validation_failed) +- [Function `get_einconsistent_emode_category`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einconsistent_emode_category) +- [Function `get_eprice_oracle_sentinel_check_failed`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eprice_oracle_sentinel_check_failed) +- [Function `get_easset_not_borrowable_in_isolation`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_easset_not_borrowable_in_isolation) +- [Function `get_ereserve_already_initialized`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ereserve_already_initialized) +- [Function `get_euser_in_isolation_mode_or_ltv_zero`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_euser_in_isolation_mode_or_ltv_zero) +- [Function `get_einvalid_ltv`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_ltv) +- [Function `get_einvalid_liq_threshold`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_liq_threshold) +- [Function `get_einvalid_liq_bonus`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_liq_bonus) +- [Function `get_einvalid_decimals`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_decimals) +- [Function `get_einvalid_reserve_factor`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_reserve_factor) +- [Function `get_einvalid_borrow_cap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_borrow_cap) +- [Function `get_einvalid_supply_cap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_supply_cap) +- [Function `get_einvalid_liquidation_protocol_fee`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_liquidation_protocol_fee) +- [Function `get_einvalid_emode_category`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_emode_category) +- [Function `get_einvalid_unbacked_mint_cap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_unbacked_mint_cap) +- [Function `get_einvalid_debt_ceiling`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_debt_ceiling) +- [Function `get_einvalid_reserve_index`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_reserve_index) +- [Function `get_eacl_admin_cannot_be_zero`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eacl_admin_cannot_be_zero) +- [Function `get_einconsistent_params_length`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einconsistent_params_length) +- [Function `get_ezero_address_not_valid`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ezero_address_not_valid) +- [Function `get_einvalid_expiration`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_expiration) +- [Function `get_einvalid_signature`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_signature) +- [Function `get_eoperation_not_supported`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eoperation_not_supported) +- [Function `get_edebt_ceiling_not_zero`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_edebt_ceiling_not_zero) +- [Function `get_easset_not_listed`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_easset_not_listed) +- [Function `get_einvalid_optimal_usage_ratio`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_einvalid_optimal_usage_ratio) +- [Function `get_eunderlying_cannot_be_rescued`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eunderlying_cannot_be_rescued) +- [Function `get_eaddresses_provider_already_added`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eaddresses_provider_already_added) +- [Function `get_epool_addresses_do_not_match`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_epool_addresses_do_not_match) +- [Function `get_esiloed_borrowing_violation`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_esiloed_borrowing_violation) +- [Function `get_ereserve_debt_not_zero`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_ereserve_debt_not_zero) +- [Function `get_eflashloan_disabled`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eflashloan_disabled) +- [Function `get_euser_not_listed`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_euser_not_listed) +- [Function `get_esigner_and_on_behalf_of_no_same`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_esigner_and_on_behalf_of_no_same) +- [Function `get_eaccount_does_not_exist`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_eaccount_does_not_exist) +- [Function `get_flashloan_payer_not_receiver`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_error_get_flashloan_payer_not_receiver)
@@ -104,1827 +109,1869 @@ ## Constants - + + +Account does not exist + + +
const EACCOUNT_DOES_NOT_EXIST: u64 = 95;
+
+ + + + ACL admin cannot be set to the zero address -
const EACL_ADMIN_CANNOT_BE_ZERO: u64 = 75;
+
const EACL_ADMIN_CANNOT_BE_ZERO: u64 = 75;
 
- + Reserve has already been added to reserve list -
const EADDRESSES_PROVIDER_ALREADY_ADDED: u64 = 86;
+
const EADDRESSES_PROVIDER_ALREADY_ADDED: u64 = 86;
 
- + Pool addresses provider is not registered -
const EADDRESSES_PROVIDER_NOT_REGISTERED: u64 = 7;
+
const EADDRESSES_PROVIDER_NOT_REGISTERED: u64 = 7;
 
- + Asset is not borrowable in isolation mode -
const EASSET_NOT_BORROWABLE_IN_ISOLATION: u64 = 60;
+
const EASSET_NOT_BORROWABLE_IN_ISOLATION: u64 = 60;
 
- + Asset is not listed -
const EASSET_NOT_LISTED: u64 = 82;
+
const EASSET_NOT_LISTED: u64 = 82;
 
- + Borrowing is not enabled -
const EBORROWING_NOT_ENABLED: u64 = 30;
+
const EBORROWING_NOT_ENABLED: u64 = 30;
 
- + Borrow cap is exceeded -
const EBORROW_CAP_EXCEEDED: u64 = 50;
+
const EBORROW_CAP_EXCEEDED: u64 = 50;
 
- + Invalid bridge protocol fee -
const EBRIDGE_PROTOCOL_FEE_INVALID: u64 = 22;
+
const EBRIDGE_PROTOCOL_FEE_INVALID: u64 = 22;
 
- + The caller of this function must be a pool -
const ECALLER_MUST_BE_POOL: u64 = 23;
+
const ECALLER_MUST_BE_POOL: u64 = 23;
 
- + The caller of the function is not an asset listing or pool admin -
const ECALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN: u64 = 5;
+
const ECALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN: u64 = 5;
 
- + The caller of the function is not an AToken -
const ECALLER_NOT_ATOKEN: u64 = 11;
+
const ECALLER_NOT_ATOKEN: u64 = 11;
 
- + The caller of the function is not a bridge -
const ECALLER_NOT_BRIDGE: u64 = 6;
+
const ECALLER_NOT_BRIDGE: u64 = 6;
 
- + The caller of the function is not an emergency admin -
const ECALLER_NOT_EMERGENCY_ADMIN: u64 = 2;
+
const ECALLER_NOT_EMERGENCY_ADMIN: u64 = 2;
 
- + The caller of the function is not a pool admin -
const ECALLER_NOT_POOL_ADMIN: u64 = 1;
+
const ECALLER_NOT_POOL_ADMIN: u64 = 1;
 
- + The caller of the function is not the pool configurator -
const ECALLER_NOT_POOL_CONFIGURATOR: u64 = 10;
+
const ECALLER_NOT_POOL_CONFIGURATOR: u64 = 10;
 
- + The caller of the function is not a pool or emergency admin -
const ECALLER_NOT_POOL_OR_EMERGENCY_ADMIN: u64 = 3;
+
const ECALLER_NOT_POOL_OR_EMERGENCY_ADMIN: u64 = 3;
 
- + The caller of the function is not a risk or pool admin -
const ECALLER_NOT_RISK_OR_POOL_ADMIN: u64 = 4;
+
const ECALLER_NOT_RISK_OR_POOL_ADMIN: u64 = 4;
 
- + The collateral balance is 0 -
const ECOLLATERAL_BALANCE_IS_ZERO: u64 = 34;
+
const ECOLLATERAL_BALANCE_IS_ZERO: u64 = 34;
 
- + The collateral chosen cannot be liquidated -
const ECOLLATERAL_CANNOT_BE_LIQUIDATED: u64 = 46;
+
const ECOLLATERAL_CANNOT_BE_LIQUIDATED: u64 = 46;
 
- + There is not enough collateral to cover a new borrow -
const ECOLLATERAL_CANNOT_COVER_NEW_BORROW: u64 = 36;
+
const ECOLLATERAL_CANNOT_COVER_NEW_BORROW: u64 = 36;
 
- + Collateral is (mostly) the same currency that is being borrowed -
const ECOLLATERAL_SAME_AS_BORROWING_CURRENCY: u64 = 37;
+
const ECOLLATERAL_SAME_AS_BORROWING_CURRENCY: u64 = 37;
 
- + Debt ceiling is exceeded -
const EDEBT_CEILING_EXCEEDED: u64 = 53;
+
const EDEBT_CEILING_EXCEEDED: u64 = 53;
 
- + Debt ceiling is not zero -
const EDEBT_CEILING_NOT_ZERO: u64 = 81;
+
const EDEBT_CEILING_NOT_ZERO: u64 = 81;
 
- + Zero eMode category is reserved for volatile heterogeneous assets -
const EEMODE_CATEGORY_RESERVED: u64 = 16;
+
const EEMODE_CATEGORY_RESERVED: u64 = 16;
 
- + FlashLoaning for this asset is disabled -
const EFLASHLOAN_DISABLED: u64 = 91;
+
const EFLASHLOAN_DISABLED: u64 = 91;
 
- + + +Flashloan payer is different from the flashloan receiver + + +
const EFLASHLOAN_PAYER_NOT_RECEIVER: u64 = 95;
+
+ + + + Invalid flashloan premium -
const EFLASHLOAN_PREMIUM_INVALID: u64 = 19;
+
const EFLASHLOAN_PREMIUM_INVALID: u64 = 19;
 
- + Health factor is lesser than the liquidation threshold -
const EHEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD: u64 = 35;
+
const EHEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD: u64 = 35;
 
- + Health factor is not below the threshold -
const EHEALTH_FACTOR_NOT_BELOW_THRESHOLD: u64 = 45;
+
const EHEALTH_FACTOR_NOT_BELOW_THRESHOLD: u64 = 45;
 
- + Inconsistent eMode category -
const EINCONSISTENT_EMODE_CATEGORY: u64 = 58;
+
const EINCONSISTENT_EMODE_CATEGORY: u64 = 58;
 
- + Inconsistent flashloan parameters -
const EINCONSISTENT_FLASHLOAN_PARAMS: u64 = 49;
+
const EINCONSISTENT_FLASHLOAN_PARAMS: u64 = 49;
 
- + Array parameters that should be equal length are not -
const EINCONSISTENT_PARAMS_LENGTH: u64 = 76;
+
const EINCONSISTENT_PARAMS_LENGTH: u64 = 76;
 
- + Interest rate rebalance conditions were not met -
const EINTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET: u64 = 44;
+
const EINTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET: u64 = 44;
 
- + The address of the pool addresses provider is invalid -
const EINVALID_ADDRESSES_PROVIDER: u64 = 12;
+
const EINVALID_ADDRESSES_PROVIDER: u64 = 12;
 
- + Invalid id for the pool addresses provider -
const EINVALID_ADDRESSES_PROVIDER_ID: u64 = 8;
+
const EINVALID_ADDRESSES_PROVIDER_ID: u64 = 8;
 
- + Amount must be greater than 0 -
const EINVALID_AMOUNT: u64 = 26;
+
const EINVALID_AMOUNT: u64 = 26;
 
- + Invalid borrow cap for the reserve -
const EINVALID_BORROW_CAP: u64 = 68;
+
const EINVALID_BORROW_CAP: u64 = 68;
 
- + Invalid amount to burn -
const EINVALID_BURN_AMOUNT: u64 = 25;
+
const EINVALID_BURN_AMOUNT: u64 = 25;
 
- + Invalid debt ceiling for the reserve -
const EINVALID_DEBT_CEILING: u64 = 73;
+
const EINVALID_DEBT_CEILING: u64 = 73;
 
- + Invalid decimals parameter of the underlying asset of the reserve -
const EINVALID_DECIMALS: u64 = 66;
+
const EINVALID_DECIMALS: u64 = 66;
 
- + Invalid eMode category for the reserve -
const EINVALID_EMODE_CATEGORY: u64 = 71;
+
const EINVALID_EMODE_CATEGORY: u64 = 71;
 
- + Invalid eMode category assignment to asset -
const EINVALID_EMODE_CATEGORY_ASSIGNMENT: u64 = 17;
+
const EINVALID_EMODE_CATEGORY_ASSIGNMENT: u64 = 17;
 
- + Invalid risk parameters for the eMode category -
const EINVALID_EMODE_CATEGORY_PARAMS: u64 = 21;
+
const EINVALID_EMODE_CATEGORY_PARAMS: u64 = 21;
 
- + Invalid expiration -
const EINVALID_EXPIRATION: u64 = 78;
+
const EINVALID_EXPIRATION: u64 = 78;
 
- + Invalid return value of the flashloan executor function -
const EINVALID_FLASHLOAN_EXECUTOR_RETURN: u64 = 13;
+
const EINVALID_FLASHLOAN_EXECUTOR_RETURN: u64 = 13;
 
- + Invalid interest rate mode selected -
const EINVALID_INTEREST_RATE_MODE_SELECTED: u64 = 33;
+
const EINVALID_INTEREST_RATE_MODE_SELECTED: u64 = 33;
 
- + Invalid liquidation protocol fee for the reserve -
const EINVALID_LIQUIDATION_PROTOCOL_FEE: u64 = 70;
+
const EINVALID_LIQUIDATION_PROTOCOL_FEE: u64 = 70;
 
- + Invalid liquidity bonus parameter for the reserve -
const EINVALID_LIQ_BONUS: u64 = 65;
+
const EINVALID_LIQ_BONUS: u64 = 65;
 
- + Invalid liquidity threshold parameter for the reserve -
const EINVALID_LIQ_THRESHOLD: u64 = 64;
+
const EINVALID_LIQ_THRESHOLD: u64 = 64;
 
- + Invalid ltv parameter for the reserve -
const EINVALID_LTV: u64 = 63;
+
const EINVALID_LTV: u64 = 63;
 
- + Invalid amount to mint -
const EINVALID_MINT_AMOUNT: u64 = 24;
+
const EINVALID_MINT_AMOUNT: u64 = 24;
 
- + Invalid optimal usage ratio -
const EINVALID_OPTIMAL_USAGE_RATIO: u64 = 83;
+
const EINVALID_OPTIMAL_USAGE_RATIO: u64 = 83;
 
- + Invalid reserve factor parameter for the reserve -
const EINVALID_RESERVE_FACTOR: u64 = 67;
+
const EINVALID_RESERVE_FACTOR: u64 = 67;
 
- + Invalid reserve index -
const EINVALID_RESERVE_INDEX: u64 = 74;
+
const EINVALID_RESERVE_INDEX: u64 = 74;
 
- + Invalid risk parameters for the reserve -
const EINVALID_RESERVE_PARAMS: u64 = 20;
+
const EINVALID_RESERVE_PARAMS: u64 = 20;
 
- + Invalid signature -
const EINVALID_SIGNATURE: u64 = 79;
+
const EINVALID_SIGNATURE: u64 = 79;
 
- + Invalid supply cap for the reserve -
const EINVALID_SUPPLY_CAP: u64 = 69;
+
const EINVALID_SUPPLY_CAP: u64 = 69;
 
- + Invalid unbacked mint cap for the reserve -
const EINVALID_UNBACKED_MINT_CAP: u64 = 72;
+
const EINVALID_UNBACKED_MINT_CAP: u64 = 72;
 
- + Ltv validation failed -
const ELTV_VALIDATION_FAILED: u64 = 57;
+
const ELTV_VALIDATION_FAILED: u64 = 57;
 
- + Address is not a contract -
const ENOT_CONTRACT: u64 = 9;
+
const ENOT_CONTRACT: u64 = 9;
 
- + User cannot withdraw more than the available balance -
const ENOT_ENOUGH_AVAILABLE_USER_BALANCE: u64 = 32;
+
const ENOT_ENOUGH_AVAILABLE_USER_BALANCE: u64 = 32;
 
- + For repayment of a specific type of debt, the user needs to have debt that type -
const ENO_DEBT_OF_SELECTED_TYPE: u64 = 39;
+
const ENO_DEBT_OF_SELECTED_TYPE: u64 = 39;
 
- + To repay on behalf of a user an explicit amount to repay is needed -
const ENO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF: u64 = 40;
+
const ENO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF: u64 = 40;
 
- + Maximum amount of reserves in the pool reached -
const ENO_MORE_RESERVES_ALLOWED: u64 = 15;
+
const ENO_MORE_RESERVES_ALLOWED: u64 = 15;
 
- + User does not have outstanding variable rate debt on this reserve -
const ENO_OUTSTANDING_VARIABLE_DEBT: u64 = 42;
+
const ENO_OUTSTANDING_VARIABLE_DEBT: u64 = 42;
 
- + Operation not supported -
const EOPERATION_NOT_SUPPORTED: u64 = 80;
+
const EOPERATION_NOT_SUPPORTED: u64 = 80;
 
- + The token implementation pool address and the pool address provided by the initializing pool do not match -
const EPOOL_ADDRESSES_DO_NOT_MATCH: u64 = 87;
+
const EPOOL_ADDRESSES_DO_NOT_MATCH: u64 = 87;
 
- + Price oracle sentinel validation failed -
const EPRICE_ORACLE_SENTINEL_CHECK_FAILED: u64 = 59;
+
const EPRICE_ORACLE_SENTINEL_CHECK_FAILED: u64 = 59;
 
- + Mismatch of reserves count in storage -
const ERESERVES_STORAGE_COUNT_MISMATCH: u64 = 93;
+
const ERESERVES_STORAGE_COUNT_MISMATCH: u64 = 93;
 
- + Reserve has already been added to reserve list -
const ERESERVE_ALREADY_ADDED: u64 = 14;
+
const ERESERVE_ALREADY_ADDED: u64 = 14;
 
- + Reserve has already been initialized -
const ERESERVE_ALREADY_INITIALIZED: u64 = 61;
+
const ERESERVE_ALREADY_INITIALIZED: u64 = 61;
 
- + the total debt of the reserve needs to be 0 -
const ERESERVE_DEBT_NOT_ZERO: u64 = 90;
+
const ERESERVE_DEBT_NOT_ZERO: u64 = 90;
 
- + Action cannot be performed because the reserve is frozen -
const ERESERVE_FROZEN: u64 = 28;
+
const ERESERVE_FROZEN: u64 = 28;
 
- + Action requires an active reserve -
const ERESERVE_INACTIVE: u64 = 27;
+
const ERESERVE_INACTIVE: u64 = 27;
 
- + The liquidity of the reserve needs to be 0 -
const ERESERVE_LIQUIDITY_NOT_ZERO: u64 = 18;
+
const ERESERVE_LIQUIDITY_NOT_ZERO: u64 = 18;
 
- + Action cannot be performed because the reserve is paused -
const ERESERVE_PAUSED: u64 = 29;
+
const ERESERVE_PAUSED: u64 = 29;
 
- + The person who signed must be consistent with on_behalf_of -
const ESIGNER_AND_ON_BEHALF_OF_NO_SAME: u64 = 94;
+
const ESIGNER_AND_ON_BEHALF_OF_NO_SAME: u64 = 94;
 
- + User is trying to borrow multiple assets including a siloed one -
const ESILOED_BORROWING_VIOLATION: u64 = 89;
+
const ESILOED_BORROWING_VIOLATION: u64 = 89;
 
- + User did not borrow the specified currency -
const ESPECIFIED_CURRENCY_NOT_BORROWED_BY_USER: u64 = 47;
+
const ESPECIFIED_CURRENCY_NOT_BORROWED_BY_USER: u64 = 47;
 
- + Supply cap is exceeded -
const ESUPPLY_CAP_EXCEEDED: u64 = 51;
+
const ESUPPLY_CAP_EXCEEDED: u64 = 51;
 
- + Unbacked mint cap is exceeded -
const EUNBACKED_MINT_CAP_EXCEEDED: u64 = 52;
+
const EUNBACKED_MINT_CAP_EXCEEDED: u64 = 52;
 
- + The underlying balance needs to be greater than 0 -
const EUNDERLYING_BALANCE_ZERO: u64 = 43;
+
const EUNDERLYING_BALANCE_ZERO: u64 = 43;
 
- + The underlying asset cannot be rescued -
const EUNDERLYING_CANNOT_BE_RESCUED: u64 = 85;
+
const EUNDERLYING_CANNOT_BE_RESCUED: u64 = 85;
 
- + Claimable rights over underlying not zero (aToken supply or accruedToTreasury) -
const EUNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO: u64 = 54;
+
const EUNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO: u64 = 54;
 
- + User is in isolation mode or ltv is zero -
const EUSER_IN_ISOLATION_MODE_OR_LTV_ZERO: u64 = 62;
+
const EUSER_IN_ISOLATION_MODE_OR_LTV_ZERO: u64 = 62;
 
- + User is not listed -
const EUSER_NOT_LISTED: u64 = 92;
+
const EUSER_NOT_LISTED: u64 = 92;
 
- + Variable debt supply is not zero -
const EVARIABLE_DEBT_SUPPLY_NOT_ZERO: u64 = 56;
+
const EVARIABLE_DEBT_SUPPLY_NOT_ZERO: u64 = 56;
 
- + Zero address not valid -
const EZERO_ADDRESS_NOT_VALID: u64 = 77;
+
const EZERO_ADDRESS_NOT_VALID: u64 = 77;
 
- + ## Function `get_ecaller_not_pool_admin` -
public fun get_ecaller_not_pool_admin(): u64
+
public fun get_ecaller_not_pool_admin(): u64
 
- + ## Function `get_ecaller_not_emergency_admin` -
public fun get_ecaller_not_emergency_admin(): u64
+
public fun get_ecaller_not_emergency_admin(): u64
 
- + ## Function `get_ecaller_not_pool_or_emergency_admin` -
public fun get_ecaller_not_pool_or_emergency_admin(): u64
+
public fun get_ecaller_not_pool_or_emergency_admin(): u64
 
- + ## Function `get_ecaller_not_risk_or_pool_admin` -
public fun get_ecaller_not_risk_or_pool_admin(): u64
+
public fun get_ecaller_not_risk_or_pool_admin(): u64
 
- + ## Function `get_ecaller_not_asset_listing_or_pool_admin` -
public fun get_ecaller_not_asset_listing_or_pool_admin(): u64
+
public fun get_ecaller_not_asset_listing_or_pool_admin(): u64
 
- + ## Function `get_ecaller_not_bridge` -
public fun get_ecaller_not_bridge(): u64
+
public fun get_ecaller_not_bridge(): u64
 
- + ## Function `get_eaddresses_provider_not_registered` -
public fun get_eaddresses_provider_not_registered(): u64
+
public fun get_eaddresses_provider_not_registered(): u64
 
- + ## Function `get_einvalid_addresses_provider_id` -
public fun get_einvalid_addresses_provider_id(): u64
+
public fun get_einvalid_addresses_provider_id(): u64
 
- + ## Function `get_enot_contract` -
public fun get_enot_contract(): u64
+
public fun get_enot_contract(): u64
 
- + ## Function `get_ecaller_not_pool_configurator` -
public fun get_ecaller_not_pool_configurator(): u64
+
public fun get_ecaller_not_pool_configurator(): u64
 
- + ## Function `get_ecaller_not_atoken` -
public fun get_ecaller_not_atoken(): u64
+
public fun get_ecaller_not_atoken(): u64
 
- + ## Function `get_einvalid_addresses_provider` -
public fun get_einvalid_addresses_provider(): u64
+
public fun get_einvalid_addresses_provider(): u64
 
- + ## Function `get_einvalid_flashloan_executor_return` -
public fun get_einvalid_flashloan_executor_return(): u64
+
public fun get_einvalid_flashloan_executor_return(): u64
 
- + ## Function `get_ereserve_already_added` -
public fun get_ereserve_already_added(): u64
+
public fun get_ereserve_already_added(): u64
 
- + ## Function `get_ereserves_storage_count_mismatch` -
public fun get_ereserves_storage_count_mismatch(): u64
+
public fun get_ereserves_storage_count_mismatch(): u64
 
- + ## Function `get_eno_more_reserves_allowed` -
public fun get_eno_more_reserves_allowed(): u64
+
public fun get_eno_more_reserves_allowed(): u64
 
- + ## Function `get_eemode_category_reserved` -
public fun get_eemode_category_reserved(): u64
+
public fun get_eemode_category_reserved(): u64
 
- + ## Function `get_einvalid_emode_category_assignment` -
public fun get_einvalid_emode_category_assignment(): u64
+
public fun get_einvalid_emode_category_assignment(): u64
 
- + ## Function `get_ereserve_liquidity_not_zero` -
public fun get_ereserve_liquidity_not_zero(): u64
+
public fun get_ereserve_liquidity_not_zero(): u64
 
- + ## Function `get_eflashloan_premium_invalid` -
public fun get_eflashloan_premium_invalid(): u64
+
public fun get_eflashloan_premium_invalid(): u64
 
- + ## Function `get_einvalid_reserve_params` -
public fun get_einvalid_reserve_params(): u64
+
public fun get_einvalid_reserve_params(): u64
 
- + ## Function `get_einvalid_emode_category_params` -
public fun get_einvalid_emode_category_params(): u64
+
public fun get_einvalid_emode_category_params(): u64
 
- + ## Function `get_ebridge_protocol_fee_invalid` -
public fun get_ebridge_protocol_fee_invalid(): u64
+
public fun get_ebridge_protocol_fee_invalid(): u64
 
- + ## Function `get_ecaller_must_be_pool` -
public fun get_ecaller_must_be_pool(): u64
+
public fun get_ecaller_must_be_pool(): u64
 
- + ## Function `get_einvalid_mint_amount` -
public fun get_einvalid_mint_amount(): u64
+
public fun get_einvalid_mint_amount(): u64
 
- + ## Function `get_einvalid_burn_amount` -
public fun get_einvalid_burn_amount(): u64
+
public fun get_einvalid_burn_amount(): u64
 
- + ## Function `get_einvalid_amount` -
public fun get_einvalid_amount(): u64
+
public fun get_einvalid_amount(): u64
 
- + ## Function `get_ereserve_inactive` -
public fun get_ereserve_inactive(): u64
+
public fun get_ereserve_inactive(): u64
 
- + ## Function `get_ereserve_frozen` -
public fun get_ereserve_frozen(): u64
+
public fun get_ereserve_frozen(): u64
 
- + ## Function `get_ereserve_paused` -
public fun get_ereserve_paused(): u64
+
public fun get_ereserve_paused(): u64
 
- + ## Function `get_eborrowing_not_enabled` -
public fun get_eborrowing_not_enabled(): u64
+
public fun get_eborrowing_not_enabled(): u64
 
- + ## Function `get_enot_enough_available_user_balance` -
public fun get_enot_enough_available_user_balance(): u64
+
public fun get_enot_enough_available_user_balance(): u64
 
- + ## Function `get_einvalid_interest_rate_mode_selected` -
public fun get_einvalid_interest_rate_mode_selected(): u64
+
public fun get_einvalid_interest_rate_mode_selected(): u64
 
- + ## Function `get_ecollateral_balance_is_zero` -
public fun get_ecollateral_balance_is_zero(): u64
+
public fun get_ecollateral_balance_is_zero(): u64
 
- + ## Function `get_ehealth_factor_lower_than_liquidation_threshold` -
public fun get_ehealth_factor_lower_than_liquidation_threshold(): u64
+
public fun get_ehealth_factor_lower_than_liquidation_threshold(): u64
 
- + ## Function `get_ecollateral_cannot_cover_new_borrow` -
public fun get_ecollateral_cannot_cover_new_borrow(): u64
+
public fun get_ecollateral_cannot_cover_new_borrow(): u64
 
- + ## Function `get_ecollateral_same_as_borrowing_currency` -
public fun get_ecollateral_same_as_borrowing_currency(): u64
+
public fun get_ecollateral_same_as_borrowing_currency(): u64
 
- + ## Function `get_eno_debt_of_selected_type` -
public fun get_eno_debt_of_selected_type(): u64
+
public fun get_eno_debt_of_selected_type(): u64
 
- + ## Function `get_eno_explicit_amount_to_repay_on_behalf` -
public fun get_eno_explicit_amount_to_repay_on_behalf(): u64
+
public fun get_eno_explicit_amount_to_repay_on_behalf(): u64
 
- + ## Function `get_eno_outstanding_variable_debt` -
public fun get_eno_outstanding_variable_debt(): u64
+
public fun get_eno_outstanding_variable_debt(): u64
 
- + ## Function `get_eunderlying_balance_zero` -
public fun get_eunderlying_balance_zero(): u64
+
public fun get_eunderlying_balance_zero(): u64
 
- + ## Function `get_einterest_rate_rebalance_conditions_not_met` -
public fun get_einterest_rate_rebalance_conditions_not_met(): u64
+
public fun get_einterest_rate_rebalance_conditions_not_met(): u64
 
- + ## Function `get_ehealth_factor_not_below_threshold` -
public fun get_ehealth_factor_not_below_threshold(): u64
+
public fun get_ehealth_factor_not_below_threshold(): u64
 
- + ## Function `get_ecollateral_cannot_be_liquidated` -
public fun get_ecollateral_cannot_be_liquidated(): u64
+
public fun get_ecollateral_cannot_be_liquidated(): u64
 
- + ## Function `get_especified_currency_not_borrowed_by_user` -
public fun get_especified_currency_not_borrowed_by_user(): u64
+
public fun get_especified_currency_not_borrowed_by_user(): u64
 
- + ## Function `get_einconsistent_flashloan_params` -
public fun get_einconsistent_flashloan_params(): u64
+
public fun get_einconsistent_flashloan_params(): u64
 
- + ## Function `get_eborrow_cap_exceeded` -
public fun get_eborrow_cap_exceeded(): u64
+
public fun get_eborrow_cap_exceeded(): u64
 
- + ## Function `get_esupply_cap_exceeded` -
public fun get_esupply_cap_exceeded(): u64
+
public fun get_esupply_cap_exceeded(): u64
 
- + ## Function `get_eunbacked_mint_cap_exceeded` -
public fun get_eunbacked_mint_cap_exceeded(): u64
+
public fun get_eunbacked_mint_cap_exceeded(): u64
 
- + ## Function `get_edebt_ceiling_exceeded` -
public fun get_edebt_ceiling_exceeded(): u64
+
public fun get_edebt_ceiling_exceeded(): u64
 
- + ## Function `get_eunderlying_claimable_rights_not_zero` -
public fun get_eunderlying_claimable_rights_not_zero(): u64
+
public fun get_eunderlying_claimable_rights_not_zero(): u64
 
- + ## Function `get_evariable_debt_supply_not_zero` -
public fun get_evariable_debt_supply_not_zero(): u64
+
public fun get_evariable_debt_supply_not_zero(): u64
 
- + ## Function `get_eltv_validation_failed` -
public fun get_eltv_validation_failed(): u64
+
public fun get_eltv_validation_failed(): u64
 
- + ## Function `get_einconsistent_emode_category` -
public fun get_einconsistent_emode_category(): u64
+
public fun get_einconsistent_emode_category(): u64
 
- + ## Function `get_eprice_oracle_sentinel_check_failed` -
public fun get_eprice_oracle_sentinel_check_failed(): u64
+
public fun get_eprice_oracle_sentinel_check_failed(): u64
 
- + ## Function `get_easset_not_borrowable_in_isolation` -
public fun get_easset_not_borrowable_in_isolation(): u64
+
public fun get_easset_not_borrowable_in_isolation(): u64
 
- + ## Function `get_ereserve_already_initialized` -
public fun get_ereserve_already_initialized(): u64
+
public fun get_ereserve_already_initialized(): u64
 
- + ## Function `get_euser_in_isolation_mode_or_ltv_zero` -
public fun get_euser_in_isolation_mode_or_ltv_zero(): u64
+
public fun get_euser_in_isolation_mode_or_ltv_zero(): u64
 
- + ## Function `get_einvalid_ltv` -
public fun get_einvalid_ltv(): u64
+
public fun get_einvalid_ltv(): u64
 
- + ## Function `get_einvalid_liq_threshold` -
public fun get_einvalid_liq_threshold(): u64
+
public fun get_einvalid_liq_threshold(): u64
 
- + ## Function `get_einvalid_liq_bonus` -
public fun get_einvalid_liq_bonus(): u64
+
public fun get_einvalid_liq_bonus(): u64
 
- + ## Function `get_einvalid_decimals` -
public fun get_einvalid_decimals(): u64
+
public fun get_einvalid_decimals(): u64
 
- + ## Function `get_einvalid_reserve_factor` -
public fun get_einvalid_reserve_factor(): u64
+
public fun get_einvalid_reserve_factor(): u64
 
- + ## Function `get_einvalid_borrow_cap` -
public fun get_einvalid_borrow_cap(): u64
+
public fun get_einvalid_borrow_cap(): u64
 
- + ## Function `get_einvalid_supply_cap` -
public fun get_einvalid_supply_cap(): u64
+
public fun get_einvalid_supply_cap(): u64
 
- + ## Function `get_einvalid_liquidation_protocol_fee` -
public fun get_einvalid_liquidation_protocol_fee(): u64
+
public fun get_einvalid_liquidation_protocol_fee(): u64
 
- + ## Function `get_einvalid_emode_category` -
public fun get_einvalid_emode_category(): u64
+
public fun get_einvalid_emode_category(): u64
 
- + ## Function `get_einvalid_unbacked_mint_cap` -
public fun get_einvalid_unbacked_mint_cap(): u64
+
public fun get_einvalid_unbacked_mint_cap(): u64
 
- + ## Function `get_einvalid_debt_ceiling` -
public fun get_einvalid_debt_ceiling(): u64
+
public fun get_einvalid_debt_ceiling(): u64
 
- + ## Function `get_einvalid_reserve_index` -
public fun get_einvalid_reserve_index(): u64
+
public fun get_einvalid_reserve_index(): u64
 
- + ## Function `get_eacl_admin_cannot_be_zero` -
public fun get_eacl_admin_cannot_be_zero(): u64
+
public fun get_eacl_admin_cannot_be_zero(): u64
 
- + ## Function `get_einconsistent_params_length` -
public fun get_einconsistent_params_length(): u64
+
public fun get_einconsistent_params_length(): u64
 
- + ## Function `get_ezero_address_not_valid` -
public fun get_ezero_address_not_valid(): u64
+
public fun get_ezero_address_not_valid(): u64
 
- + ## Function `get_einvalid_expiration` -
public fun get_einvalid_expiration(): u64
+
public fun get_einvalid_expiration(): u64
 
- + ## Function `get_einvalid_signature` -
public fun get_einvalid_signature(): u64
+
public fun get_einvalid_signature(): u64
 
- + ## Function `get_eoperation_not_supported` -
public fun get_eoperation_not_supported(): u64
+
public fun get_eoperation_not_supported(): u64
 
- + ## Function `get_edebt_ceiling_not_zero` -
public fun get_edebt_ceiling_not_zero(): u64
+
public fun get_edebt_ceiling_not_zero(): u64
 
- + ## Function `get_easset_not_listed` -
public fun get_easset_not_listed(): u64
+
public fun get_easset_not_listed(): u64
 
- + ## Function `get_einvalid_optimal_usage_ratio` -
public fun get_einvalid_optimal_usage_ratio(): u64
+
public fun get_einvalid_optimal_usage_ratio(): u64
 
- + ## Function `get_eunderlying_cannot_be_rescued` -
public fun get_eunderlying_cannot_be_rescued(): u64
+
public fun get_eunderlying_cannot_be_rescued(): u64
 
- + ## Function `get_eaddresses_provider_already_added` -
public fun get_eaddresses_provider_already_added(): u64
+
public fun get_eaddresses_provider_already_added(): u64
 
- + ## Function `get_epool_addresses_do_not_match` -
public fun get_epool_addresses_do_not_match(): u64
+
public fun get_epool_addresses_do_not_match(): u64
 
- + ## Function `get_esiloed_borrowing_violation` -
public fun get_esiloed_borrowing_violation(): u64
+
public fun get_esiloed_borrowing_violation(): u64
 
- + ## Function `get_ereserve_debt_not_zero` -
public fun get_ereserve_debt_not_zero(): u64
+
public fun get_ereserve_debt_not_zero(): u64
 
- + ## Function `get_eflashloan_disabled` -
public fun get_eflashloan_disabled(): u64
+
public fun get_eflashloan_disabled(): u64
 
- + ## Function `get_euser_not_listed` -
public fun get_euser_not_listed(): u64
+
public fun get_euser_not_listed(): u64
 
- + ## Function `get_esigner_and_on_behalf_of_no_same` -
public fun get_esigner_and_on_behalf_of_no_same(): u64
+
public fun get_esigner_and_on_behalf_of_no_same(): u64
+
+ + + + + +## Function `get_eaccount_does_not_exist` + + + +
public fun get_eaccount_does_not_exist(): u64
+
+ + + + + +## Function `get_flashloan_payer_not_receiver` + + + +
public fun get_flashloan_payer_not_receiver(): u64
 
diff --git a/aave-core/aave-config/doc/helper.md b/aave-core/aave-config/doc/helper.md index 343784c..abc7f0e 100644 --- a/aave-core/aave-config/doc/helper.md +++ b/aave-core/aave-config/doc/helper.md @@ -1,22 +1,23 @@ - + -# Module `0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::helper` +# Module `0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::helper` -- [Function `bitwise_negation`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_helper_bitwise_negation) +- [Function `bitwise_negation`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_helper_bitwise_negation)
- + ## Function `bitwise_negation` +Get the result of bitwise negation -
public fun bitwise_negation(m: u256): u256
+
public fun bitwise_negation(m: u256): u256
 
diff --git a/aave-core/aave-config/doc/reserve_config.md b/aave-core/aave-config/doc/reserve_config.md index 1a44fcd..9459052 100644 --- a/aave-core/aave-config/doc/reserve_config.md +++ b/aave-core/aave-config/doc/reserve_config.md @@ -1,69 +1,72 @@ - + -# Module `0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve` +# Module `0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve` +@title ReserveConfiguration module +@author Aave +@notice Implements the bitmap logic to handle the reserve configuration -- [Resource `ReserveConfigurationMap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_ReserveConfigurationMap) +- [Resource `ReserveConfigurationMap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_ReserveConfigurationMap) - [Constants](#@Constants_0) -- [Function `init`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_init) -- [Function `set_ltv`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_ltv) -- [Function `get_ltv`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_ltv) -- [Function `set_liquidation_threshold`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_liquidation_threshold) -- [Function `get_liquidation_threshold`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_liquidation_threshold) -- [Function `set_liquidation_bonus`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_liquidation_bonus) -- [Function `get_liquidation_bonus`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_liquidation_bonus) -- [Function `set_decimals`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_decimals) -- [Function `get_decimals`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_decimals) -- [Function `set_active`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_active) -- [Function `get_active`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_active) -- [Function `set_frozen`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_frozen) -- [Function `get_frozen`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_frozen) -- [Function `set_paused`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_paused) -- [Function `get_paused`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_paused) -- [Function `set_borrowable_in_isolation`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_borrowable_in_isolation) -- [Function `get_borrowable_in_isolation`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_borrowable_in_isolation) -- [Function `set_siloed_borrowing`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_siloed_borrowing) -- [Function `get_siloed_borrowing`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_siloed_borrowing) -- [Function `set_borrowing_enabled`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_borrowing_enabled) -- [Function `get_borrowing_enabled`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_borrowing_enabled) -- [Function `set_reserve_factor`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_reserve_factor) -- [Function `get_reserve_factor`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_reserve_factor) -- [Function `set_borrow_cap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_borrow_cap) -- [Function `get_borrow_cap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_borrow_cap) -- [Function `set_supply_cap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_supply_cap) -- [Function `get_supply_cap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_supply_cap) -- [Function `set_debt_ceiling`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_debt_ceiling) -- [Function `get_debt_ceiling`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_debt_ceiling) -- [Function `set_liquidation_protocol_fee`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_liquidation_protocol_fee) -- [Function `get_liquidation_protocol_fee`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_liquidation_protocol_fee) -- [Function `set_unbacked_mint_cap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_unbacked_mint_cap) -- [Function `get_unbacked_mint_cap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_unbacked_mint_cap) -- [Function `set_emode_category`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_emode_category) -- [Function `get_emode_category`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_emode_category) -- [Function `set_flash_loan_enabled`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_set_flash_loan_enabled) -- [Function `get_flash_loan_enabled`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_flash_loan_enabled) -- [Function `get_flags`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_flags) -- [Function `get_params`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_params) -- [Function `get_caps`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_caps) -- [Function `get_debt_ceiling_decimals`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_debt_ceiling_decimals) -- [Function `get_max_reserves_count`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_reserve_get_max_reserves_count) - - -
use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::helper;
-
- - - - +- [Function `init`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_init) +- [Function `set_ltv`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_ltv) +- [Function `get_ltv`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_ltv) +- [Function `set_liquidation_threshold`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_liquidation_threshold) +- [Function `get_liquidation_threshold`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_liquidation_threshold) +- [Function `set_liquidation_bonus`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_liquidation_bonus) +- [Function `get_liquidation_bonus`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_liquidation_bonus) +- [Function `set_decimals`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_decimals) +- [Function `get_decimals`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_decimals) +- [Function `set_active`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_active) +- [Function `get_active`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_active) +- [Function `set_frozen`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_frozen) +- [Function `get_frozen`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_frozen) +- [Function `set_paused`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_paused) +- [Function `get_paused`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_paused) +- [Function `set_borrowable_in_isolation`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_borrowable_in_isolation) +- [Function `get_borrowable_in_isolation`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_borrowable_in_isolation) +- [Function `set_siloed_borrowing`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_siloed_borrowing) +- [Function `get_siloed_borrowing`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_siloed_borrowing) +- [Function `set_borrowing_enabled`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_borrowing_enabled) +- [Function `get_borrowing_enabled`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_borrowing_enabled) +- [Function `set_reserve_factor`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_reserve_factor) +- [Function `get_reserve_factor`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_reserve_factor) +- [Function `set_borrow_cap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_borrow_cap) +- [Function `get_borrow_cap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_borrow_cap) +- [Function `set_supply_cap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_supply_cap) +- [Function `get_supply_cap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_supply_cap) +- [Function `set_debt_ceiling`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_debt_ceiling) +- [Function `get_debt_ceiling`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_debt_ceiling) +- [Function `set_liquidation_protocol_fee`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_liquidation_protocol_fee) +- [Function `get_liquidation_protocol_fee`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_liquidation_protocol_fee) +- [Function `set_unbacked_mint_cap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_unbacked_mint_cap) +- [Function `get_unbacked_mint_cap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_unbacked_mint_cap) +- [Function `set_emode_category`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_emode_category) +- [Function `get_emode_category`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_emode_category) +- [Function `set_flash_loan_enabled`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_set_flash_loan_enabled) +- [Function `get_flash_loan_enabled`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_flash_loan_enabled) +- [Function `get_flags`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_flags) +- [Function `get_params`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_params) +- [Function `get_caps`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_caps) +- [Function `get_debt_ceiling_decimals`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_debt_ceiling_decimals) +- [Function `get_max_reserves_count`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_reserve_get_max_reserves_count) + + +
use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::helper;
+
+ + + + ## Resource `ReserveConfigurationMap` -
struct ReserveConfigurationMap has copy, drop, store, key
+
struct ReserveConfigurationMap has copy, drop, store, key
 
@@ -73,451 +76,452 @@ ## Constants - + -
const ACTIVE_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457511950319091711999;
+
const ACTIVE_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457511950319091711999;
 
- + -
const BORROWABLE_IN_ISOLATION_MASK: u256 = 115792089237316195423570985008687907853269984665640564039455278164903915945983;
+
const BORROWABLE_IN_ISOLATION_MASK: u256 = 115792089237316195423570985008687907853269984665640564039455278164903915945983;
 
- + -
const BORROWABLE_IN_ISOLATION_START_BIT_POSITION: u256 = 61;
+
const BORROWABLE_IN_ISOLATION_START_BIT_POSITION: u256 = 61;
 
- + -
const BORROWING_ENABLED_START_BIT_POSITION: u256 = 58;
+
const BORROWING_ENABLED_START_BIT_POSITION: u256 = 58;
 
- + -
const BORROWING_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457295777536977928191;
+
const BORROWING_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457295777536977928191;
 
- + -
const BORROW_CAP_MASK: u256 = 115792089237316195423570985008687907853269901588890828691141347134601036824575;
+
const BORROW_CAP_MASK: u256 = 115792089237316195423570985008687907853269901588890828691141347134601036824575;
 
- + -
const BORROW_CAP_START_BIT_POSITION: u256 = 80;
+
const BORROW_CAP_START_BIT_POSITION: u256 = 80;
 
- + -
const DEBT_CEILING_DECIMALS: u256 = 2;
+
const DEBT_CEILING_DECIMALS: u256 = 2;
 
- + -
const DEBT_CEILING_MASK: u256 = 108555083659990515227827083269813533489170840026057959730454019326871953473535;
+
const DEBT_CEILING_MASK: u256 = 108555083659990515227827083269813533489170840026057959730454019326871953473535;
 
- + -
const DEBT_CEILING_START_BIT_POSITION: u256 = 212;
+
const DEBT_CEILING_START_BIT_POSITION: u256 = 212;
 
- + -
const DECIMALS_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457512231794068422655;
+
const DECIMALS_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457512231794068422655;
 
- + -
const EMODE_CATEGORY_MASK: u256 = 115792089237316195423570889601861022891927484329094684320502060868636724166655;
+
const EMODE_CATEGORY_MASK: u256 = 115792089237316195423570889601861022891927484329094684320502060868636724166655;
 
- + -
const EMODE_CATEGORY_START_BIT_POSITION: u256 = 168;
+
const EMODE_CATEGORY_START_BIT_POSITION: u256 = 168;
 
- + -
const FLASHLOAN_ENABLED_MASK: u256 = 115792089237316195423570985008687907853269984665640564039448360635876274864127;
+
const FLASHLOAN_ENABLED_MASK: u256 = 115792089237316195423570985008687907853269984665640564039448360635876274864127;
 
- + -
const FLASHLOAN_ENABLED_START_BIT_POSITION: u256 = 63;
+
const FLASHLOAN_ENABLED_START_BIT_POSITION: u256 = 63;
 
- + -
const FROZEN_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457439892725053784063;
+
const FROZEN_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457439892725053784063;
 
- + -
const IS_ACTIVE_START_BIT_POSITION: u256 = 56;
+
const IS_ACTIVE_START_BIT_POSITION: u256 = 56;
 
- + -
const IS_FROZEN_START_BIT_POSITION: u256 = 57;
+
const IS_FROZEN_START_BIT_POSITION: u256 = 57;
 
- + -
const IS_PAUSED_START_BIT_POSITION: u256 = 60;
+
const IS_PAUSED_START_BIT_POSITION: u256 = 60;
 
- + -
const LIQUIDATION_BONUS_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457583726442447896575;
+
const LIQUIDATION_BONUS_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457583726442447896575;
 
- + -
const LIQUIDATION_BONUS_START_BIT_POSITION: u256 = 32;
+
const LIQUIDATION_BONUS_START_BIT_POSITION: u256 = 32;
 
- + -
const LIQUIDATION_PROTOCOL_FEE_MASK: u256 = 115792089237316195423570984634549197687329661445021480007966928956539929624575;
+
const LIQUIDATION_PROTOCOL_FEE_MASK: u256 = 115792089237316195423570984634549197687329661445021480007966928956539929624575;
 
- + -
const LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION: u256 = 152;
+
const LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION: u256 = 152;
 
- + -
const LIQUIDATION_THRESHOLD_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457584007908834738175;
+
const LIQUIDATION_THRESHOLD_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457584007908834738175;
 
- + @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed -
const LIQUIDATION_THRESHOLD_START_BIT_POSITION: u256 = 16;
+
const LIQUIDATION_THRESHOLD_START_BIT_POSITION: u256 = 16;
 
- + -
const LTV_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129574400;
+
const LTV_MASK: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129574400;
 
- + -
const MAX_RESERVES_COUNT: u16 = 128;
+
const MAX_RESERVES_COUNT: u16 = 128;
 
- + -
const MAX_VALID_BORROW_CAP: u256 = 68719476735;
+
const MAX_VALID_BORROW_CAP: u256 = 68719476735;
 
- + -
const MAX_VALID_DEBT_CEILING: u256 = 1099511627775;
+
const MAX_VALID_DEBT_CEILING: u256 = 1099511627775;
 
- + -
const MAX_VALID_DECIMALS: u256 = 255;
+
const MAX_VALID_DECIMALS: u256 = 255;
 
- + -
const MAX_VALID_EMODE_CATEGORY: u256 = 255;
+
const MAX_VALID_EMODE_CATEGORY: u256 = 255;
 
- + -
const MAX_VALID_LIQUIDATION_BONUS: u256 = 65535;
+
const MAX_VALID_LIQUIDATION_BONUS: u256 = 65535;
 
- + -
const MAX_VALID_LIQUIDATION_PROTOCOL_FEE: u256 = 65535;
+
const MAX_VALID_LIQUIDATION_PROTOCOL_FEE: u256 = 65535;
 
- + -
const MAX_VALID_LIQUIDATION_THRESHOLD: u256 = 65535;
+
const MAX_VALID_LIQUIDATION_THRESHOLD: u256 = 65535;
 
- + -
const MAX_VALID_LTV: u256 = 65535;
+
const MAX_VALID_LTV: u256 = 65535;
 
- + -
const MAX_VALID_RESERVE_FACTOR: u256 = 65535;
+
const MAX_VALID_RESERVE_FACTOR: u256 = 65535;
 
- + -
const MAX_VALID_SUPPLY_CAP: u256 = 68719476735;
+
const MAX_VALID_SUPPLY_CAP: u256 = 68719476735;
 
- + -
const MAX_VALID_UNBACKED_MINT_CAP: u256 = 68719476735;
+
const MAX_VALID_UNBACKED_MINT_CAP: u256 = 68719476735;
 
- + -
const PAUSED_MASK: u256 = 115792089237316195423570985008687907853269984665640564039456431086408522792959;
+
const PAUSED_MASK: u256 = 115792089237316195423570985008687907853269984665640564039456431086408522792959;
 
- + -
const RESERVE_DECIMALS_START_BIT_POSITION: u256 = 48;
+
const RESERVE_DECIMALS_START_BIT_POSITION: u256 = 48;
 
- + -
const RESERVE_FACTOR_MASK: u256 = 115792089237316195423570985008687907853269984665640562830550211137357664485375;
+
const RESERVE_FACTOR_MASK: u256 = 115792089237316195423570985008687907853269984665640562830550211137357664485375;
 
- + -
const RESERVE_FACTOR_START_BIT_POSITION: u256 = 64;
+
const RESERVE_FACTOR_START_BIT_POSITION: u256 = 64;
 
- + -
const SILOED_BORROWING_MASK: u256 = 115792089237316195423570985008687907853269984665640564039452972321894702252031;
+
const SILOED_BORROWING_MASK: u256 = 115792089237316195423570985008687907853269984665640564039452972321894702252031;
 
- + -
const SILOED_BORROWING_START_BIT_POSITION: u256 = 62;
+
const SILOED_BORROWING_START_BIT_POSITION: u256 = 62;
 
- + -
const SUPPLY_CAP_MASK: u256 = 115792089237316195423570985008682198862499243902866067452821842515308866174975;
+
const SUPPLY_CAP_MASK: u256 = 115792089237316195423570985008682198862499243902866067452821842515308866174975;
 
- + -
const SUPPLY_CAP_START_BIT_POSITION: u256 = 116;
+
const SUPPLY_CAP_START_BIT_POSITION: u256 = 116;
 
- + -
const UNBACKED_MINT_CAP_MASK: u256 = 115792089237309613405341795965490592094593402660309829990319025859654871678975;
+
const UNBACKED_MINT_CAP_MASK: u256 = 115792089237309613405341795965490592094593402660309829990319025859654871678975;
 
- + -
const UNBACKED_MINT_CAP_START_BIT_POSITION: u256 = 176;
+
const UNBACKED_MINT_CAP_START_BIT_POSITION: u256 = 176;
 
- + ## Function `init` +@notice init the reserve configuration -
public fun init(): reserve::ReserveConfigurationMap
+
public fun init(): reserve::ReserveConfigurationMap
 
- + ## Function `set_ltv` @@ -526,12 +530,12 @@ @param ltv The new ltv -
public fun set_ltv(self: &mut reserve::ReserveConfigurationMap, ltv: u256)
+
public fun set_ltv(self: &mut reserve::ReserveConfigurationMap, ltv: u256)
 
- + ## Function `get_ltv` @@ -540,437 +544,566 @@ @return The loan to value -
public fun get_ltv(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_ltv(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_liquidation_threshold` @notice Sets the liquidation threshold of the reserve @param self The reserve configuration -@param threshold The new liquidation threshold +@param liquidation_threshold The new liquidation threshold -
public fun set_liquidation_threshold(self: &mut reserve::ReserveConfigurationMap, liquidation_threshold: u256)
+
public fun set_liquidation_threshold(self: &mut reserve::ReserveConfigurationMap, liquidation_threshold: u256)
 
- + ## Function `get_liquidation_threshold` +@notice Gets the liquidation threshold of the reserve +@param self The reserve configuration +@return The liquidation threshold -
public fun get_liquidation_threshold(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_liquidation_threshold(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_liquidation_bonus` +@notice Sets the liquidation bonus of the reserve +@param self The reserve configuration +@param liquidation_bonus The new liquidation bonus -
public fun set_liquidation_bonus(self: &mut reserve::ReserveConfigurationMap, liquidation_bonus: u256)
+
public fun set_liquidation_bonus(self: &mut reserve::ReserveConfigurationMap, liquidation_bonus: u256)
 
- + ## Function `get_liquidation_bonus` +@notice Gets the liquidation bonus of the reserve +@param self The reserve configuration +@return The liquidation bonus -
public fun get_liquidation_bonus(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_liquidation_bonus(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_decimals` +@notice Sets the decimals of the underlying asset of the reserve +@param self The reserve configuration +@param decimals The decimals -
public fun set_decimals(self: &mut reserve::ReserveConfigurationMap, decimals: u256)
+
public fun set_decimals(self: &mut reserve::ReserveConfigurationMap, decimals: u256)
 
- + ## Function `get_decimals` +@notice Gets the decimals of the underlying asset of the reserve +@param self The reserve configuration +@return The decimals -
public fun get_decimals(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_decimals(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_active` +@notice Sets the active state of the reserve +@param self The reserve configuration +@param active The new active state -
public fun set_active(self: &mut reserve::ReserveConfigurationMap, active: bool)
+
public fun set_active(self: &mut reserve::ReserveConfigurationMap, active: bool)
 
- + ## Function `get_active` +@notice Gets the active state of the reserve +@param self The reserve configuration +@return The active state -
public fun get_active(self: &reserve::ReserveConfigurationMap): bool
+
public fun get_active(self: &reserve::ReserveConfigurationMap): bool
 
- + ## Function `set_frozen` +@notice Sets the frozen state of the reserve +@param self The reserve configuration +@param frozen The new frozen state -
public fun set_frozen(self: &mut reserve::ReserveConfigurationMap, frozen: bool)
+
public fun set_frozen(self: &mut reserve::ReserveConfigurationMap, frozen: bool)
 
- + ## Function `get_frozen` +@notice Gets the frozen state of the reserve +@param self The reserve configuration +@return The frozen state -
public fun get_frozen(self: &reserve::ReserveConfigurationMap): bool
+
public fun get_frozen(self: &reserve::ReserveConfigurationMap): bool
 
- + ## Function `set_paused` +@notice Sets the paused state of the reserve +@param self The reserve configuration +@param paused The new paused state -
public fun set_paused(self: &mut reserve::ReserveConfigurationMap, paused: bool)
+
public fun set_paused(self: &mut reserve::ReserveConfigurationMap, paused: bool)
 
- + ## Function `get_paused` +@notice Gets the paused state of the reserve +@param self The reserve configuration +@return The paused state -
public fun get_paused(self: &reserve::ReserveConfigurationMap): bool
+
public fun get_paused(self: &reserve::ReserveConfigurationMap): bool
 
- + ## Function `set_borrowable_in_isolation` +@notice Sets the borrowing in isolation state of the reserve +@dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the borrowed +amount will be accumulated in the isolated collateral's total debt exposure. +@dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep +consistency in the debt ceiling calculations. +@param self The reserve configuration +@param borrowable The new borrowing in isolation state -
public fun set_borrowable_in_isolation(self: &mut reserve::ReserveConfigurationMap, borrowable: bool)
+
public fun set_borrowable_in_isolation(self: &mut reserve::ReserveConfigurationMap, borrowable: bool)
 
- + ## Function `get_borrowable_in_isolation` +@notice Gets the borrowable in isolation flag for the reserve. +@dev If the returned flag is true, the asset is borrowable against isolated collateral. Assets borrowed with +isolated collateral is accounted for in the isolated collateral's total debt exposure. +@dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep +consistency in the debt ceiling calculations. +@param self The reserve configuration +@return The borrowable in isolation flag -
public fun get_borrowable_in_isolation(self: &reserve::ReserveConfigurationMap): bool
+
public fun get_borrowable_in_isolation(self: &reserve::ReserveConfigurationMap): bool
 
- + ## Function `set_siloed_borrowing` +@notice Sets the siloed borrowing flag for the reserve. +@dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset. +@param self The reserve configuration +@param siloed_borrowing True if the asset is siloed -
public fun set_siloed_borrowing(self: &mut reserve::ReserveConfigurationMap, siloed_borrowing: bool)
+
public fun set_siloed_borrowing(self: &mut reserve::ReserveConfigurationMap, siloed_borrowing: bool)
 
- + ## Function `get_siloed_borrowing` +@notice Gets the siloed borrowing flag for the reserve. +@dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset. +@param self The reserve configuration +@return The siloed borrowing flag -
public fun get_siloed_borrowing(self: &reserve::ReserveConfigurationMap): bool
+
public fun get_siloed_borrowing(self: &reserve::ReserveConfigurationMap): bool
 
- + ## Function `set_borrowing_enabled` +@notice Enables or disables borrowing on the reserve +@param self The reserve configuration +@param borrowing_enabled True if the borrowing needs to be enabled, false otherwise -
public fun set_borrowing_enabled(self: &mut reserve::ReserveConfigurationMap, borrowing_enabled: bool)
+
public fun set_borrowing_enabled(self: &mut reserve::ReserveConfigurationMap, borrowing_enabled: bool)
 
- + ## Function `get_borrowing_enabled` +@notice Gets the borrowing state of the reserve +@param self The reserve configuration +@return The borrowing state -
public fun get_borrowing_enabled(self: &reserve::ReserveConfigurationMap): bool
+
public fun get_borrowing_enabled(self: &reserve::ReserveConfigurationMap): bool
 
- + ## Function `set_reserve_factor` +@notice Sets the reserve factor of the reserve +@param self The reserve configuration +@param reserve_factor The reserve factor -
public fun set_reserve_factor(self: &mut reserve::ReserveConfigurationMap, reserve_factor: u256)
+
public fun set_reserve_factor(self: &mut reserve::ReserveConfigurationMap, reserve_factor: u256)
 
- + ## Function `get_reserve_factor` +@notice Gets the reserve factor of the reserve +@param self The reserve configuration +@return The reserve factor -
public fun get_reserve_factor(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_reserve_factor(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_borrow_cap` +@notice Sets the borrow cap of the reserve +@param self The reserve configuration +@param borrow_cap The borrow cap -
public fun set_borrow_cap(self: &mut reserve::ReserveConfigurationMap, borrow_cap: u256)
+
public fun set_borrow_cap(self: &mut reserve::ReserveConfigurationMap, borrow_cap: u256)
 
- + ## Function `get_borrow_cap` +@notice Gets the borrow cap of the reserve +@param self The reserve configuration +@return The borrow cap -
public fun get_borrow_cap(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_borrow_cap(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_supply_cap` +@notice Sets the supply cap of the reserve +@param self The reserve configuration +@param supply_cap The supply cap -
public fun set_supply_cap(self: &mut reserve::ReserveConfigurationMap, supply_cap: u256)
+
public fun set_supply_cap(self: &mut reserve::ReserveConfigurationMap, supply_cap: u256)
 
- + ## Function `get_supply_cap` +@notice Gets the supply cap of the reserve +@param self The reserve configuration +@return The supply cap -
public fun get_supply_cap(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_supply_cap(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_debt_ceiling` +@notice Sets the debt ceiling in isolation mode for the asset +@param self The reserve configuration +@param debt_ceiling The maximum debt ceiling for the asset -
public fun set_debt_ceiling(self: &mut reserve::ReserveConfigurationMap, debt_ceiling: u256)
+
public fun set_debt_ceiling(self: &mut reserve::ReserveConfigurationMap, debt_ceiling: u256)
 
- + ## Function `get_debt_ceiling` +@notice Gets the debt ceiling for the asset if the asset is in isolation mode +@param self The reserve configuration +@return The debt ceiling (0 = isolation mode disabled) -
public fun get_debt_ceiling(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_debt_ceiling(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_liquidation_protocol_fee` +@notice Sets the liquidation protocol fee of the reserve +@param self The reserve configuration +@param liquidation_protocol_fee The liquidation protocol fee -
public fun set_liquidation_protocol_fee(self: &mut reserve::ReserveConfigurationMap, liquidation_protocol_fee: u256)
+
public fun set_liquidation_protocol_fee(self: &mut reserve::ReserveConfigurationMap, liquidation_protocol_fee: u256)
 
- + ## Function `get_liquidation_protocol_fee` +@dev Gets the liquidation protocol fee +@param self The reserve configuration +@return The liquidation protocol fee -
public fun get_liquidation_protocol_fee(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_liquidation_protocol_fee(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_unbacked_mint_cap` +@notice Sets the unbacked mint cap of the reserve +@param self The reserve configuration +@param unbacked_mint_cap The unbacked mint cap -
public fun set_unbacked_mint_cap(self: &mut reserve::ReserveConfigurationMap, unbacked_mint_cap: u256)
+
public fun set_unbacked_mint_cap(self: &mut reserve::ReserveConfigurationMap, unbacked_mint_cap: u256)
 
- + ## Function `get_unbacked_mint_cap` +@dev Gets the unbacked mint cap of the reserve +@param self The reserve configuration +@return The unbacked mint cap -
public fun get_unbacked_mint_cap(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_unbacked_mint_cap(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_emode_category` +@notice Sets the eMode asset category +@param self The reserve configuration +@param emode_category The asset category when the user selects the eMode -
public fun set_emode_category(self: &mut reserve::ReserveConfigurationMap, emode_category: u256)
+
public fun set_emode_category(self: &mut reserve::ReserveConfigurationMap, emode_category: u256)
 
- + ## Function `get_emode_category` +@dev Gets the eMode asset category +@param self The reserve configuration +@return The eMode category for the asset -
public fun get_emode_category(self: &reserve::ReserveConfigurationMap): u256
+
public fun get_emode_category(self: &reserve::ReserveConfigurationMap): u256
 
- + ## Function `set_flash_loan_enabled` +@notice Sets the flashloanable flag for the reserve +@param self The reserve configuration +@param flash_loan_enabled True if the asset is flashloanable, false otherwise -
public fun set_flash_loan_enabled(self: &mut reserve::ReserveConfigurationMap, flash_loan_enabled: bool)
+
public fun set_flash_loan_enabled(self: &mut reserve::ReserveConfigurationMap, flash_loan_enabled: bool)
 
- + ## Function `get_flash_loan_enabled` +@notice Gets the flashloanable flag for the reserve +@param self The reserve configuration +@return The flashloanable flag -
public fun get_flash_loan_enabled(self: &reserve::ReserveConfigurationMap): bool
+
public fun get_flash_loan_enabled(self: &reserve::ReserveConfigurationMap): bool
 
- + ## Function `get_flags` +@notice Gets the configuration flags of the reserve +@param self The reserve configuration +@return The state flag representing active +@return The state flag representing frozen +@return The state flag representing borrowing enabled +@return The state flag representing paused -
public fun get_flags(self: &reserve::ReserveConfigurationMap): (bool, bool, bool, bool)
+
public fun get_flags(self: &reserve::ReserveConfigurationMap): (bool, bool, bool, bool)
 
- + ## Function `get_params` +@notice Gets the configuration parameters of the reserve from storage +@param self The reserve configuration +@return The state param representing ltv +@return The state param representing liquidation threshold +@return The state param representing liquidation bonus +@return The state param representing reserve decimals +@return The state param representing reserve factor +@return The state param representing eMode category -
public fun get_params(self: &reserve::ReserveConfigurationMap): (u256, u256, u256, u256, u256, u256)
+
public fun get_params(self: &reserve::ReserveConfigurationMap): (u256, u256, u256, u256, u256, u256)
 
- + ## Function `get_caps` +@notice Gets the caps parameters of the reserve from storage +@param self The reserve configuration +@return The state param representing borrow cap +@return The state param representing supply cap. -
public fun get_caps(self: &reserve::ReserveConfigurationMap): (u256, u256)
+
public fun get_caps(self: &reserve::ReserveConfigurationMap): (u256, u256)
 
- + ## Function `get_debt_ceiling_decimals` +@notice Gets the debt ceiling decimals -
public fun get_debt_ceiling_decimals(): u256
+
public fun get_debt_ceiling_decimals(): u256
 
- + ## Function `get_max_reserves_count` +@notice Gets the maximum number of reserves -
public fun get_max_reserves_count(): u16
+
public fun get_max_reserves_count(): u16
 
diff --git a/aave-core/aave-config/doc/user_config.md b/aave-core/aave-config/doc/user_config.md index 4d6724d..f5dc24e 100644 --- a/aave-core/aave-config/doc/user_config.md +++ b/aave-core/aave-config/doc/user_config.md @@ -1,48 +1,50 @@ - + -# Module `0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user` +# Module `0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user` +@title UserConfiguration library +@author Aave +@notice Implements the bitmap logic to handle the user configuration -- [Resource `UserConfigurationMap`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_UserConfigurationMap) +- [Resource `UserConfigurationMap`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_UserConfigurationMap) - [Constants](#@Constants_0) -- [Function `init`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_init) -- [Function `get_interest_rate_mode_none`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_get_interest_rate_mode_none) -- [Function `get_interest_rate_mode_variable`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_get_interest_rate_mode_variable) -- [Function `get_borrowing_mask`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_get_borrowing_mask) -- [Function `get_collateral_mask`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_get_collateral_mask) -- [Function `get_rebalance_up_liquidity_rate_threshold`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_get_rebalance_up_liquidity_rate_threshold) -- [Function `get_minimum_health_factor_liquidation_threshold`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_get_minimum_health_factor_liquidation_threshold) -- [Function `get_health_factor_liquidation_threshold`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_get_health_factor_liquidation_threshold) -- [Function `get_isolated_collateral_supplier_role`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_get_isolated_collateral_supplier_role) -- [Function `set_borrowing`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_set_borrowing) -- [Function `set_using_as_collateral`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_set_using_as_collateral) -- [Function `is_using_as_collateral_or_borrowing`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_is_using_as_collateral_or_borrowing) -- [Function `is_borrowing`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_is_borrowing) -- [Function `is_using_as_collateral`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_is_using_as_collateral) -- [Function `is_using_as_collateral_one`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_is_using_as_collateral_one) -- [Function `is_using_as_collateral_any`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_is_using_as_collateral_any) -- [Function `is_borrowing_one`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_is_borrowing_one) -- [Function `is_borrowing_any`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_is_borrowing_any) -- [Function `is_empty`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_is_empty) -- [Function `get_first_asset_id_by_mask`](#0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2_user_get_first_asset_id_by_mask) - - -
use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::helper;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
+-  [Function `init`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_init)
+-  [Function `get_interest_rate_mode_none`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_get_interest_rate_mode_none)
+-  [Function `get_interest_rate_mode_variable`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_get_interest_rate_mode_variable)
+-  [Function `get_borrowing_mask`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_get_borrowing_mask)
+-  [Function `get_collateral_mask`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_get_collateral_mask)
+-  [Function `get_minimum_health_factor_liquidation_threshold`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_get_minimum_health_factor_liquidation_threshold)
+-  [Function `get_health_factor_liquidation_threshold`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_get_health_factor_liquidation_threshold)
+-  [Function `get_isolated_collateral_supplier_role`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_get_isolated_collateral_supplier_role)
+-  [Function `set_borrowing`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_set_borrowing)
+-  [Function `set_using_as_collateral`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_set_using_as_collateral)
+-  [Function `is_using_as_collateral_or_borrowing`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_is_using_as_collateral_or_borrowing)
+-  [Function `is_borrowing`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_is_borrowing)
+-  [Function `is_using_as_collateral`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_is_using_as_collateral)
+-  [Function `is_using_as_collateral_one`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_is_using_as_collateral_one)
+-  [Function `is_using_as_collateral_any`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_is_using_as_collateral_any)
+-  [Function `is_borrowing_one`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_is_borrowing_one)
+-  [Function `is_borrowing_any`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_is_borrowing_any)
+-  [Function `is_empty`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_is_empty)
+-  [Function `get_first_asset_id_by_mask`](#0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd_user_get_first_asset_id_by_mask)
+
+
+
use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::helper;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
 
- + ## Resource `UserConfigurationMap` -
struct UserConfigurationMap has copy, drop, store, key
+
struct UserConfigurationMap has copy, drop, store, key
 
@@ -52,299 +54,321 @@ ## Constants - + -
const BORROWING_MASK: u256 = 38597363079105398474523661669562635951089994888546854679819194669304376546645;
+
const BORROWING_MASK: u256 = 38597363079105398474523661669562635951089994888546854679819194669304376546645;
 
- + -
const COLLATERAL_MASK: u256 = 77194726158210796949047323339125271902179989777093709359638389338608753093290;
+
const COLLATERAL_MASK: u256 = 77194726158210796949047323339125271902179989777093709359638389338608753093290;
 
- + +@dev Minimum health factor to consider a user position healthy +A value of 1e18 results in 1 +1 * 10 ** 18 -* @dev Minimum health factor to consider a user position healthy -* A value of 1e18 results in 1 - - -
const HEALTH_FACTOR_LIQUIDATION_THRESHOLD: u256 = 1000000000000000000;
+
const HEALTH_FACTOR_LIQUIDATION_THRESHOLD: u256 = 1000000000000000000;
 
- + -
const INTEREST_RATE_MODE_NONE: u8 = 0;
+
const INTEREST_RATE_MODE_NONE: u8 = 0;
 
- + +1 = Stable Rate, 2 = Variable Rate, Since the Stable Rate service has been removed, only the Variable Rate service is retained. -
const INTEREST_RATE_MODE_VARIABLE: u8 = 2;
+
const INTEREST_RATE_MODE_VARIABLE: u8 = 2;
 
- - + -* @dev Role identifier for the role allowed to supply isolated reserves as collateral +@dev Role identifier for the role allowed to supply isolated reserves as collateral - -
const ISOLATED_COLLATERAL_SUPPLIER_ROLE: vector<u8> = [73, 83, 79, 76, 65, 84, 69, 68, 95, 67, 79, 76, 76, 65, 84, 69, 82, 65, 76, 95, 83, 85, 80, 80, 76, 73, 69, 82];
+
const ISOLATED_COLLATERAL_SUPPLIER_ROLE: vector<u8> = [73, 83, 79, 76, 65, 84, 69, 68, 95, 67, 79, 76, 76, 65, 84, 69, 82, 65, 76, 95, 83, 85, 80, 80, 76, 73, 69, 82];
 
- + +Minimum health factor allowed under any circumstance +A value of 0.95e18 results in 0.95 +0.95 * 10 ** 18 -
const MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD: u256 = 950000000000000000;
+
const MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD: u256 = 950000000000000000;
 
- - - - -
const REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD: u256 = 9000;
-
- - - - + ## Function `init` +@notice Initializes the user configuration map -
public fun init(): user::UserConfigurationMap
+
public fun init(): user::UserConfigurationMap
 
- + ## Function `get_interest_rate_mode_none` -
public fun get_interest_rate_mode_none(): u8
+
public fun get_interest_rate_mode_none(): u8
 
- + ## Function `get_interest_rate_mode_variable` -
public fun get_interest_rate_mode_variable(): u8
+
public fun get_interest_rate_mode_variable(): u8
 
- + ## Function `get_borrowing_mask` -
public fun get_borrowing_mask(): u256
+
public fun get_borrowing_mask(): u256
 
- + ## Function `get_collateral_mask` -
public fun get_collateral_mask(): u256
-
- - - - - -## Function `get_rebalance_up_liquidity_rate_threshold` - - - -
public fun get_rebalance_up_liquidity_rate_threshold(): u256
+
public fun get_collateral_mask(): u256
 
- + ## Function `get_minimum_health_factor_liquidation_threshold` -
public fun get_minimum_health_factor_liquidation_threshold(): u256
+
public fun get_minimum_health_factor_liquidation_threshold(): u256
 
- + ## Function `get_health_factor_liquidation_threshold` -
public fun get_health_factor_liquidation_threshold(): u256
+
public fun get_health_factor_liquidation_threshold(): u256
 
- + ## Function `get_isolated_collateral_supplier_role` -
public fun get_isolated_collateral_supplier_role(): vector<u8>
+
public fun get_isolated_collateral_supplier_role(): vector<u8>
 
- + ## Function `set_borrowing` +@notice Sets if the user is borrowing the reserve identified by reserve_index +@param self The configuration object +@param reserve_index The index of the reserve in the bitmap +@param borrowing True if the user is borrowing the reserve, false otherwise -
public fun set_borrowing(user_configuration: &mut user::UserConfigurationMap, reserve_index: u256, borrowing: bool)
+
public fun set_borrowing(self: &mut user::UserConfigurationMap, reserve_index: u256, borrowing: bool)
 
- + ## Function `set_using_as_collateral` +@notice Sets if the user is using as collateral the reserve identified by reserve_index +@param self The configuration object +@param reserve_index The index of the reserve in the bitmap +@param using_as_collateral True if the user is using the reserve as collateral, false otherwise -
public fun set_using_as_collateral(user_configuration: &mut user::UserConfigurationMap, reserve_index: u256, using_as_collateral: bool)
+
public fun set_using_as_collateral(self: &mut user::UserConfigurationMap, reserve_index: u256, using_as_collateral: bool)
 
- + ## Function `is_using_as_collateral_or_borrowing` +@notice Returns if a user has been using the reserve for borrowing or as collateral +@param self The configuration object +@param reserve_index The index of the reserve in the bitmap +@return True if the user has been using a reserve for borrowing or as collateral, false otherwise -
public fun is_using_as_collateral_or_borrowing(user_configuration: &user::UserConfigurationMap, reserve_index: u256): bool
+
public fun is_using_as_collateral_or_borrowing(self: &user::UserConfigurationMap, reserve_index: u256): bool
 
- + ## Function `is_borrowing` +@notice Validate a user has been using the reserve for borrowing +@param self The configuration object +@param reserve_index The index of the reserve in the bitmap +@return True if the user has been using a reserve for borrowing, false otherwise -
public fun is_borrowing(user_configuration: &user::UserConfigurationMap, reserve_index: u256): bool
+
public fun is_borrowing(self: &user::UserConfigurationMap, reserve_index: u256): bool
 
- + ## Function `is_using_as_collateral` +@notice Validate a user has been using the reserve as collateral +@param self The configuration object +@param reserve_index The index of the reserve in the bitmap +@return True if the user has been using a reserve as collateral, false otherwise -
public fun is_using_as_collateral(user_configuration: &user::UserConfigurationMap, reserve_index: u256): bool
+
public fun is_using_as_collateral(self: &user::UserConfigurationMap, reserve_index: u256): bool
 
- + ## Function `is_using_as_collateral_one` +@notice Checks if a user has been supplying only one reserve as collateral +@dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0 +@param self The configuration object +@return True if the user has been supplying as collateral one reserve, false otherwise -
public fun is_using_as_collateral_one(user_configuration: &user::UserConfigurationMap): bool
+
public fun is_using_as_collateral_one(self: &user::UserConfigurationMap): bool
 
- + ## Function `is_using_as_collateral_any` +@notice Checks if a user has been supplying any reserve as collateral +@param self The configuration object +@return True if the user has been supplying as collateral any reserve, false otherwise -
public fun is_using_as_collateral_any(user_configuration: &user::UserConfigurationMap): bool
+
public fun is_using_as_collateral_any(self: &user::UserConfigurationMap): bool
 
- + ## Function `is_borrowing_one` +@notice Checks if a user has been borrowing only one asset +@dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0 +@param self The configuration object +@return True if the user has been supplying as collateral one reserve, false otherwise -
public fun is_borrowing_one(user_configuration: &user::UserConfigurationMap): bool
+
public fun is_borrowing_one(self: &user::UserConfigurationMap): bool
 
- + ## Function `is_borrowing_any` +@notice Checks if a user has been borrowing from any reserve +@param self The configuration object +@return True if the user has been borrowing any reserve, false otherwise -
public fun is_borrowing_any(user_configuration: &user::UserConfigurationMap): bool
+
public fun is_borrowing_any(self: &user::UserConfigurationMap): bool
 
- + ## Function `is_empty` +@notice Checks if a user has not been using any reserve for borrowing or supply +@param self The configuration object +@return True if the user has not been borrowing or supplying any reserve, false otherwise -
public fun is_empty(user_configuration: &user::UserConfigurationMap): bool
+
public fun is_empty(self: &user::UserConfigurationMap): bool
 
- + ## Function `get_first_asset_id_by_mask` +@notice Returns the address of the first asset flagged in the bitmap given the corresponding bitmask +@param self The configuration object +@return The index of the first asset flagged in the bitmap once the corresponding mask is applied -
public fun get_first_asset_id_by_mask(user_configuration: &user::UserConfigurationMap, mask: u256): u256
+
public fun get_first_asset_id_by_mask(self: &user::UserConfigurationMap, mask: u256): u256
 
diff --git a/aave-core/aave-config/sources/error_config.move b/aave-core/aave-config/sources/error_config.move index b627766..33e5bdf 100644 --- a/aave-core/aave-config/sources/error_config.move +++ b/aave-core/aave-config/sources/error_config.move @@ -1,3 +1,6 @@ +/// @title Errors library +/// @author Aave +/// @notice Defines the error messages emitted by the different contracts of the Aave protocol module aave_config::error { /// The caller of the function is not a pool admin const ECALLER_NOT_POOL_ADMIN: u64 = 1; @@ -175,6 +178,11 @@ module aave_config::error { const ERESERVES_STORAGE_COUNT_MISMATCH: u64 = 93; /// The person who signed must be consistent with on_behalf_of const ESIGNER_AND_ON_BEHALF_OF_NO_SAME: u64 = 94; + /// Account does not exist + const EACCOUNT_DOES_NOT_EXIST: u64 = 95; + + /// Flashloan payer is different from the flashloan receiver + const EFLASHLOAN_PAYER_NOT_RECEIVER: u64 = 95; public fun get_ecaller_not_pool_admin(): u64 { ECALLER_NOT_POOL_ADMIN @@ -524,4 +532,11 @@ module aave_config::error { ESIGNER_AND_ON_BEHALF_OF_NO_SAME } + public fun get_eaccount_does_not_exist(): u64 { + EACCOUNT_DOES_NOT_EXIST + } + + public fun get_flashloan_payer_not_receiver(): u64 { + EFLASHLOAN_PAYER_NOT_RECEIVER + } } diff --git a/aave-core/aave-config/sources/helper.move b/aave-core/aave-config/sources/helper.move index 553048c..02b46b5 100644 --- a/aave-core/aave-config/sources/helper.move +++ b/aave-core/aave-config/sources/helper.move @@ -1,6 +1,6 @@ module aave_config::helper { - // Get the result of bitwise negation + /// Get the result of bitwise negation public fun bitwise_negation(m: u256): u256 { let all_ones: u256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; @@ -10,8 +10,10 @@ module aave_config::helper { #[test] fun test_bitwise_negation() { - let ret = bitwise_negation( - 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000); + let ret = + bitwise_negation( + 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000 + ); assert!(ret == 65535, 1); } } diff --git a/aave-core/aave-config/sources/reserve_config.move b/aave-core/aave-config/sources/reserve_config.move index 935e70e..6000061 100644 --- a/aave-core/aave-config/sources/reserve_config.move +++ b/aave-core/aave-config/sources/reserve_config.move @@ -1,3 +1,6 @@ +/// @title ReserveConfiguration module +/// @author Aave +/// @notice Implements the bitmap logic to handle the reserve configuration module aave_config::reserve { use aave_config::error as error_config; use aave_config::helper; @@ -73,6 +76,7 @@ module aave_config::reserve { const DEBT_CEILING_DECIMALS: u256 = 2; const MAX_RESERVES_COUNT: u16 = 128; + struct ReserveConfigurationMap has key, store, copy, drop { /// bit 0-15: LTV /// bit 16-31: Liq. threshold @@ -97,6 +101,7 @@ module aave_config::reserve { data: u256, } + /// @notice init the reserve configuration public fun init(): ReserveConfigurationMap { ReserveConfigurationMap { data: 0 } } @@ -118,96 +123,137 @@ module aave_config::reserve { /// @notice Sets the liquidation threshold of the reserve /// @param self The reserve configuration - /// @param threshold The new liquidation threshold + /// @param liquidation_threshold The new liquidation threshold public fun set_liquidation_threshold( self: &mut ReserveConfigurationMap, liquidation_threshold: u256 ) { - assert!(liquidation_threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, - error_config::get_einvalid_liq_threshold()); - self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) |(liquidation_threshold << ( - LIQUIDATION_THRESHOLD_START_BIT_POSITION as u8 - )) + assert!( + liquidation_threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, + error_config::get_einvalid_liq_threshold(), + ); + self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) + |(liquidation_threshold << (LIQUIDATION_THRESHOLD_START_BIT_POSITION as u8)) } + /// @notice Gets the liquidation threshold of the reserve + /// @param self The reserve configuration + /// @return The liquidation threshold public fun get_liquidation_threshold(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(LIQUIDATION_THRESHOLD_MASK)) >> ( - LIQUIDATION_THRESHOLD_START_BIT_POSITION as u8 - ) + (self.data & helper::bitwise_negation(LIQUIDATION_THRESHOLD_MASK)) + >> (LIQUIDATION_THRESHOLD_START_BIT_POSITION as u8) } + /// @notice Sets the liquidation bonus of the reserve + /// @param self The reserve configuration + /// @param liquidation_bonus The new liquidation bonus public fun set_liquidation_bonus( self: &mut ReserveConfigurationMap, liquidation_bonus: u256 ) { - assert!(liquidation_bonus <= MAX_VALID_LIQUIDATION_BONUS, - error_config::get_einvalid_liq_bonus()); - self.data = (self.data & LIQUIDATION_BONUS_MASK) |(liquidation_bonus << ( - LIQUIDATION_BONUS_START_BIT_POSITION as u8 - )) + assert!( + liquidation_bonus <= MAX_VALID_LIQUIDATION_BONUS, + error_config::get_einvalid_liq_bonus(), + ); + self.data = (self.data & LIQUIDATION_BONUS_MASK) + |(liquidation_bonus << (LIQUIDATION_BONUS_START_BIT_POSITION as u8)) } + /// @notice Gets the liquidation bonus of the reserve + /// @param self The reserve configuration + /// @return The liquidation bonus public fun get_liquidation_bonus(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(LIQUIDATION_BONUS_MASK)) >> ( - LIQUIDATION_BONUS_START_BIT_POSITION as u8 - ) + (self.data & helper::bitwise_negation(LIQUIDATION_BONUS_MASK)) + >> (LIQUIDATION_BONUS_START_BIT_POSITION as u8) } + /// @notice Sets the decimals of the underlying asset of the reserve + /// @param self The reserve configuration + /// @param decimals The decimals public fun set_decimals( self: &mut ReserveConfigurationMap, decimals: u256 ) { assert!(decimals <= MAX_VALID_DECIMALS, error_config::get_einvalid_decimals()); - self.data = (self.data & DECIMALS_MASK) |(decimals << ( - RESERVE_DECIMALS_START_BIT_POSITION as u8 - )) + self.data = (self.data & DECIMALS_MASK) + |(decimals << (RESERVE_DECIMALS_START_BIT_POSITION as u8)) } + /// @notice Gets the decimals of the underlying asset of the reserve + /// @param self The reserve configuration + /// @return The decimals public fun get_decimals(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(DECIMALS_MASK)) >> ( - RESERVE_DECIMALS_START_BIT_POSITION as u8 - ) + (self.data & helper::bitwise_negation(DECIMALS_MASK)) + >> (RESERVE_DECIMALS_START_BIT_POSITION as u8) } - public fun set_active(self: &mut ReserveConfigurationMap, active: bool) { + /// @notice Sets the active state of the reserve + /// @param self The reserve configuration + /// @param active The new active state + public fun set_active( + self: &mut ReserveConfigurationMap, active: bool + ) { let active_state: u256 = 0; if (active) { active_state = 1; }; - self.data = (self.data & ACTIVE_MASK) | active_state << ( - IS_ACTIVE_START_BIT_POSITION as u8 - ) + self.data = (self.data & ACTIVE_MASK) + | active_state << (IS_ACTIVE_START_BIT_POSITION as u8) } + /// @notice Gets the active state of the reserve + /// @param self The reserve configuration + /// @return The active state public fun get_active(self: &ReserveConfigurationMap): bool { (self.data & helper::bitwise_negation(ACTIVE_MASK)) != 0 } - public fun set_frozen(self: &mut ReserveConfigurationMap, frozen: bool) { + /// @notice Sets the frozen state of the reserve + /// @param self The reserve configuration + /// @param frozen The new frozen state + public fun set_frozen( + self: &mut ReserveConfigurationMap, frozen: bool + ) { let frozen_state: u256 = 0; if (frozen) { frozen_state = 1; }; - self.data = (self.data & FROZEN_MASK) |(frozen_state << ( - IS_FROZEN_START_BIT_POSITION as u8 - )) + self.data = (self.data & FROZEN_MASK) + |(frozen_state << (IS_FROZEN_START_BIT_POSITION as u8)) } + /// @notice Gets the frozen state of the reserve + /// @param self The reserve configuration + /// @return The frozen state public fun get_frozen(self: &ReserveConfigurationMap): bool { (self.data & helper::bitwise_negation(FROZEN_MASK)) != 0 } - public fun set_paused(self: &mut ReserveConfigurationMap, paused: bool) { + /// @notice Sets the paused state of the reserve + /// @param self The reserve configuration + /// @param paused The new paused state + public fun set_paused( + self: &mut ReserveConfigurationMap, paused: bool + ) { let paused_state: u256 = 0; if (paused) { paused_state = 1; }; - self.data = (self.data & PAUSED_MASK) |(paused_state << ( - IS_PAUSED_START_BIT_POSITION as u8 - )) + self.data = (self.data & PAUSED_MASK) + |(paused_state << (IS_PAUSED_START_BIT_POSITION as u8)) } + /// @notice Gets the paused state of the reserve + /// @param self The reserve configuration + /// @return The paused state public fun get_paused(self: &ReserveConfigurationMap): bool { (self.data & helper::bitwise_negation(PAUSED_MASK)) != 0 } + /// @notice Sets the borrowing in isolation state of the reserve + /// @dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the borrowed + /// amount will be accumulated in the isolated collateral's total debt exposure. + /// @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep + /// consistency in the debt ceiling calculations. + /// @param self The reserve configuration + /// @param borrowable The new borrowing in isolation state public fun set_borrowable_in_isolation( self: &mut ReserveConfigurationMap, borrowable: bool ) { @@ -215,15 +261,25 @@ module aave_config::reserve { if (borrowable) { borrowable_state = 1; }; - self.data = (self.data & BORROWABLE_IN_ISOLATION_MASK) |(borrowable_state << ( - BORROWABLE_IN_ISOLATION_START_BIT_POSITION as u8 - )) + self.data = (self.data & BORROWABLE_IN_ISOLATION_MASK) + |(borrowable_state << (BORROWABLE_IN_ISOLATION_START_BIT_POSITION as u8)) } + /// @notice Gets the borrowable in isolation flag for the reserve. + /// @dev If the returned flag is true, the asset is borrowable against isolated collateral. Assets borrowed with + /// isolated collateral is accounted for in the isolated collateral's total debt exposure. + /// @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep + /// consistency in the debt ceiling calculations. + /// @param self The reserve configuration + /// @return The borrowable in isolation flag public fun get_borrowable_in_isolation(self: &ReserveConfigurationMap): bool { (self.data & helper::bitwise_negation(BORROWABLE_IN_ISOLATION_MASK)) != 0 } + /// @notice Sets the siloed borrowing flag for the reserve. + /// @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset. + /// @param self The reserve configuration + /// @param siloed_borrowing True if the asset is siloed public fun set_siloed_borrowing( self: &mut ReserveConfigurationMap, siloed_borrowing: bool ) { @@ -231,15 +287,21 @@ module aave_config::reserve { if (siloed_borrowing) { siloed_borrowing_state = 1; }; - self.data = (self.data & SILOED_BORROWING_MASK) | siloed_borrowing_state << ( - SILOED_BORROWING_START_BIT_POSITION as u8 - ) + self.data = (self.data & SILOED_BORROWING_MASK) + | siloed_borrowing_state << (SILOED_BORROWING_START_BIT_POSITION as u8) } + /// @notice Gets the siloed borrowing flag for the reserve. + /// @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset. + /// @param self The reserve configuration + /// @return The siloed borrowing flag public fun get_siloed_borrowing(self: &ReserveConfigurationMap): bool { (self.data & helper::bitwise_negation(SILOED_BORROWING_MASK)) != 0 } + /// @notice Enables or disables borrowing on the reserve + /// @param self The reserve configuration + /// @param borrowing_enabled True if the borrowing needs to be enabled, false otherwise public fun set_borrowing_enabled( self: &mut ReserveConfigurationMap, borrowing_enabled: bool ) { @@ -247,127 +309,180 @@ module aave_config::reserve { if (borrowing_enabled) { borrowing_enabled_state = 1; }; - self.data = (self.data & BORROWING_MASK) | borrowing_enabled_state << ( - BORROWING_ENABLED_START_BIT_POSITION as u8 - ) + self.data = (self.data & BORROWING_MASK) + | borrowing_enabled_state << (BORROWING_ENABLED_START_BIT_POSITION as u8) } + /// @notice Gets the borrowing state of the reserve + /// @param self The reserve configuration + /// @return The borrowing state public fun get_borrowing_enabled(self: &ReserveConfigurationMap): bool { (self.data & helper::bitwise_negation(BORROWING_MASK)) != 0 } + /// @notice Sets the reserve factor of the reserve + /// @param self The reserve configuration + /// @param reserve_factor The reserve factor public fun set_reserve_factor( self: &mut ReserveConfigurationMap, reserve_factor: u256 ) { - assert!(reserve_factor <= MAX_VALID_RESERVE_FACTOR, - error_config::get_einvalid_reserve_factor()); + assert!( + reserve_factor <= MAX_VALID_RESERVE_FACTOR, + error_config::get_einvalid_reserve_factor(), + ); - self.data = (self.data & RESERVE_FACTOR_MASK) |(reserve_factor << ( - RESERVE_FACTOR_START_BIT_POSITION as u8 - )) + self.data = (self.data & RESERVE_FACTOR_MASK) + |(reserve_factor << (RESERVE_FACTOR_START_BIT_POSITION as u8)) } + /// @notice Gets the reserve factor of the reserve + /// @param self The reserve configuration + /// @return The reserve factor public fun get_reserve_factor(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(RESERVE_FACTOR_MASK)) >> ( - RESERVE_FACTOR_START_BIT_POSITION as u8 - ) + (self.data & helper::bitwise_negation(RESERVE_FACTOR_MASK)) + >> (RESERVE_FACTOR_START_BIT_POSITION as u8) } + /// @notice Sets the borrow cap of the reserve + /// @param self The reserve configuration + /// @param borrow_cap The borrow cap public fun set_borrow_cap( self: &mut ReserveConfigurationMap, borrow_cap: u256 ) { - assert!(borrow_cap <= MAX_VALID_BORROW_CAP, error_config::get_einvalid_borrow_cap()); - self.data = (self.data & BORROW_CAP_MASK) |(borrow_cap << ( - BORROW_CAP_START_BIT_POSITION as u8 - )); + assert!( + borrow_cap <= MAX_VALID_BORROW_CAP, error_config::get_einvalid_borrow_cap() + ); + self.data = (self.data & BORROW_CAP_MASK) + |(borrow_cap << (BORROW_CAP_START_BIT_POSITION as u8)); } + /// @notice Gets the borrow cap of the reserve + /// @param self The reserve configuration + /// @return The borrow cap public fun get_borrow_cap(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(BORROW_CAP_MASK)) >> ( - BORROW_CAP_START_BIT_POSITION as u8 - ) + (self.data & helper::bitwise_negation(BORROW_CAP_MASK)) + >> (BORROW_CAP_START_BIT_POSITION as u8) } + /// @notice Sets the supply cap of the reserve + /// @param self The reserve configuration + /// @param supply_cap The supply cap public fun set_supply_cap( self: &mut ReserveConfigurationMap, supply_cap: u256 ) { - assert!(supply_cap <= MAX_VALID_SUPPLY_CAP, error_config::get_einvalid_supply_cap()); - self.data = (self.data & SUPPLY_CAP_MASK) |(supply_cap << ( - SUPPLY_CAP_START_BIT_POSITION as u8 - )) + assert!( + supply_cap <= MAX_VALID_SUPPLY_CAP, error_config::get_einvalid_supply_cap() + ); + self.data = (self.data & SUPPLY_CAP_MASK) + |(supply_cap << (SUPPLY_CAP_START_BIT_POSITION as u8)) } + /// @notice Gets the supply cap of the reserve + /// @param self The reserve configuration + /// @return The supply cap public fun get_supply_cap(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(SUPPLY_CAP_MASK)) >> ( - SUPPLY_CAP_START_BIT_POSITION as u8 - ) + (self.data & helper::bitwise_negation(SUPPLY_CAP_MASK)) + >> (SUPPLY_CAP_START_BIT_POSITION as u8) } + /// @notice Sets the debt ceiling in isolation mode for the asset + /// @param self The reserve configuration + /// @param debt_ceiling The maximum debt ceiling for the asset public fun set_debt_ceiling( self: &mut ReserveConfigurationMap, debt_ceiling: u256 ) { - assert!(debt_ceiling <= MAX_VALID_DEBT_CEILING, - error_config::get_einvalid_debt_ceiling()); + assert!( + debt_ceiling <= MAX_VALID_DEBT_CEILING, + error_config::get_einvalid_debt_ceiling(), + ); - self.data = (self.data & DEBT_CEILING_MASK) |(debt_ceiling << ( - DEBT_CEILING_START_BIT_POSITION as u8 - )); + self.data = (self.data & DEBT_CEILING_MASK) + |(debt_ceiling << (DEBT_CEILING_START_BIT_POSITION as u8)); } + /// @notice Gets the debt ceiling for the asset if the asset is in isolation mode + /// @param self The reserve configuration + /// @return The debt ceiling (0 = isolation mode disabled) public fun get_debt_ceiling(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(DEBT_CEILING_MASK)) >> ( - DEBT_CEILING_START_BIT_POSITION as u8 - ) + (self.data & helper::bitwise_negation(DEBT_CEILING_MASK)) + >> (DEBT_CEILING_START_BIT_POSITION as u8) } + /// @notice Sets the liquidation protocol fee of the reserve + /// @param self The reserve configuration + /// @param liquidation_protocol_fee The liquidation protocol fee public fun set_liquidation_protocol_fee( self: &mut ReserveConfigurationMap, liquidation_protocol_fee: u256 ) { - assert!(liquidation_protocol_fee <= MAX_VALID_LIQUIDATION_PROTOCOL_FEE, - error_config::get_einvalid_liquidation_protocol_fee()); - self.data = (self.data & LIQUIDATION_PROTOCOL_FEE_MASK) |(liquidation_protocol_fee - << (LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION as u8)) - } - - public fun get_liquidation_protocol_fee(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(LIQUIDATION_PROTOCOL_FEE_MASK)) >> ( - LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION as u8 - ) + assert!( + liquidation_protocol_fee <= MAX_VALID_LIQUIDATION_PROTOCOL_FEE, + error_config::get_einvalid_liquidation_protocol_fee(), + ); + self.data = (self.data & LIQUIDATION_PROTOCOL_FEE_MASK) + |( + liquidation_protocol_fee + << (LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION as u8) + ) + } + + /// @dev Gets the liquidation protocol fee + /// @param self The reserve configuration + /// @return The liquidation protocol fee + public fun get_liquidation_protocol_fee( + self: &ReserveConfigurationMap + ): u256 { + (self.data & helper::bitwise_negation(LIQUIDATION_PROTOCOL_FEE_MASK)) + >> (LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION as u8) } + /// @notice Sets the unbacked mint cap of the reserve + /// @param self The reserve configuration + /// @param unbacked_mint_cap The unbacked mint cap public fun set_unbacked_mint_cap( self: &mut ReserveConfigurationMap, unbacked_mint_cap: u256 ) { - assert!(unbacked_mint_cap <= MAX_VALID_UNBACKED_MINT_CAP, - error_config::get_einvalid_unbacked_mint_cap()); + assert!( + unbacked_mint_cap <= MAX_VALID_UNBACKED_MINT_CAP, + error_config::get_einvalid_unbacked_mint_cap(), + ); - self.data = (self.data & UNBACKED_MINT_CAP_MASK) |(unbacked_mint_cap << ( - UNBACKED_MINT_CAP_START_BIT_POSITION as u8 - )) + self.data = (self.data & UNBACKED_MINT_CAP_MASK) + |(unbacked_mint_cap << (UNBACKED_MINT_CAP_START_BIT_POSITION as u8)) } + /// @dev Gets the unbacked mint cap of the reserve + /// @param self The reserve configuration + /// @return The unbacked mint cap public fun get_unbacked_mint_cap(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(UNBACKED_MINT_CAP_MASK)) >> ( - UNBACKED_MINT_CAP_START_BIT_POSITION as u8 - ) + (self.data & helper::bitwise_negation(UNBACKED_MINT_CAP_MASK)) + >> (UNBACKED_MINT_CAP_START_BIT_POSITION as u8) } + /// @notice Sets the eMode asset category + /// @param self The reserve configuration + /// @param emode_category The asset category when the user selects the eMode public fun set_emode_category( self: &mut ReserveConfigurationMap, emode_category: u256 ) { - assert!(emode_category <= MAX_VALID_EMODE_CATEGORY, - error_config::get_einvalid_emode_category()); - self.data = (self.data & EMODE_CATEGORY_MASK) |(emode_category << ( - EMODE_CATEGORY_START_BIT_POSITION as u8 - )) + assert!( + emode_category <= MAX_VALID_EMODE_CATEGORY, + error_config::get_einvalid_emode_category(), + ); + self.data = (self.data & EMODE_CATEGORY_MASK) + |(emode_category << (EMODE_CATEGORY_START_BIT_POSITION as u8)) } + /// @dev Gets the eMode asset category + /// @param self The reserve configuration + /// @return The eMode category for the asset public fun get_emode_category(self: &ReserveConfigurationMap): u256 { - (self.data & helper::bitwise_negation(EMODE_CATEGORY_MASK)) >> ( - EMODE_CATEGORY_START_BIT_POSITION as u8 - ) + (self.data & helper::bitwise_negation(EMODE_CATEGORY_MASK)) + >> (EMODE_CATEGORY_START_BIT_POSITION as u8) } + /// @notice Sets the flashloanable flag for the reserve + /// @param self The reserve configuration + /// @param flash_loan_enabled True if the asset is flashloanable, false otherwise public fun set_flash_loan_enabled( self: &mut ReserveConfigurationMap, flash_loan_enabled: bool ) { @@ -375,21 +490,41 @@ module aave_config::reserve { if (flash_loan_enabled) { flash_loan_enabled_state = 1; }; - self.data = (self.data & FLASHLOAN_ENABLED_MASK) |(flash_loan_enabled_state << ( - FLASHLOAN_ENABLED_START_BIT_POSITION as u8 - )) + self.data = (self.data & FLASHLOAN_ENABLED_MASK) + |(flash_loan_enabled_state << (FLASHLOAN_ENABLED_START_BIT_POSITION as u8)) } + /// @notice Gets the flashloanable flag for the reserve + /// @param self The reserve configuration + /// @return The flashloanable flag public fun get_flash_loan_enabled(self: &ReserveConfigurationMap): bool { (self.data & helper::bitwise_negation(FLASHLOAN_ENABLED_MASK)) != 0 } + /// @notice Gets the configuration flags of the reserve + /// @param self The reserve configuration + /// @return The state flag representing active + /// @return The state flag representing frozen + /// @return The state flag representing borrowing enabled + /// @return The state flag representing paused public fun get_flags(self: &ReserveConfigurationMap): (bool, bool, bool, bool) { - (get_active(self), get_frozen(self), get_borrowing_enabled(self), get_paused(self),) + ( + get_active(self), get_frozen(self), get_borrowing_enabled(self), + get_paused(self), + ) } + /// @notice Gets the configuration parameters of the reserve from storage + /// @param self The reserve configuration + /// @return The state param representing ltv + /// @return The state param representing liquidation threshold + /// @return The state param representing liquidation bonus + /// @return The state param representing reserve decimals + /// @return The state param representing reserve factor + /// @return The state param representing eMode category public fun get_params(self: &ReserveConfigurationMap): (u256, u256, u256, u256, u256, u256) { - (get_ltv(self), + ( + get_ltv(self), get_liquidation_threshold(self), get_liquidation_bonus(self), get_decimals(self), @@ -398,14 +533,20 @@ module aave_config::reserve { ) } + /// @notice Gets the caps parameters of the reserve from storage + /// @param self The reserve configuration + /// @return The state param representing borrow cap + /// @return The state param representing supply cap. public fun get_caps(self: &ReserveConfigurationMap): (u256, u256) { (get_borrow_cap(self), get_supply_cap(self)) } + /// @notice Gets the debt ceiling decimals public fun get_debt_ceiling_decimals(): u256 { DEBT_CEILING_DECIMALS } + /// @notice Gets the maximum number of reserves public fun get_max_reserves_count(): u16 { MAX_RESERVES_COUNT } diff --git a/aave-core/aave-config/sources/user_config.move b/aave-core/aave-config/sources/user_config.move index 3e2e9cf..f7285a2 100644 --- a/aave-core/aave-config/sources/user_config.move +++ b/aave-core/aave-config/sources/user_config.move @@ -1,3 +1,6 @@ +/// @title UserConfiguration library +/// @author Aave +/// @notice Implements the bitmap logic to handle the user configuration module aave_config::user { use aave_config::error as error_config; use aave_config::helper; @@ -7,42 +10,32 @@ module aave_config::user { 0x5555555555555555555555555555555555555555555555555555555555555555; const COLLATERAL_MASK: u256 = 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA; - // Factor to apply to "only-variable-debt" liquidity rate to get threshold for rebalancing, expressed in bps - // A value of 0.9e4 results in 90% - // 0.9 * 10 ** 4 - const REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD: u256 = 9000; - - // Minimum health factor allowed under any circumstance - // A value of 0.95e18 results in 0.95 - // 0.95 * 10 ** 18 - const MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD: u256 = 950000000000000000; - /** - * @dev Minimum health factor to consider a user position healthy - * A value of 1e18 results in 1 - */ + /// Minimum health factor allowed under any circumstance + /// A value of 0.95e18 results in 0.95 + /// 0.95 * 10 ** 18 + const MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD: u256 = 950000000000000000; - // 1 * 10 ** 18 + /// @dev Minimum health factor to consider a user position healthy + /// A value of 1e18 results in 1 + /// 1 * 10 ** 18 const HEALTH_FACTOR_LIQUIDATION_THRESHOLD: u256 = 1000000000000000000; - /** - * @dev Role identifier for the role allowed to supply isolated reserves as collateral - */ + /// @dev Role identifier for the role allowed to supply isolated reserves as collateral const ISOLATED_COLLATERAL_SUPPLIER_ROLE: vector = b"ISOLATED_COLLATERAL_SUPPLIER"; const INTEREST_RATE_MODE_NONE: u8 = 0; - // 1 = Stable Rate, 2 = Variable Rate, Since the Stable Rate service has been removed, only the Variable Rate service is retained. + /// 1 = Stable Rate, 2 = Variable Rate, Since the Stable Rate service has been removed, only the Variable Rate service is retained. const INTEREST_RATE_MODE_VARIABLE: u8 = 2; struct UserConfigurationMap has key, copy, store, drop { - /** - * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset. - * The first bit indicates if an asset is used as collateral by the user, the second whether an - * asset is borrowed by the user. - */ + /// @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset. + /// The first bit indicates if an asset is used as collateral by the user, the second whether an + /// asset is borrowed by the user. data: u256, } + /// @notice Initializes the user configuration map public fun init(): UserConfigurationMap { UserConfigurationMap { data: 0 } } @@ -69,10 +62,6 @@ module aave_config::user { COLLATERAL_MASK } - public fun get_rebalance_up_liquidity_rate_threshold(): u256 { - REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD - } - public fun get_minimum_health_factor_liquidation_threshold(): u256 { MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD } @@ -85,93 +74,137 @@ module aave_config::user { ISOLATED_COLLATERAL_SUPPLIER_ROLE } + /// @notice Sets if the user is borrowing the reserve identified by reserve_index + /// @param self The configuration object + /// @param reserve_index The index of the reserve in the bitmap + /// @param borrowing True if the user is borrowing the reserve, false otherwise public fun set_borrowing( - user_configuration: &mut UserConfigurationMap, reserve_index: u256, borrowing: bool + self: &mut UserConfigurationMap, reserve_index: u256, borrowing: bool ) { - assert!(reserve_index < (reserve_config::get_max_reserves_count() as u256), - error_config::get_einvalid_reserve_index()); + assert!( + reserve_index < (reserve_config::get_max_reserves_count() as u256), + error_config::get_einvalid_reserve_index(), + ); let bit = 1 << ((reserve_index << 1) as u8); if (borrowing) { - user_configuration.data = user_configuration.data | bit; + self.data = self.data | bit; } else { - user_configuration.data = user_configuration.data & helper::bitwise_negation(bit); + self.data = self.data & helper::bitwise_negation(bit); } } + /// @notice Sets if the user is using as collateral the reserve identified by reserve_index + /// @param self The configuration object + /// @param reserve_index The index of the reserve in the bitmap + /// @param using_as_collateral True if the user is using the reserve as collateral, false otherwise public fun set_using_as_collateral( - user_configuration: &mut UserConfigurationMap, reserve_index: u256, - using_as_collateral: bool, + self: &mut UserConfigurationMap, reserve_index: u256, using_as_collateral: bool, ) { - assert!(reserve_index < (reserve_config::get_max_reserves_count() as u256), - error_config::get_einvalid_reserve_index()); + assert!( + reserve_index < (reserve_config::get_max_reserves_count() as u256), + error_config::get_einvalid_reserve_index(), + ); let bit: u256 = 1 << (((reserve_index << 1) + 1) as u8); if (using_as_collateral) { - user_configuration.data = user_configuration.data | bit; + self.data = self.data | bit; } else { - user_configuration.data = user_configuration.data & helper::bitwise_negation(bit); + self.data = self.data & helper::bitwise_negation(bit); } } + /// @notice Returns if a user has been using the reserve for borrowing or as collateral + /// @param self The configuration object + /// @param reserve_index The index of the reserve in the bitmap + /// @return True if the user has been using a reserve for borrowing or as collateral, false otherwise public fun is_using_as_collateral_or_borrowing( - user_configuration: &UserConfigurationMap, reserve_index: u256 + self: &UserConfigurationMap, reserve_index: u256 ): bool { - assert!(reserve_index < (reserve_config::get_max_reserves_count() as u256), - error_config::get_einvalid_reserve_index()); - (user_configuration.data >> ((reserve_index << 1) as u8)) + assert!( + reserve_index < (reserve_config::get_max_reserves_count() as u256), + error_config::get_einvalid_reserve_index(), + ); + (self.data >> ((reserve_index << 1) as u8)) & 3 != 0 } + /// @notice Validate a user has been using the reserve for borrowing + /// @param self The configuration object + /// @param reserve_index The index of the reserve in the bitmap + /// @return True if the user has been using a reserve for borrowing, false otherwise public fun is_borrowing( - user_configuration: &UserConfigurationMap, reserve_index: u256 + self: &UserConfigurationMap, reserve_index: u256 ): bool { - assert!(reserve_index < (reserve_config::get_max_reserves_count() as u256), - error_config::get_einvalid_reserve_index()); - (user_configuration.data >> ((reserve_index << 1) as u8)) + assert!( + reserve_index < (reserve_config::get_max_reserves_count() as u256), + error_config::get_einvalid_reserve_index(), + ); + (self.data >> ((reserve_index << 1) as u8)) & 1 != 0 } + /// @notice Validate a user has been using the reserve as collateral + /// @param self The configuration object + /// @param reserve_index The index of the reserve in the bitmap + /// @return True if the user has been using a reserve as collateral, false otherwise public fun is_using_as_collateral( - user_configuration: &UserConfigurationMap, reserve_index: u256 + self: &UserConfigurationMap, reserve_index: u256 ): bool { - assert!(reserve_index < (reserve_config::get_max_reserves_count() as u256), - error_config::get_einvalid_reserve_index()); - (user_configuration.data >> ((reserve_index << 1) as u8) + 1) + assert!( + reserve_index < (reserve_config::get_max_reserves_count() as u256), + error_config::get_einvalid_reserve_index(), + ); + (self.data >> ((reserve_index << 1) as u8) + 1) & 1 != 0 } - public fun is_using_as_collateral_one( - user_configuration: &UserConfigurationMap - ): bool { - let user_configuration_data = user_configuration.data & COLLATERAL_MASK; - user_configuration_data != 0 && (user_configuration_data & (user_configuration_data - - 1) == 0) + /// @notice Checks if a user has been supplying only one reserve as collateral + /// @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0 + /// @param self The configuration object + /// @return True if the user has been supplying as collateral one reserve, false otherwise + public fun is_using_as_collateral_one(self: &UserConfigurationMap): bool { + let self_data = self.data & COLLATERAL_MASK; + self_data != 0 && (self_data & (self_data - 1) == 0) } - public fun is_using_as_collateral_any( - user_configuration: &UserConfigurationMap - ): bool { - user_configuration.data & COLLATERAL_MASK != 0 + /// @notice Checks if a user has been supplying any reserve as collateral + /// @param self The configuration object + /// @return True if the user has been supplying as collateral any reserve, false otherwise + public fun is_using_as_collateral_any(self: &UserConfigurationMap): bool { + self.data & COLLATERAL_MASK != 0 } - public fun is_borrowing_one(user_configuration: &UserConfigurationMap): bool { - let borrowing_data = user_configuration.data & BORROWING_MASK; + /// @notice Checks if a user has been borrowing only one asset + /// @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0 + /// @param self The configuration object + /// @return True if the user has been supplying as collateral one reserve, false otherwise + public fun is_borrowing_one(self: &UserConfigurationMap): bool { + let borrowing_data = self.data & BORROWING_MASK; borrowing_data != 0 && (borrowing_data & (borrowing_data - 1) == 0) } - public fun is_borrowing_any(user_configuration: &UserConfigurationMap): bool { - user_configuration.data & BORROWING_MASK != 0 + /// @notice Checks if a user has been borrowing from any reserve + /// @param self The configuration object + /// @return True if the user has been borrowing any reserve, false otherwise + public fun is_borrowing_any(self: &UserConfigurationMap): bool { + self.data & BORROWING_MASK != 0 } - public fun is_empty(user_configuration: &UserConfigurationMap): bool { - user_configuration.data == 0 + /// @notice Checks if a user has not been using any reserve for borrowing or supply + /// @param self The configuration object + /// @return True if the user has not been borrowing or supplying any reserve, false otherwise + public fun is_empty(self: &UserConfigurationMap): bool { + self.data == 0 } + /// @notice Returns the address of the first asset flagged in the bitmap given the corresponding bitmask + /// @param self The configuration object + /// @return The index of the first asset flagged in the bitmap once the corresponding mask is applied public fun get_first_asset_id_by_mask( - user_configuration: &UserConfigurationMap, mask: u256 + self: &UserConfigurationMap, mask: u256 ): u256 { - let bit_map_data = user_configuration.data & mask; - let first_asset_position = - bit_map_data & helper::bitwise_negation(bit_map_data - 1); + let bit_map_data = self.data & mask; + let first_asset_position = bit_map_data + & helper::bitwise_negation(bit_map_data - 1); let id: u256 = 0; first_asset_position = first_asset_position >> 2; while (first_asset_position != 0) { @@ -186,11 +219,6 @@ module aave_config::user { *borrow_global(@aave_config) } - #[test_only] - public fun get_rebalance_up_liquidity_rate_threshold_for_testing(): u256 { - REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD - } - #[test_only] public fun get_minimum_health_factor_liquidation_threshold_for_testing(): u256 { MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD diff --git a/aave-core/aave-config/tests/error_tests.move b/aave-core/aave-config/tests/error_tests.move new file mode 100644 index 0000000..121d89c --- /dev/null +++ b/aave-core/aave-config/tests/error_tests.move @@ -0,0 +1,867 @@ +#[test_only] +module aave_config::error_tests { + use aave_config::error::{ + get_ecaller_not_pool_admin, + get_ecaller_not_emergency_admin, + get_ecaller_not_pool_or_emergency_admin, + get_ecaller_not_risk_or_pool_admin, + get_ecaller_not_asset_listing_or_pool_admin, + get_ecaller_not_bridge, + get_eaddresses_provider_not_registered, + get_einvalid_addresses_provider_id, + get_enot_contract, + get_ecaller_not_pool_configurator, + get_ecaller_not_atoken, + get_einvalid_addresses_provider, + get_einvalid_flashloan_executor_return, + get_ereserve_already_added, + get_ereserves_storage_count_mismatch, + get_eno_more_reserves_allowed, + get_eemode_category_reserved, + get_einvalid_emode_category_assignment, + get_ereserve_liquidity_not_zero, + get_eflashloan_premium_invalid, + get_einvalid_reserve_params, + get_einvalid_emode_category_params, + get_ebridge_protocol_fee_invalid, + get_ecaller_must_be_pool, + get_einvalid_mint_amount, + get_einvalid_burn_amount, + get_einvalid_amount, + get_ereserve_inactive, + get_ereserve_frozen, + get_ereserve_paused, + get_eborrowing_not_enabled, + get_einvalid_interest_rate_mode_selected, + get_ehealth_factor_lower_than_liquidation_threshold, + get_ecollateral_cannot_cover_new_borrow, + get_ecollateral_same_as_borrowing_currency, + get_eno_debt_of_selected_type, + get_eno_explicit_amount_to_repay_on_behalf, + get_eno_outstanding_variable_debt, + get_eunderlying_balance_zero, + get_einterest_rate_rebalance_conditions_not_met, + get_ehealth_factor_not_below_threshold, + get_ecollateral_cannot_be_liquidated, + get_especified_currency_not_borrowed_by_user, + get_einconsistent_flashloan_params, + get_eborrow_cap_exceeded, + get_esupply_cap_exceeded, + get_eunbacked_mint_cap_exceeded, + get_edebt_ceiling_exceeded, + get_eunderlying_claimable_rights_not_zero, + get_evariable_debt_supply_not_zero, + get_enot_enough_available_user_balance, + get_ecollateral_balance_is_zero, + get_eltv_validation_failed, + get_einconsistent_emode_category, + get_eprice_oracle_sentinel_check_failed, + get_easset_not_borrowable_in_isolation, + get_ereserve_already_initialized, + get_euser_in_isolation_mode_or_ltv_zero, + get_einvalid_ltv, + get_einvalid_liq_threshold, + get_einvalid_liq_bonus, + get_einvalid_decimals, + get_einvalid_borrow_cap, + get_einvalid_supply_cap, + get_einvalid_liquidation_protocol_fee, + get_einvalid_reserve_factor, + get_einvalid_emode_category, + get_einvalid_unbacked_mint_cap, + get_einvalid_debt_ceiling, + get_einvalid_reserve_index, + get_eacl_admin_cannot_be_zero, + get_einconsistent_params_length, + get_ezero_address_not_valid, + get_einvalid_expiration, + get_einvalid_signature, + get_eoperation_not_supported, + get_edebt_ceiling_not_zero, + get_easset_not_listed, + get_einvalid_optimal_usage_ratio, + get_eunderlying_cannot_be_rescued, + get_eaddresses_provider_already_added, + get_epool_addresses_do_not_match, + get_esiloed_borrowing_violation, + get_ereserve_debt_not_zero, + get_eflashloan_disabled, + get_euser_not_listed, + get_esigner_and_on_behalf_of_no_same, + get_eaccount_does_not_exist, + get_flashloan_payer_not_receiver, + }; + + const TEST_SUCCESS: u64 = 1; + const TEST_FAILED: u64 = 2; + + /// The caller of the function is not a pool admin + const ECALLER_NOT_POOL_ADMIN: u64 = 1; + /// The caller of the function is not an emergency admin + const ECALLER_NOT_EMERGENCY_ADMIN: u64 = 2; + /// The caller of the function is not a pool or emergency admin + const ECALLER_NOT_POOL_OR_EMERGENCY_ADMIN: u64 = 3; + /// The caller of the function is not a risk or pool admin + const ECALLER_NOT_RISK_OR_POOL_ADMIN: u64 = 4; + /// The caller of the function is not an asset listing or pool admin + const ECALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN: u64 = 5; + /// The caller of the function is not a bridge + const ECALLER_NOT_BRIDGE: u64 = 6; + /// Pool addresses provider is not registered + const EADDRESSES_PROVIDER_NOT_REGISTERED: u64 = 7; + /// Invalid id for the pool addresses provider + const EINVALID_ADDRESSES_PROVIDER_ID: u64 = 8; + /// Address is not a contract + const ENOT_CONTRACT: u64 = 9; + /// The caller of the function is not the pool configurator + const ECALLER_NOT_POOL_CONFIGURATOR: u64 = 10; + /// The caller of the function is not an AToken + const ECALLER_NOT_ATOKEN: u64 = 11; + /// The address of the pool addresses provider is invalid + const EINVALID_ADDRESSES_PROVIDER: u64 = 12; + /// Invalid return value of the flashloan executor function + const EINVALID_FLASHLOAN_EXECUTOR_RETURN: u64 = 13; + /// Reserve has already been added to reserve list + const ERESERVE_ALREADY_ADDED: u64 = 14; + /// Maximum amount of reserves in the pool reached + const ENO_MORE_RESERVES_ALLOWED: u64 = 15; + /// Zero eMode category is reserved for volatile heterogeneous assets + const EEMODE_CATEGORY_RESERVED: u64 = 16; + /// Invalid eMode category assignment to asset + const EINVALID_EMODE_CATEGORY_ASSIGNMENT: u64 = 17; + /// The liquidity of the reserve needs to be 0 + const ERESERVE_LIQUIDITY_NOT_ZERO: u64 = 18; + /// Invalid flashloan premium + const EFLASHLOAN_PREMIUM_INVALID: u64 = 19; + /// Invalid risk parameters for the reserve + const EINVALID_RESERVE_PARAMS: u64 = 20; + /// Invalid risk parameters for the eMode category + const EINVALID_EMODE_CATEGORY_PARAMS: u64 = 21; + /// Invalid bridge protocol fee + const EBRIDGE_PROTOCOL_FEE_INVALID: u64 = 22; + /// The caller of this function must be a pool + const ECALLER_MUST_BE_POOL: u64 = 23; + /// Invalid amount to mint + const EINVALID_MINT_AMOUNT: u64 = 24; + /// Invalid amount to burn + const EINVALID_BURN_AMOUNT: u64 = 25; + /// Amount must be greater than 0 + const EINVALID_AMOUNT: u64 = 26; + /// Action requires an active reserve + const ERESERVE_INACTIVE: u64 = 27; + /// Action cannot be performed because the reserve is frozen + const ERESERVE_FROZEN: u64 = 28; + /// Action cannot be performed because the reserve is paused + const ERESERVE_PAUSED: u64 = 29; + /// Borrowing is not enabled + const EBORROWING_NOT_ENABLED: u64 = 30; + /// User cannot withdraw more than the available balance + const ENOT_ENOUGH_AVAILABLE_USER_BALANCE: u64 = 32; + /// Invalid interest rate mode selected + const EINVALID_INTEREST_RATE_MODE_SELECTED: u64 = 33; + /// The collateral balance is 0 + const ECOLLATERAL_BALANCE_IS_ZERO: u64 = 34; + /// Health factor is lesser than the liquidation threshold + const EHEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD: u64 = 35; + /// There is not enough collateral to cover a new borrow + const ECOLLATERAL_CANNOT_COVER_NEW_BORROW: u64 = 36; + /// Collateral is (mostly) the same currency that is being borrowed + const ECOLLATERAL_SAME_AS_BORROWING_CURRENCY: u64 = 37; + /// For repayment of a specific type of debt, the user needs to have debt that type + const ENO_DEBT_OF_SELECTED_TYPE: u64 = 39; + /// To repay on behalf of a user an explicit amount to repay is needed + const ENO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF: u64 = 40; + /// User does not have outstanding variable rate debt on this reserve + const ENO_OUTSTANDING_VARIABLE_DEBT: u64 = 42; + /// The underlying balance needs to be greater than 0 + const EUNDERLYING_BALANCE_ZERO: u64 = 43; + /// Interest rate rebalance conditions were not met + const EINTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET: u64 = 44; + /// Health factor is not below the threshold + const EHEALTH_FACTOR_NOT_BELOW_THRESHOLD: u64 = 45; + /// The collateral chosen cannot be liquidated + const ECOLLATERAL_CANNOT_BE_LIQUIDATED: u64 = 46; + /// User did not borrow the specified currency + const ESPECIFIED_CURRENCY_NOT_BORROWED_BY_USER: u64 = 47; + /// Inconsistent flashloan parameters + const EINCONSISTENT_FLASHLOAN_PARAMS: u64 = 49; + /// Borrow cap is exceeded + const EBORROW_CAP_EXCEEDED: u64 = 50; + /// Supply cap is exceeded + const ESUPPLY_CAP_EXCEEDED: u64 = 51; + /// Unbacked mint cap is exceeded + const EUNBACKED_MINT_CAP_EXCEEDED: u64 = 52; + /// Debt ceiling is exceeded + const EDEBT_CEILING_EXCEEDED: u64 = 53; + /// Claimable rights over underlying not zero (aToken supply or accruedToTreasury) + const EUNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO: u64 = 54; + /// Variable debt supply is not zero + const EVARIABLE_DEBT_SUPPLY_NOT_ZERO: u64 = 56; + /// Ltv validation failed + const ELTV_VALIDATION_FAILED: u64 = 57; + /// Inconsistent eMode category + const EINCONSISTENT_EMODE_CATEGORY: u64 = 58; + /// Price oracle sentinel validation failed + const EPRICE_ORACLE_SENTINEL_CHECK_FAILED: u64 = 59; + /// Asset is not borrowable in isolation mode + const EASSET_NOT_BORROWABLE_IN_ISOLATION: u64 = 60; + /// Reserve has already been initialized + const ERESERVE_ALREADY_INITIALIZED: u64 = 61; + /// User is in isolation mode or ltv is zero + const EUSER_IN_ISOLATION_MODE_OR_LTV_ZERO: u64 = 62; + /// Invalid ltv parameter for the reserve + const EINVALID_LTV: u64 = 63; + /// Invalid liquidity threshold parameter for the reserve + const EINVALID_LIQ_THRESHOLD: u64 = 64; + /// Invalid liquidity bonus parameter for the reserve + const EINVALID_LIQ_BONUS: u64 = 65; + /// Invalid decimals parameter of the underlying asset of the reserve + const EINVALID_DECIMALS: u64 = 66; + /// Invalid reserve factor parameter for the reserve + const EINVALID_RESERVE_FACTOR: u64 = 67; + /// Invalid borrow cap for the reserve + const EINVALID_BORROW_CAP: u64 = 68; + /// Invalid supply cap for the reserve + const EINVALID_SUPPLY_CAP: u64 = 69; + /// Invalid liquidation protocol fee for the reserve + const EINVALID_LIQUIDATION_PROTOCOL_FEE: u64 = 70; + /// Invalid eMode category for the reserve + const EINVALID_EMODE_CATEGORY: u64 = 71; + /// Invalid unbacked mint cap for the reserve + const EINVALID_UNBACKED_MINT_CAP: u64 = 72; + /// Invalid debt ceiling for the reserve + const EINVALID_DEBT_CEILING: u64 = 73; + /// Invalid reserve index + const EINVALID_RESERVE_INDEX: u64 = 74; + /// ACL admin cannot be set to the zero address + const EACL_ADMIN_CANNOT_BE_ZERO: u64 = 75; + /// Array parameters that should be equal length are not + const EINCONSISTENT_PARAMS_LENGTH: u64 = 76; + /// Zero address not valid + const EZERO_ADDRESS_NOT_VALID: u64 = 77; + /// Invalid expiration + const EINVALID_EXPIRATION: u64 = 78; + /// Invalid signature + const EINVALID_SIGNATURE: u64 = 79; + /// Operation not supported + const EOPERATION_NOT_SUPPORTED: u64 = 80; + /// Debt ceiling is not zero + const EDEBT_CEILING_NOT_ZERO: u64 = 81; + /// Asset is not listed + const EASSET_NOT_LISTED: u64 = 82; + /// Invalid optimal usage ratio + const EINVALID_OPTIMAL_USAGE_RATIO: u64 = 83; + /// The underlying asset cannot be rescued + const EUNDERLYING_CANNOT_BE_RESCUED: u64 = 85; + /// Reserve has already been added to reserve list + const EADDRESSES_PROVIDER_ALREADY_ADDED: u64 = 86; + /// The token implementation pool address and the pool address provided by the initializing pool do not match + const EPOOL_ADDRESSES_DO_NOT_MATCH: u64 = 87; + + /// User is trying to borrow multiple assets including a siloed one + const ESILOED_BORROWING_VIOLATION: u64 = 89; + /// the total debt of the reserve needs to be 0 + const ERESERVE_DEBT_NOT_ZERO: u64 = 90; + /// FlashLoaning for this asset is disabled + const EFLASHLOAN_DISABLED: u64 = 91; + /// User is not listed + const EUSER_NOT_LISTED: u64 = 92; + + /// Mismatch of reserves count in storage + const ERESERVES_STORAGE_COUNT_MISMATCH: u64 = 93; + /// The person who signed must be consistent with on_behalf_of + const ESIGNER_AND_ON_BEHALF_OF_NO_SAME: u64 = 94; + /// Account does not exist + const EACCOUNT_DOES_NOT_EXIST: u64 = 95; + + /// Flashloan payer is different from the flashloan receiver + const EFLASHLOAN_PAYER_NOT_RECEIVER: u64 = 95; + + #[test] + fun test_get_ecaller_not_pool_admin() { + assert!(get_ecaller_not_pool_admin() == ECALLER_NOT_POOL_ADMIN, TEST_SUCCESS); + } + + #[test] + fun test_get_ecaller_not_emergency_admin() { + assert!( + get_ecaller_not_emergency_admin() == ECALLER_NOT_EMERGENCY_ADMIN, TEST_SUCCESS + ); + } + + #[test] + fun test_get_ecaller_not_pool_or_emergency_admin() { + assert!( + get_ecaller_not_pool_or_emergency_admin() == ECALLER_NOT_POOL_OR_EMERGENCY_ADMIN, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ecaller_not_risk_or_pool_admin() { + assert!( + get_ecaller_not_risk_or_pool_admin() == ECALLER_NOT_RISK_OR_POOL_ADMIN, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ecaller_not_asset_listing_or_pool_admin() { + assert!( + get_ecaller_not_asset_listing_or_pool_admin() + == ECALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ecaller_not_bridge() { + assert!(get_ecaller_not_bridge() == ECALLER_NOT_BRIDGE, TEST_SUCCESS); + } + + #[test] + fun test_get_eaddresses_provider_not_registered() { + assert!( + get_eaddresses_provider_not_registered() == EADDRESSES_PROVIDER_NOT_REGISTERED, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_einvalid_addresses_provider_id() { + assert!( + get_einvalid_addresses_provider_id() == EINVALID_ADDRESSES_PROVIDER_ID, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_enot_contract() { + assert!(get_enot_contract() == ENOT_CONTRACT, TEST_SUCCESS); + } + + #[test] + fun test_get_ecaller_not_pool_configurator() { + assert!( + get_ecaller_not_pool_configurator() == ECALLER_NOT_POOL_CONFIGURATOR, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ecaller_not_atoken() { + assert!(get_ecaller_not_atoken() == ECALLER_NOT_ATOKEN, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_addresses_provider() { + assert!( + get_einvalid_addresses_provider() == EINVALID_ADDRESSES_PROVIDER, TEST_SUCCESS + ); + } + + #[test] + fun test_get_einvalid_flashloan_executor_return() { + assert!( + get_einvalid_flashloan_executor_return() == EINVALID_FLASHLOAN_EXECUTOR_RETURN, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ereserve_already_added() { + assert!(get_ereserve_already_added() == ERESERVE_ALREADY_ADDED, TEST_SUCCESS); + } + + #[test] + fun test_get_ereserves_storage_count_mismatch() { + assert!( + get_ereserves_storage_count_mismatch() == ERESERVES_STORAGE_COUNT_MISMATCH, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eno_more_reserves_allowed() { + assert!( + get_eno_more_reserves_allowed() == ENO_MORE_RESERVES_ALLOWED, TEST_SUCCESS + ); + } + + #[test] + fun test_get_eemode_category_reserved() { + assert!(get_eemode_category_reserved() == EEMODE_CATEGORY_RESERVED, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_emode_category_assignment() { + assert!( + get_einvalid_emode_category_assignment() == EINVALID_EMODE_CATEGORY_ASSIGNMENT, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ereserve_liquidity_not_zero() { + assert!( + get_ereserve_liquidity_not_zero() == ERESERVE_LIQUIDITY_NOT_ZERO, TEST_SUCCESS + ); + } + + #[test] + fun test_get_eflashloan_premium_invalid() { + assert!( + get_eflashloan_premium_invalid() == EFLASHLOAN_PREMIUM_INVALID, TEST_SUCCESS + ); + } + + #[test] + fun test_get_einvalid_reserve_params() { + assert!(get_einvalid_reserve_params() == EINVALID_RESERVE_PARAMS, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_emode_category_params() { + assert!( + get_einvalid_emode_category_params() == EINVALID_EMODE_CATEGORY_PARAMS, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ebridge_protocol_fee_invalid() { + assert!( + get_ebridge_protocol_fee_invalid() == EBRIDGE_PROTOCOL_FEE_INVALID, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ecaller_must_be_pool() { + assert!(get_ecaller_must_be_pool() == ECALLER_MUST_BE_POOL, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_mint_amount() { + assert!(get_einvalid_mint_amount() == EINVALID_MINT_AMOUNT, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_burn_amount() { + assert!(get_einvalid_burn_amount() == EINVALID_BURN_AMOUNT, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_amount() { + assert!(get_einvalid_amount() == EINVALID_AMOUNT, TEST_SUCCESS); + } + + #[test] + fun test_get_ereserve_inactive() { + assert!(get_ereserve_inactive() == ERESERVE_INACTIVE, TEST_SUCCESS); + } + + #[test] + fun test_get_ereserve_frozen() { + assert!(get_ereserve_frozen() == ERESERVE_FROZEN, TEST_SUCCESS); + } + + #[test] + fun test_get_ereserve_paused() { + assert!(get_ereserve_paused() == ERESERVE_PAUSED, TEST_SUCCESS); + } + + #[test] + fun test_get_eborrowing_not_enabled() { + assert!(get_eborrowing_not_enabled() == EBORROWING_NOT_ENABLED, TEST_SUCCESS); + } + + #[test] + fun test_get_enot_enough_available_user_balance() { + assert!( + get_enot_enough_available_user_balance() == ENOT_ENOUGH_AVAILABLE_USER_BALANCE, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_einvalid_interest_rate_mode_selected() { + assert!( + get_einvalid_interest_rate_mode_selected() + == EINVALID_INTEREST_RATE_MODE_SELECTED, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ecollateral_balance_is_zero() { + assert!( + get_ecollateral_balance_is_zero() == ECOLLATERAL_BALANCE_IS_ZERO, TEST_SUCCESS + ); + } + + #[test] + fun test_get_ehealth_factor_lower_than_liquidation_threshold() { + assert!( + get_ehealth_factor_lower_than_liquidation_threshold() + == EHEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ecollateral_cannot_cover_new_borrow() { + assert!( + get_ecollateral_cannot_cover_new_borrow() == ECOLLATERAL_CANNOT_COVER_NEW_BORROW, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ecollateral_same_as_borrowing_currency() { + assert!( + get_ecollateral_same_as_borrowing_currency() + == ECOLLATERAL_SAME_AS_BORROWING_CURRENCY, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eno_debt_of_selected_type() { + assert!( + get_eno_debt_of_selected_type() == ENO_DEBT_OF_SELECTED_TYPE, TEST_SUCCESS + ); + } + + #[test] + fun test_get_eno_explicit_amount_to_repay_on_behalf() { + assert!( + get_eno_explicit_amount_to_repay_on_behalf() + == ENO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eno_outstanding_variable_debt() { + assert!( + get_eno_outstanding_variable_debt() == ENO_OUTSTANDING_VARIABLE_DEBT, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eunderlying_balance_zero() { + assert!(get_eunderlying_balance_zero() == EUNDERLYING_BALANCE_ZERO, TEST_SUCCESS); + } + + #[test] + fun test_get_einterest_rate_rebalance_conditions_not_met() { + assert!( + get_einterest_rate_rebalance_conditions_not_met() + == EINTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ehealth_factor_not_below_threshold() { + assert!( + get_ehealth_factor_not_below_threshold() == EHEALTH_FACTOR_NOT_BELOW_THRESHOLD, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ecollateral_cannot_be_liquidated() { + assert!( + get_ecollateral_cannot_be_liquidated() == ECOLLATERAL_CANNOT_BE_LIQUIDATED, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_especified_currency_not_borrowed_by_user() { + assert!( + get_especified_currency_not_borrowed_by_user() + == ESPECIFIED_CURRENCY_NOT_BORROWED_BY_USER, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_einconsistent_flashloan_params() { + assert!( + get_einconsistent_flashloan_params() == EINCONSISTENT_FLASHLOAN_PARAMS, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eborrow_cap_exceeded() { + assert!(get_eborrow_cap_exceeded() == EBORROW_CAP_EXCEEDED, TEST_SUCCESS); + } + + #[test] + fun test_get_esupply_cap_exceeded() { + assert!(get_esupply_cap_exceeded() == ESUPPLY_CAP_EXCEEDED, TEST_SUCCESS); + } + + #[test] + fun test_get_eunbacked_mint_cap_exceededd() { + assert!( + get_eunbacked_mint_cap_exceeded() == EUNBACKED_MINT_CAP_EXCEEDED, TEST_SUCCESS + ); + } + + #[test] + fun test_get_edebt_ceiling_exceeded() { + assert!(get_edebt_ceiling_exceeded() == EDEBT_CEILING_EXCEEDED, TEST_SUCCESS); + } + + #[test] + fun test_get_eunderlying_claimable_rights_not_zero() { + assert!( + get_eunderlying_claimable_rights_not_zero() + == EUNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_evariable_debt_supply_not_zero() { + assert!( + get_evariable_debt_supply_not_zero() == EVARIABLE_DEBT_SUPPLY_NOT_ZERO, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eltv_validation_failed() { + assert!(get_eltv_validation_failed() == ELTV_VALIDATION_FAILED, TEST_SUCCESS); + } + + #[test] + fun test_get_einconsistent_emode_category() { + assert!( + get_einconsistent_emode_category() == EINCONSISTENT_EMODE_CATEGORY, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eprice_oracle_sentinel_check_failed() { + assert!( + get_eprice_oracle_sentinel_check_failed() == EPRICE_ORACLE_SENTINEL_CHECK_FAILED, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_easset_not_borrowable_in_isolation() { + assert!( + get_easset_not_borrowable_in_isolation() == EASSET_NOT_BORROWABLE_IN_ISOLATION, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_ereserve_already_initialized() { + assert!( + get_ereserve_already_initialized() == ERESERVE_ALREADY_INITIALIZED, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_euser_in_isolation_mode_or_ltv_zero() { + assert!( + get_euser_in_isolation_mode_or_ltv_zero() == EUSER_IN_ISOLATION_MODE_OR_LTV_ZERO, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_einvalid_ltv() { + assert!(get_einvalid_ltv() == EINVALID_LTV, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_liq_threshold() { + assert!(get_einvalid_liq_threshold() == EINVALID_LIQ_THRESHOLD, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_decimals() { + assert!(get_einvalid_decimals() == EINVALID_DECIMALS, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_reserve_factor() { + assert!(get_einvalid_reserve_factor() == EINVALID_RESERVE_FACTOR, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_borrow_cap() { + assert!(get_einvalid_borrow_cap() == EINVALID_BORROW_CAP, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_supply_cap() { + assert!(get_einvalid_supply_cap() == EINVALID_SUPPLY_CAP, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_liquidation_protocol_fee() { + assert!( + get_einvalid_liquidation_protocol_fee() == EINVALID_LIQUIDATION_PROTOCOL_FEE, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_einvalid_emode_category() { + assert!(get_einvalid_emode_category() == EINVALID_EMODE_CATEGORY, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_unbacked_mint_cap() { + assert!( + get_einvalid_unbacked_mint_cap() == EINVALID_UNBACKED_MINT_CAP, TEST_SUCCESS + ); + } + + #[test] + fun test_get_einvalid_debt_ceiling() { + assert!(get_einvalid_debt_ceiling() == EINVALID_DEBT_CEILING, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_reserve_index() { + assert!(get_einvalid_reserve_index() == EINVALID_RESERVE_INDEX, TEST_SUCCESS); + } + + #[test] + fun test_get_eacl_admin_cannot_be_zero() { + assert!( + get_eacl_admin_cannot_be_zero() == EACL_ADMIN_CANNOT_BE_ZERO, TEST_SUCCESS + ); + } + + #[test] + fun test_get_einconsistent_params_length() { + assert!( + get_einconsistent_params_length() == EINCONSISTENT_PARAMS_LENGTH, TEST_SUCCESS + ); + } + + #[test] + fun test_get_ezero_address_not_valid() { + assert!(get_ezero_address_not_valid() == EZERO_ADDRESS_NOT_VALID, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_expiration() { + assert!(get_einvalid_expiration() == EINVALID_EXPIRATION, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_signature() { + assert!(get_einvalid_signature() == EINVALID_SIGNATURE, TEST_SUCCESS); + } + + #[test] + fun test_get_eoperation_not_supported() { + assert!(get_eoperation_not_supported() == EOPERATION_NOT_SUPPORTED, TEST_SUCCESS); + } + + #[test] + fun test_get_edebt_ceiling_not_zero() { + assert!(get_edebt_ceiling_not_zero() == EDEBT_CEILING_NOT_ZERO, TEST_SUCCESS); + } + + #[test] + fun test_get_easset_not_listed() { + assert!(get_easset_not_listed() == EASSET_NOT_LISTED, TEST_SUCCESS); + } + + #[test] + fun test_get_einvalid_optimal_usage_ratio() { + assert!( + get_einvalid_optimal_usage_ratio() == EINVALID_OPTIMAL_USAGE_RATIO, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eunderlying_cannot_be_rescued() { + assert!( + get_eunderlying_cannot_be_rescued() == EUNDERLYING_CANNOT_BE_RESCUED, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eaddresses_provider_already_added() { + assert!( + get_eaddresses_provider_already_added() == EADDRESSES_PROVIDER_ALREADY_ADDED, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_epool_addresses_do_not_match() { + assert!( + get_epool_addresses_do_not_match() == EPOOL_ADDRESSES_DO_NOT_MATCH, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_esiloed_borrowing_violation() { + assert!( + get_esiloed_borrowing_violation() == ESILOED_BORROWING_VIOLATION, TEST_SUCCESS + ); + } + + #[test] + fun test_get_ereserve_debt_not_zero() { + assert!(get_ereserve_debt_not_zero() == ERESERVE_DEBT_NOT_ZERO, TEST_SUCCESS); + } + + #[test] + fun test_get_eflashloan_disabled() { + assert!(get_eflashloan_disabled() == EFLASHLOAN_DISABLED, TEST_SUCCESS); + } + + #[test] + fun test_get_euser_not_listed() { + assert!(get_euser_not_listed() == EUSER_NOT_LISTED, TEST_SUCCESS); + } + + #[test] + fun test_get_esigner_and_on_behalf_of_no_same() { + assert!( + get_esigner_and_on_behalf_of_no_same() == ESIGNER_AND_ON_BEHALF_OF_NO_SAME, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_eaccount_does_not_exist() { + assert!(get_eaccount_does_not_exist() == EACCOUNT_DOES_NOT_EXIST, TEST_SUCCESS); + } + + #[test] + fun test_get_flashloan_payer_not_receiver() { + assert!( + get_flashloan_payer_not_receiver() == EFLASHLOAN_PAYER_NOT_RECEIVER, + TEST_SUCCESS, + ); + } + + #[test] + fun test_get_einvalid_liq_bonus() { + assert!(get_einvalid_liq_bonus() == EINVALID_LIQ_BONUS, TEST_SUCCESS); + } +} diff --git a/aave-core/aave-config/tests/reserve_config_tests.move b/aave-core/aave-config/tests/reserve_config_tests.move index cbd3195..49cc112 100644 --- a/aave-core/aave-config/tests/reserve_config_tests.move +++ b/aave-core/aave-config/tests/reserve_config_tests.move @@ -70,8 +70,14 @@ module aave_config::reserve_tests { fun check_params( reserve_config: &ReserveConfigurationMap, param_key: u256, param_val: u256 ) { - let (ltv, liquidation_threshold, liquidation_bonus, decimals, reserve_factor, - emode_category) = get_params(reserve_config); + let ( + ltv, + liquidation_threshold, + liquidation_bonus, + decimals, + reserve_factor, + emode_category + ) = get_params(reserve_config); if (param_key == ENUM_LTV) { assert!(ltv == param_val, SUCCESS); } else { @@ -361,11 +367,19 @@ module aave_config::reserve_tests { check_params(&reserve_config, ZERO, ZERO); assert!(get_liquidation_threshold(&reserve_config) == ZERO, SUCCESS); - set_liquidation_threshold(&mut reserve_config, get_max_valid_liquidation_threshold()); - check_params(&reserve_config, ENUM_LIQUIDATION_THRESHOLD, - get_max_valid_liquidation_threshold()); - assert!(get_liquidation_threshold(&reserve_config) == get_max_valid_liquidation_threshold(), - SUCCESS); + set_liquidation_threshold( + &mut reserve_config, get_max_valid_liquidation_threshold() + ); + check_params( + &reserve_config, + ENUM_LIQUIDATION_THRESHOLD, + get_max_valid_liquidation_threshold(), + ); + assert!( + get_liquidation_threshold(&reserve_config) + == get_max_valid_liquidation_threshold(), + SUCCESS, + ); set_liquidation_threshold(&mut reserve_config, ZERO); check_params(&reserve_config, ENUM_LIQUIDATION_THRESHOLD, ZERO); @@ -379,8 +393,9 @@ module aave_config::reserve_tests { let reserve_config = init(); assert!(get_liquidation_threshold(&reserve_config) == ZERO, SUCCESS); - set_liquidation_threshold(&mut reserve_config, get_max_valid_liquidation_threshold() - + 1); + set_liquidation_threshold( + &mut reserve_config, get_max_valid_liquidation_threshold() + 1 + ); assert!(get_liquidation_threshold(&reserve_config) == ZERO, SUCCESS); } @@ -418,8 +433,9 @@ module aave_config::reserve_tests { assert!(get_emode_category(&reserve_config) == ZERO, SUCCESS); set_emode_category(&mut reserve_config, get_max_valid_emode_category()); - assert!(get_emode_category(&reserve_config) == get_max_valid_emode_category(), - SUCCESS); + assert!( + get_emode_category(&reserve_config) == get_max_valid_emode_category(), SUCCESS + ); set_emode_category(&mut reserve_config, ZERO); assert!(get_emode_category(&reserve_config) == ZERO, SUCCESS); @@ -442,10 +458,14 @@ module aave_config::reserve_tests { let reserve_config = init(); assert!(get_liquidation_protocol_fee(&reserve_config) == ZERO, SUCCESS); - set_liquidation_protocol_fee(&mut reserve_config, - get_max_valid_liquidation_protocol_fee()); - assert!(get_liquidation_protocol_fee(&reserve_config) == get_max_valid_liquidation_protocol_fee(), - SUCCESS); + set_liquidation_protocol_fee( + &mut reserve_config, get_max_valid_liquidation_protocol_fee() + ); + assert!( + get_liquidation_protocol_fee(&reserve_config) + == get_max_valid_liquidation_protocol_fee(), + SUCCESS, + ); } #[test] @@ -455,8 +475,9 @@ module aave_config::reserve_tests { let reserve_config = init(); assert!(get_liquidation_protocol_fee(&reserve_config) == ZERO, SUCCESS); - set_liquidation_protocol_fee(&mut reserve_config, - get_max_valid_liquidation_protocol_fee() + 1); + set_liquidation_protocol_fee( + &mut reserve_config, get_max_valid_liquidation_protocol_fee() + 1 + ); assert!(get_liquidation_protocol_fee(&reserve_config) == ZERO, SUCCESS); } } diff --git a/aave-core/aave-config/tests/user_config_tests.move b/aave-core/aave-config/tests/user_config_tests.move index 9de9e9a..c44ee68 100644 --- a/aave-core/aave-config/tests/user_config_tests.move +++ b/aave-core/aave-config/tests/user_config_tests.move @@ -1,28 +1,27 @@ #[test_only] module aave_config::user_tests { + use aave_config::helper::Self; use aave_config::user::{ - set_using_as_collateral, - is_borrowing_any, - is_using_as_collateral_or_borrowing, - set_borrowing, + get_health_factor_liquidation_threshold, + get_health_factor_liquidation_threshold_for_testing, + get_isolated_collateral_supplier_role, + get_isolated_collateral_supplier_role_for_testing, + get_minimum_health_factor_liquidation_threshold, + get_minimum_health_factor_liquidation_threshold_for_testing, + get_user_config_map, is_borrowing, + is_borrowing_any, is_borrowing_one, + is_empty, is_using_as_collateral, is_using_as_collateral_any, is_using_as_collateral_one, - get_rebalance_up_liquidity_rate_threshold, - get_minimum_health_factor_liquidation_threshold, - get_health_factor_liquidation_threshold, - get_isolated_collateral_supplier_role, + is_using_as_collateral_or_borrowing, + set_borrowing, + set_using_as_collateral, test_init_module, - is_empty, - get_user_config_map, - get_rebalance_up_liquidity_rate_threshold_for_testing, - get_minimum_health_factor_liquidation_threshold_for_testing, - get_health_factor_liquidation_threshold_for_testing, - get_isolated_collateral_supplier_role_for_testing, + get_first_asset_id_by_mask, }; - use aave_config::helper::{Self}; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; @@ -30,14 +29,21 @@ module aave_config::user_tests { #[test(admin = @aave_config)] fun test_user_config(admin: &signer) { test_init_module(admin); - assert!(get_rebalance_up_liquidity_rate_threshold() == get_rebalance_up_liquidity_rate_threshold_for_testing(), - TEST_SUCCESS); - assert!(get_minimum_health_factor_liquidation_threshold() == get_minimum_health_factor_liquidation_threshold_for_testing(), - TEST_SUCCESS); - assert!(get_health_factor_liquidation_threshold() == get_health_factor_liquidation_threshold_for_testing(), - TEST_SUCCESS); - assert!(get_isolated_collateral_supplier_role() == get_isolated_collateral_supplier_role_for_testing(), - TEST_SUCCESS); + assert!( + get_minimum_health_factor_liquidation_threshold() + == get_minimum_health_factor_liquidation_threshold_for_testing(), + TEST_SUCCESS, + ); + assert!( + get_health_factor_liquidation_threshold() + == get_health_factor_liquidation_threshold_for_testing(), + TEST_SUCCESS, + ); + assert!( + get_isolated_collateral_supplier_role() + == get_isolated_collateral_supplier_role_for_testing(), + TEST_SUCCESS, + ); // test default values let user_config_map = get_user_config_map(); assert!(is_empty(&user_config_map), TEST_SUCCESS); @@ -50,15 +56,29 @@ module aave_config::user_tests { assert!(is_borrowing(&mut user_config_map, reserve_index), TEST_SUCCESS); assert!(is_borrowing_any(&mut user_config_map), TEST_SUCCESS); assert!(is_borrowing_one(&mut user_config_map), TEST_SUCCESS); - assert!(is_using_as_collateral_or_borrowing(&mut user_config_map, reserve_index), - TEST_SUCCESS); + assert!( + is_using_as_collateral_or_borrowing(&mut user_config_map, reserve_index), + TEST_SUCCESS, + ); // test collateral set_using_as_collateral(&mut user_config_map, reserve_index, true); assert!(is_using_as_collateral(&user_config_map, reserve_index), TEST_SUCCESS); assert!(is_using_as_collateral_any(&user_config_map), TEST_SUCCESS); assert!(is_using_as_collateral_one(&user_config_map), TEST_SUCCESS); - assert!(is_using_as_collateral_or_borrowing(&user_config_map, reserve_index), - TEST_SUCCESS); + assert!( + is_using_as_collateral_or_borrowing(&user_config_map, reserve_index), + TEST_SUCCESS, + ); + } + + #[test(admin = @aave_config)] + fun test_get_first_asset_id_by_mask(admin: &signer) { + test_init_module(admin); + let user_config_map = get_user_config_map(); + let reserve_index: u256 = 1; + set_using_as_collateral(&mut user_config_map, reserve_index, true); + let mask = 1 << (((reserve_index << 1) + 1) as u8); + assert!(get_first_asset_id_by_mask(&user_config_map, mask) == 1, TEST_SUCCESS); } #[test] diff --git a/aave-core/aave-large-packages/Move.toml b/aave-core/aave-large-packages/Move.toml index ee715da..f7449a7 100644 --- a/aave-core/aave-large-packages/Move.toml +++ b/aave-core/aave-large-packages/Move.toml @@ -10,6 +10,6 @@ aave_large_packages = "_" [dev-addresses] [dependencies] -AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "main" } +AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "mainnet" } [dev-dependencies] \ No newline at end of file diff --git a/aave-core/aave-large-packages/sources/large_packages.move b/aave-core/aave-large-packages/sources/large_packages.move index 5a75dcb..611ca16 100644 --- a/aave-core/aave-large-packages/sources/large_packages.move +++ b/aave-core/aave-large-packages/sources/large_packages.move @@ -45,7 +45,8 @@ module aave_large_packages::large_packages { code_indices: vector, code_chunks: vector>, ) acquires StagingArea { - let staging_area = stage_code_chunk_internal(owner, metadata_chunk, code_indices, code_chunks); + let staging_area = + stage_code_chunk_internal(owner, metadata_chunk, code_indices, code_chunks); publish_to_account(owner, staging_area); cleanup_staging_area(owner); } @@ -56,7 +57,8 @@ module aave_large_packages::large_packages { code_indices: vector, code_chunks: vector>, ) acquires StagingArea { - let staging_area = stage_code_chunk_internal(owner, metadata_chunk, code_indices, code_chunks); + let staging_area = + stage_code_chunk_internal(owner, metadata_chunk, code_indices, code_chunks); publish_to_object(owner, staging_area); cleanup_staging_area(owner); } @@ -68,7 +70,8 @@ module aave_large_packages::large_packages { code_chunks: vector>, code_object: Option>, ) acquires StagingArea { - let staging_area = stage_code_chunk_internal(owner, metadata_chunk, code_indices, code_chunks); + let staging_area = + stage_code_chunk_internal(owner, metadata_chunk, code_indices, code_chunks); upgrade_object_code(owner, staging_area, option::extract(&mut code_object)); cleanup_staging_area(owner); } @@ -87,11 +90,14 @@ module aave_large_packages::large_packages { let owner_address = signer::address_of(owner); if (!exists(owner_address)) { - move_to(owner, StagingArea { - metadata_serialized: vector[], - code: smart_table::new(), - last_module_idx: 0, - }); + move_to( + owner, + StagingArea { + metadata_serialized: vector[], + code: smart_table::new(), + last_module_idx: 0, + }, + ); }; let staging_area = borrow_global_mut(owner_address); @@ -106,7 +112,9 @@ module aave_large_packages::large_packages { let idx = (*vector::borrow(&code_indices, i) as u64); if (smart_table::contains(&staging_area.code, idx)) { - vector::append(smart_table::borrow_mut(&mut staging_area.code, idx), inner_code); + vector::append( + smart_table::borrow_mut(&mut staging_area.code, idx), inner_code + ); } else { smart_table::add(&mut staging_area.code, idx, inner_code); if (idx > staging_area.last_module_idx) { @@ -120,16 +128,14 @@ module aave_large_packages::large_packages { } inline fun publish_to_account( - publisher: &signer, - staging_area: &mut StagingArea, + publisher: &signer, staging_area: &mut StagingArea, ) { let code = assemble_module_code(staging_area); code::publish_package_txn(publisher, staging_area.metadata_serialized, code); } inline fun publish_to_object( - publisher: &signer, - staging_area: &mut StagingArea, + publisher: &signer, staging_area: &mut StagingArea, ) { let code = assemble_module_code(staging_area); object_code_deployment::publish(publisher, staging_area.metadata_serialized, code); @@ -141,31 +147,28 @@ module aave_large_packages::large_packages { code_object: Object, ) { let code = assemble_module_code(staging_area); - object_code_deployment::upgrade(publisher, staging_area.metadata_serialized, code, code_object); + object_code_deployment::upgrade( + publisher, + staging_area.metadata_serialized, + code, + code_object, + ); } - inline fun assemble_module_code( - staging_area: &mut StagingArea, - ): vector> { + inline fun assemble_module_code(staging_area: &mut StagingArea,): vector> { let last_module_idx = staging_area.last_module_idx; let code: vector> = vector[]; let i: u64 = 0; while (i <= last_module_idx) { - vector::push_back( - &mut code, - *smart_table::borrow(&staging_area.code, i) - ); + vector::push_back(&mut code, *smart_table::borrow(&staging_area.code, i)); i = i + 1; }; code } public entry fun cleanup_staging_area(owner: &signer) acquires StagingArea { - let StagingArea { - metadata_serialized: _, - code, - last_module_idx: _, - } = move_from(signer::address_of(owner)); + let StagingArea { metadata_serialized: _, code, last_module_idx: _, } = + move_from(signer::address_of(owner)); smart_table::destroy(code); } } diff --git a/aave-core/aave-math/Move.toml b/aave-core/aave-math/Move.toml index 1903a32..6481278 100644 --- a/aave-core/aave-math/Move.toml +++ b/aave-core/aave-math/Move.toml @@ -10,6 +10,6 @@ aave_math = '_' [dev-addresses] [dependencies] -AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "main" } +AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "mainnet" } [dev-dependencies] diff --git a/aave-core/aave-math/doc/math_utils.md b/aave-core/aave-math/doc/math_utils.md index ae5c9f8..a6872db 100644 --- a/aave-core/aave-math/doc/math_utils.md +++ b/aave-core/aave-math/doc/math_utils.md @@ -1,23 +1,23 @@ - + -# Module `0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils` +# Module `0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils` - [Constants](#@Constants_0) -- [Function `u256_max`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_math_utils_u256_max) -- [Function `calculate_linear_interest`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_math_utils_calculate_linear_interest) -- [Function `calculate_compounded_interest`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_math_utils_calculate_compounded_interest) -- [Function `calculate_compounded_interest_now`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_math_utils_calculate_compounded_interest_now) -- [Function `get_percentage_factor`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_math_utils_get_percentage_factor) -- [Function `percent_mul`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_math_utils_percent_mul) -- [Function `percent_div`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_math_utils_percent_div) -- [Function `pow`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_math_utils_pow) +- [Function `u256_max`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_math_utils_u256_max) +- [Function `calculate_linear_interest`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_math_utils_calculate_linear_interest) +- [Function `calculate_compounded_interest`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_math_utils_calculate_compounded_interest) +- [Function `calculate_compounded_interest_now`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_math_utils_calculate_compounded_interest_now) +- [Function `get_percentage_factor`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_math_utils_get_percentage_factor) +- [Function `percent_mul`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_math_utils_percent_mul) +- [Function `percent_div`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_math_utils_percent_div) +- [Function `pow`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_math_utils_pow)
use 0x1::timestamp;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
 
@@ -27,77 +27,77 @@ ## Constants - + Cannot divide by zero -
const EDIVISION_BY_ZERO: u64 = 2;
+
const EDIVISION_BY_ZERO: u64 = 2;
 
- + Calculation results in overflow -
const EOVERFLOW: u64 = 1;
+
const EOVERFLOW: u64 = 1;
 
- + -
const U256_MAX: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
+
const U256_MAX: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
 
- + Half percentage factor (50.00%) -
const HALF_PERCENTAGE_FACTOR: u256 = 5000;
+
const HALF_PERCENTAGE_FACTOR: u256 = 5000;
 
- + Maximum percentage factor (100.00%) -
const PERCENTAGE_FACTOR: u256 = 10000;
+
const PERCENTAGE_FACTOR: u256 = 10000;
 
- + @dev Ignoring leap years -
const SECONDS_PER_YEAR: u256 = 31536000;
+
const SECONDS_PER_YEAR: u256 = 31536000;
 
- + ## Function `u256_max` -
public fun u256_max(): u256
+
public fun u256_max(): u256
 
- + ## Function `calculate_linear_interest` @@ -107,12 +107,12 @@ Maximum percentage factor (100.00%) @return The interest rate linearly accumulated during the timeDelta, in ray -
public fun calculate_linear_interest(rate: u256, last_update_timestamp: u64): u256
+
public fun calculate_linear_interest(rate: u256, last_update_timestamp: u64): u256
 
- + ## Function `calculate_compounded_interest` @@ -130,12 +130,12 @@ error per different time periods @return The interest rate compounded during the timeDelta, in ray -
public fun calculate_compounded_interest(rate: u256, last_update_timestamp: u64, current_timestamp: u64): u256
+
public fun calculate_compounded_interest(rate: u256, last_update_timestamp: u64, current_timestamp: u64): u256
 
- + ## Function `calculate_compounded_interest_now` @@ -145,23 +145,23 @@ error per different time periods @return The interest rate compounded between lastUpdateTimestamp and current block timestamp, in ray -
public fun calculate_compounded_interest_now(rate: u256, last_update_timestamp: u64): u256
+
public fun calculate_compounded_interest_now(rate: u256, last_update_timestamp: u64): u256
 
- + ## Function `get_percentage_factor` -
public fun get_percentage_factor(): u256
+
public fun get_percentage_factor(): u256
 
- + ## Function `percent_mul` @@ -171,12 +171,12 @@ error per different time periods @return result value percentmul percentage -
public fun percent_mul(value: u256, percentage: u256): u256
+
public fun percent_mul(value: u256, percentage: u256): u256
 
- + ## Function `percent_div` @@ -186,16 +186,16 @@ error per different time periods @return result value percentdiv percentage -
public fun percent_div(value: u256, percentage: u256): u256
+
public fun percent_div(value: u256, percentage: u256): u256
 
- + ## Function `pow` -
public fun pow(base: u256, exponent: u256): u256
+
public fun pow(base: u256, exponent: u256): u256
 
diff --git a/aave-core/aave-math/doc/wad_ray_math.md b/aave-core/aave-math/doc/wad_ray_math.md index 03e8318..365e1be 100644 --- a/aave-core/aave-math/doc/wad_ray_math.md +++ b/aave-core/aave-math/doc/wad_ray_math.md @@ -1,7 +1,7 @@ - + -# Module `0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math` +# Module `0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math` @title WadRayMath library @author Aave @@ -12,16 +12,16 @@ with 27 digits of precision) - [Constants](#@Constants_0) -- [Function `wad`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_wad) -- [Function `half_wad`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_half_wad) -- [Function `ray`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_ray) -- [Function `half_ray`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_half_ray) -- [Function `wad_mul`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_wad_mul) -- [Function `wad_div`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_wad_div) -- [Function `ray_mul`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_ray_mul) -- [Function `ray_div`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_ray_div) -- [Function `ray_to_wad`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_ray_to_wad) -- [Function `wad_to_ray`](#0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77_wad_ray_math_wad_to_ray) +- [Function `wad`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_wad) +- [Function `half_wad`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_half_wad) +- [Function `ray`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_ray) +- [Function `half_ray`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_half_ray) +- [Function `wad_mul`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_wad_mul) +- [Function `wad_div`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_wad_div) +- [Function `ray_mul`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_ray_mul) +- [Function `ray_div`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_ray_div) +- [Function `ray_to_wad`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_ray_to_wad) +- [Function `wad_to_ray`](#0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c_wad_ray_math_wad_to_ray)
@@ -33,125 +33,125 @@ with 27 digits of precision) ## Constants - + Cannot divide by 0 -
const EDIVISION_BY_ZERO: u64 = 2;
+
const EDIVISION_BY_ZERO: u64 = 2;
 
- + Overflow resulting from a calculation -
const EOVERFLOW: u64 = 1;
+
const EOVERFLOW: u64 = 1;
 
- + -
const HALF_RAY: u256 = 500000000000000000000000000;
+
const HALF_RAY: u256 = 500000000000000000000000000;
 
- + -
const HALF_WAD: u256 = 500000000000000000;
+
const HALF_WAD: u256 = 500000000000000000;
 
- + -
const RAY: u256 = 1000000000000000000000000000;
+
const RAY: u256 = 1000000000000000000000000000;
 
- + -
const U256_MAX: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
+
const U256_MAX: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
 
- + -
const WAD: u256 = 1000000000000000000;
+
const WAD: u256 = 1000000000000000000;
 
- + -
const WAD_RAY_RATIO: u256 = 1000000000;
+
const WAD_RAY_RATIO: u256 = 1000000000;
 
- + ## Function `wad` -
public fun wad(): u256
+
public fun wad(): u256
 
- + ## Function `half_wad` -
public fun half_wad(): u256
+
public fun half_wad(): u256
 
- + ## Function `ray` -
public fun ray(): u256
+
public fun ray(): u256
 
- + ## Function `half_ray` -
public fun half_ray(): u256
+
public fun half_ray(): u256
 
- + ## Function `wad_mul` @@ -161,12 +161,12 @@ Overflow resulting from a calculation @return c = a*b, in wad -
public fun wad_mul(a: u256, b: u256): u256
+
public fun wad_mul(a: u256, b: u256): u256
 
- + ## Function `wad_div` @@ -176,12 +176,12 @@ Overflow resulting from a calculation @return c = a/b, in wad -
public fun wad_div(a: u256, b: u256): u256
+
public fun wad_div(a: u256, b: u256): u256
 
- + ## Function `ray_mul` @@ -191,12 +191,12 @@ Overflow resulting from a calculation @return c = a raymul b -
public fun ray_mul(a: u256, b: u256): u256
+
public fun ray_mul(a: u256, b: u256): u256
 
- + ## Function `ray_div` @@ -206,12 +206,12 @@ Overflow resulting from a calculation @return c = a raydiv b -
public fun ray_div(a: u256, b: u256): u256
+
public fun ray_div(a: u256, b: u256): u256
 
- + ## Function `ray_to_wad` @@ -220,12 +220,12 @@ Overflow resulting from a calculation @return b = a converted to wad, rounded half up to the nearest wad -
public fun ray_to_wad(a: u256): u256
+
public fun ray_to_wad(a: u256): u256
 
- + ## Function `wad_to_ray` @@ -234,5 +234,5 @@ Overflow resulting from a calculation @return b = a converted in ray -
public fun wad_to_ray(a: u256): u256
+
public fun wad_to_ray(a: u256): u256
 
diff --git a/aave-core/aave-math/sources/math_utils.move b/aave-core/aave-math/sources/math_utils.move index b6c020c..fcf695b 100644 --- a/aave-core/aave-math/sources/math_utils.move +++ b/aave-core/aave-math/sources/math_utils.move @@ -74,8 +74,10 @@ module aave_math::math_utils { let exp_minus_one = exp - 1; let exp_minus_two = if (exp > 2) exp - 2 else 0; - let base_power_two = wad_ray_math::ray_mul(rate, rate) / (SECONDS_PER_YEAR * SECONDS_PER_YEAR); - let base_power_three = wad_ray_math::ray_mul(base_power_two, rate) / SECONDS_PER_YEAR; + let base_power_two = + wad_ray_math::ray_mul(rate, rate) / (SECONDS_PER_YEAR * SECONDS_PER_YEAR); + let base_power_three = + wad_ray_math::ray_mul(base_power_two, rate) / SECONDS_PER_YEAR; let second_term = (exp * exp_minus_one * base_power_two) / 2; let third_term = (exp * exp_minus_one * exp_minus_two * base_power_three) / 6; @@ -89,7 +91,9 @@ module aave_math::math_utils { public fun calculate_compounded_interest_now( rate: u256, last_update_timestamp: u64 ): u256 { - calculate_compounded_interest(rate, last_update_timestamp, timestamp::now_seconds()) + calculate_compounded_interest( + rate, last_update_timestamp, timestamp::now_seconds() + ) } public fun get_percentage_factor(): u256 { @@ -119,7 +123,10 @@ module aave_math::math_utils { /// @return result value percentdiv percentage public fun percent_div(value: u256, percentage: u256): u256 { assert!(percentage > 0, EDIVISION_BY_ZERO); - assert!(value <= (U256_MAX - HALF_PERCENTAGE_FACTOR) / PERCENTAGE_FACTOR, EOVERFLOW); + assert!( + value <= (U256_MAX - HALF_PERCENTAGE_FACTOR) / PERCENTAGE_FACTOR, + EOVERFLOW, + ); (value * PERCENTAGE_FACTOR + percentage / 2) / percentage } diff --git a/aave-core/aave-math/tests/math_utils_tests.move b/aave-core/aave-math/tests/math_utils_tests.move index 25754e1..f31577e 100644 --- a/aave-core/aave-math/tests/math_utils_tests.move +++ b/aave-core/aave-math/tests/math_utils_tests.move @@ -1,6 +1,9 @@ #[test_only] module aave_math::math_utils_tests { - use aptos_framework::timestamp::{set_time_has_started_for_testing, fast_forward_seconds}; + use aptos_framework::timestamp::{ + set_time_has_started_for_testing, + fast_forward_seconds + }; use aave_math::wad_ray_math::ray; use aptos_framework::timestamp; use aave_math::math_utils::{ @@ -34,7 +37,9 @@ module aave_math::math_utils_tests { #[test] fun test_getters() { - assert!(get_percentage_factor() == get_percentage_factor_for_testing(), TEST_SUCCESS); + assert!( + get_percentage_factor() == get_percentage_factor_for_testing(), TEST_SUCCESS + ); assert!(u256_max() == get_u256_max_for_testing(), TEST_SUCCESS); } @@ -49,10 +54,12 @@ module aave_math::math_utils_tests { let ts_one_hour_ago = timestamp::now_seconds() - one_hour_in_secs; // compute the interest rate let interest_rate_per_year = ray(); // ray per year - let lin_interest_rate_increase = calculate_linear_interest(interest_rate_per_year, - ts_one_hour_ago); + let lin_interest_rate_increase = + calculate_linear_interest(interest_rate_per_year, ts_one_hour_ago); // verification - let percentage_increase = (interest_rate_per_year * (one_hour_in_secs as u256)) / get_seconds_per_year_for_testing(); + let percentage_increase = + (interest_rate_per_year * (one_hour_in_secs as u256)) + / get_seconds_per_year_for_testing(); let increased_interest_rate = interest_rate_per_year + percentage_increase; assert!(increased_interest_rate == lin_interest_rate_increase, TEST_SUCCESS); } @@ -68,12 +75,14 @@ module aave_math::math_utils_tests { let ts_one_hour_ago = timestamp::now_seconds() - one_hour_in_secs; // compute the interest rate let interest_rate_per_year = ray(); // ray per year - let compunded_interest_rate_increase = calculate_compounded_interest_now( - interest_rate_per_year, ts_one_hour_ago); - let lin_interest_rate_increase = calculate_linear_interest(interest_rate_per_year, - ts_one_hour_ago); + let compunded_interest_rate_increase = + calculate_compounded_interest_now(interest_rate_per_year, ts_one_hour_ago); + let lin_interest_rate_increase = + calculate_linear_interest(interest_rate_per_year, ts_one_hour_ago); // test that the compounded int. rate is indeed higher than the linear - assert!(compunded_interest_rate_increase > lin_interest_rate_increase, TEST_SUCCESS); + assert!( + compunded_interest_rate_increase > lin_interest_rate_increase, TEST_SUCCESS + ); } #[test] @@ -91,8 +100,9 @@ module aave_math::math_utils_tests { #[expected_failure(abort_code = 1, location = aave_math::math_utils)] fun test_percent_mul_overflow() { let percentage = get_percentage_factor_for_testing() / 5; - let value = (get_u256_max_for_testing() - get_half_percentage_factor_for_testing()) - / percentage + 1; + let value = + (get_u256_max_for_testing() - get_half_percentage_factor_for_testing()) + / percentage + 1; percent_mul(value, percentage); } @@ -101,16 +111,19 @@ module aave_math::math_utils_tests { let value = 50; let percentage = get_percentage_factor_for_testing() / 5; let percentage_of_value = percent_div(value, percentage); - assert!(percentage_of_value == value * get_percentage_factor_for_testing() / percentage, - TEST_SUCCESS); + assert!( + percentage_of_value == value * get_percentage_factor_for_testing() / percentage, + TEST_SUCCESS, + ); } #[test] #[expected_failure(abort_code = 1, location = aave_math::math_utils)] fun test_percent_div_overflow() { let percentage = get_percentage_factor_for_testing() / 5; - let value = (get_u256_max_for_testing() - get_half_percentage_factor_for_testing()) - / get_percentage_factor_for_testing() + 1; + let value = + (get_u256_max_for_testing() - get_half_percentage_factor_for_testing()) + / get_percentage_factor_for_testing() + 1; percent_div(value, percentage); } diff --git a/aave-core/aave-math/tests/wad_ray_math_tests.move b/aave-core/aave-math/tests/wad_ray_math_tests.move index 22411f1..ed07b86 100644 --- a/aave-core/aave-math/tests/wad_ray_math_tests.move +++ b/aave-core/aave-math/tests/wad_ray_math_tests.move @@ -131,8 +131,10 @@ module aave_math::wad_ray_math_tests { let too_large = get_u256_max_for_testing() - (get_wad_ray_ratio_for_testing() / 2) + 1; let x = ray_to_wad(too_large); - assert!(x == 115792089237316195423570985008687907853269984665640564039457584007913, - TEST_SUCCESS); + assert!( + x == 115792089237316195423570985008687907853269984665640564039457584007913, + TEST_SUCCESS, + ); } #[test] diff --git a/aave-core/aave-mock-oracle/Move.toml b/aave-core/aave-mock-oracle/Move.toml index 6853060..09a69db 100644 --- a/aave-core/aave-mock-oracle/Move.toml +++ b/aave-core/aave-mock-oracle/Move.toml @@ -8,7 +8,7 @@ authors = [] aave_mock_oracle = "_" [dependencies] -AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "main" } +AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "mainnet" } AaveConfig = { local = "../aave-config" } AaveAcl = { local = "../aave-acl" } diff --git a/aave-core/aave-mock-oracle/doc/oracle.md b/aave-core/aave-mock-oracle/doc/oracle.md index 0470044..e92d4b4 100644 --- a/aave-core/aave-mock-oracle/doc/oracle.md +++ b/aave-core/aave-mock-oracle/doc/oracle.md @@ -1,69 +1,69 @@ - + -# Module `0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle` +# Module `0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle` -- [Struct `OracleEvent`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_OracleEvent) -- [Resource `AssetPriceList`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_AssetPriceList) -- [Resource `RewardOracle`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_RewardOracle) +- [Struct `OracleEvent`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_OracleEvent) +- [Resource `AssetPriceList`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_AssetPriceList) +- [Resource `RewardOracle`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_RewardOracle) - [Constants](#@Constants_0) -- [Function `create_reward_oracle`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_create_reward_oracle) -- [Function `decimals`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_decimals) -- [Function `latest_answer`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_latest_answer) -- [Function `latest_timestamp`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_latest_timestamp) -- [Function `latest_round`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_latest_round) -- [Function `get_answer`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_get_answer) -- [Function `get_timestamp`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_get_timestamp) -- [Function `base_currency_unit`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_base_currency_unit) -- [Function `get_asset_price`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_get_asset_price) -- [Function `get_base_currency_unit`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_get_base_currency_unit) -- [Function `set_asset_price`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_set_asset_price) -- [Function `batch_set_asset_price`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_batch_set_asset_price) -- [Function `update_asset_price`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_update_asset_price) -- [Function `remove_asset_price`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_remove_asset_price) +- [Function `create_reward_oracle`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_create_reward_oracle) +- [Function `decimals`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_decimals) +- [Function `latest_answer`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_latest_answer) +- [Function `latest_timestamp`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_latest_timestamp) +- [Function `latest_round`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_latest_round) +- [Function `get_answer`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_get_answer) +- [Function `get_timestamp`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_get_timestamp) +- [Function `base_currency_unit`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_base_currency_unit) +- [Function `get_asset_price`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_get_asset_price) +- [Function `get_base_currency_unit`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_get_base_currency_unit) +- [Function `set_asset_price`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_set_asset_price) +- [Function `batch_set_asset_price`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_batch_set_asset_price) +- [Function `update_asset_price`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_update_asset_price) +- [Function `remove_asset_price`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_remove_asset_price)
use 0x1::event;
 use 0x1::option;
 use 0x1::signer;
 use 0x1::simple_map;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle_sentinel;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle_sentinel;
 
- + ## Struct `OracleEvent`
#[event]
-struct OracleEvent has drop, store
+struct OracleEvent has drop, store
 
- + ## Resource `AssetPriceList` -
struct AssetPriceList has key
+
struct AssetPriceList has key
 
- + ## Resource `RewardOracle` -
struct RewardOracle has copy, drop, store, key
+
struct RewardOracle has copy, drop, store, key
 
@@ -73,182 +73,182 @@ ## Constants - + -
const E_ORACLE_NOT_ADMIN: u64 = 1;
+
const E_ORACLE_NOT_ADMIN: u64 = 1;
 
- + -
const E_ASSET_ALREADY_EXISTS: u64 = 2;
+
const E_ASSET_ALREADY_EXISTS: u64 = 2;
 
- + -
const E_ASSET_NOT_EXISTS: u64 = 3;
+
const E_ASSET_NOT_EXISTS: u64 = 3;
 
- + ## Function `create_reward_oracle` -
public fun create_reward_oracle(id: u256): oracle::RewardOracle
+
public fun create_reward_oracle(id: u256): oracle::RewardOracle
 
- + ## Function `decimals` -
public fun decimals(_reward_oracle: oracle::RewardOracle): u8
+
public fun decimals(_reward_oracle: oracle::RewardOracle): u8
 
- + ## Function `latest_answer` -
public fun latest_answer(_reward_oracle: oracle::RewardOracle): u256
+
public fun latest_answer(_reward_oracle: oracle::RewardOracle): u256
 
- + ## Function `latest_timestamp` -
public fun latest_timestamp(_reward_oracle: oracle::RewardOracle): u256
+
public fun latest_timestamp(_reward_oracle: oracle::RewardOracle): u256
 
- + ## Function `latest_round` -
public fun latest_round(_reward_oracle: oracle::RewardOracle): u256
+
public fun latest_round(_reward_oracle: oracle::RewardOracle): u256
 
- + ## Function `get_answer` -
public fun get_answer(_reward_oracle: oracle::RewardOracle, _round_id: u256): u256
+
public fun get_answer(_reward_oracle: oracle::RewardOracle, _round_id: u256): u256
 
- + ## Function `get_timestamp` -
public fun get_timestamp(_reward_oracle: oracle::RewardOracle, _round_id: u256): u256
+
public fun get_timestamp(_reward_oracle: oracle::RewardOracle, _round_id: u256): u256
 
- + ## Function `base_currency_unit` -
public fun base_currency_unit(_reward_oracle: oracle::RewardOracle, _round_id: u256): u64
+
public fun base_currency_unit(_reward_oracle: oracle::RewardOracle, _round_id: u256): u64
 
- + ## Function `get_asset_price`
#[view]
-public fun get_asset_price(asset: address): u256
+public fun get_asset_price(asset: address): u256
 
- + ## Function `get_base_currency_unit` -
public fun get_base_currency_unit(): option::Option<u256>
+
public fun get_base_currency_unit(): option::Option<u256>
 
- + ## Function `set_asset_price` -
public entry fun set_asset_price(account: &signer, asset: address, price: u256)
+
public entry fun set_asset_price(account: &signer, asset: address, price: u256)
 
- + ## Function `batch_set_asset_price` -
public entry fun batch_set_asset_price(account: &signer, assets: vector<address>, prices: vector<u256>)
+
public entry fun batch_set_asset_price(account: &signer, assets: vector<address>, prices: vector<u256>)
 
- + ## Function `update_asset_price` -
public entry fun update_asset_price(account: &signer, asset: address, price: u256)
+
public entry fun update_asset_price(account: &signer, asset: address, price: u256)
 
- + ## Function `remove_asset_price` -
public entry fun remove_asset_price(account: &signer, asset: address)
+
public entry fun remove_asset_price(account: &signer, asset: address)
 
diff --git a/aave-core/aave-mock-oracle/doc/oracle_sentinel.md b/aave-core/aave-mock-oracle/doc/oracle_sentinel.md index 0bee73c..dea6cc1 100644 --- a/aave-core/aave-mock-oracle/doc/oracle_sentinel.md +++ b/aave-core/aave-mock-oracle/doc/oracle_sentinel.md @@ -1,51 +1,56 @@ - + -# Module `0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle_sentinel` +# Module `0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle_sentinel` +@title PriceOracleSentinel +@author Aave +@notice It validates if operations are allowed depending on the PriceOracle health. +@dev Once the PriceOracle gets up after an outage/downtime, users can make their positions healthy during a grace +period. So the PriceOracle is considered completely up once its up and the grace period passed. -- [Struct `GracePeriodUpdated`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_GracePeriodUpdated) -- [Resource `OrcaleSentinel`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_OrcaleSentinel) +- [Struct `GracePeriodUpdated`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_GracePeriodUpdated) +- [Resource `OracleSentinel`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_OracleSentinel) - [Constants](#@Constants_0) -- [Function `init_oracle_sentinel`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_init_oracle_sentinel) -- [Function `set_answer`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_set_answer) -- [Function `latest_round_data`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_latest_round_data) -- [Function `is_borrow_allowed`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_is_borrow_allowed) -- [Function `is_liquidation_allowed`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_is_liquidation_allowed) -- [Function `is_up_and_grace_period_passed`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_is_up_and_grace_period_passed) -- [Function `set_grace_period`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_set_grace_period) -- [Function `get_grace_period`](#0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae_oracle_sentinel_get_grace_period) +- [Function `init_oracle_sentinel`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_init_oracle_sentinel) +- [Function `set_answer`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_set_answer) +- [Function `latest_round_data`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_latest_round_data) +- [Function `is_borrow_allowed`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_is_borrow_allowed) +- [Function `is_liquidation_allowed`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_is_liquidation_allowed) +- [Function `is_up_and_grace_period_passed`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_is_up_and_grace_period_passed) +- [Function `set_grace_period`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_set_grace_period) +- [Function `get_grace_period`](#0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e_oracle_sentinel_get_grace_period)
use 0x1::event;
 use 0x1::signer;
 use 0x1::timestamp;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
 
- + ## Struct `GracePeriodUpdated`
#[event]
-struct GracePeriodUpdated has drop, store
+struct GracePeriodUpdated has drop, store
 
- + -## Resource `OrcaleSentinel` +## Resource `OracleSentinel` -
struct OrcaleSentinel has store, key
+
struct OracleSentinel has store, key
 
@@ -55,111 +60,111 @@ ## Constants - + -
const E_ORACLE_NOT_ADMIN: u64 = 1;
+
const E_ORACLE_NOT_ADMIN: u64 = 1;
 
- + -
const E_RESOURCE_NOT_FOUND: u64 = 2;
+
const E_RESOURCE_NOT_FOUND: u64 = 2;
 
- + ## Function `init_oracle_sentinel` -
public fun init_oracle_sentinel(account: &signer)
+
public(friend) fun init_oracle_sentinel(account: &signer)
 
- + ## Function `set_answer` -
public entry fun set_answer(account: &signer, is_down: bool, timestamp: u256)
+
public entry fun set_answer(account: &signer, is_down: bool, timestamp: u256)
 
- + ## Function `latest_round_data`
#[view]
-public fun latest_round_data(): (u128, u256, u256, u256, u128)
+public fun latest_round_data(): (u128, u256, u256, u256, u128)
 
- + ## Function `is_borrow_allowed`
#[view]
-public fun is_borrow_allowed(): bool
+public fun is_borrow_allowed(): bool
 
- + ## Function `is_liquidation_allowed`
#[view]
-public fun is_liquidation_allowed(): bool
+public fun is_liquidation_allowed(): bool
 
- + ## Function `is_up_and_grace_period_passed`
#[view]
-public fun is_up_and_grace_period_passed(): bool
+public fun is_up_and_grace_period_passed(): bool
 
- + ## Function `set_grace_period` -
public entry fun set_grace_period(account: &signer, new_grace_period: u256)
+
public entry fun set_grace_period(account: &signer, new_grace_period: u256)
 
- + ## Function `get_grace_period`
#[view]
-public fun get_grace_period(): u256
+public fun get_grace_period(): u256
 
diff --git a/aave-core/aave-mock-oracle/sources/oracle.move b/aave-core/aave-mock-oracle/sources/oracle.move index 880ebea..8ea5f16 100644 --- a/aave-core/aave-mock-oracle/sources/oracle.move +++ b/aave-core/aave-mock-oracle/sources/oracle.move @@ -54,7 +54,9 @@ module aave_mock_oracle::oracle { 0 } - public fun get_timestamp(_reward_oracle: RewardOracle, _round_id: u256): u256 { + public fun get_timestamp( + _reward_oracle: RewardOracle, _round_id: u256 + ): u256 { // TODO 0 } @@ -99,11 +101,7 @@ module aave_mock_oracle::oracle { ) acquires AssetPriceList { only_oracle_admin(account); let asset_price_list = borrow_global_mut(@aave_mock_oracle); - if (!simple_map::contains_key(&asset_price_list.value, &asset)) { - simple_map::add(&mut asset_price_list.value, asset, price); - } else { - simple_map::upsert(&mut asset_price_list.value, asset, price); - }; + simple_map::upsert(&mut asset_price_list.value, asset, price); event::emit(OracleEvent { asset, price }) } @@ -115,11 +113,7 @@ module aave_mock_oracle::oracle { for (i in 0..vector::length(&assets)) { let asset = *vector::borrow(&assets, i); let price = *vector::borrow(&prices, i); - if (simple_map::contains_key(&asset_price_list.value, &asset)) { - simple_map::upsert(&mut asset_price_list.value, asset, price); - } else { - simple_map::add(&mut asset_price_list.value, asset, price); - }; + simple_map::upsert(&mut asset_price_list.value, asset, price); event::emit(OracleEvent { asset, price }); }; } @@ -129,8 +123,9 @@ module aave_mock_oracle::oracle { ) acquires AssetPriceList { only_oracle_admin(account); let asset_price_list = borrow_global_mut(@aave_mock_oracle); - assert!(simple_map::contains_key(&asset_price_list.value, &asset), - E_ASSET_NOT_EXISTS); + assert!( + simple_map::contains_key(&asset_price_list.value, &asset), E_ASSET_NOT_EXISTS + ); simple_map::upsert(&mut asset_price_list.value, asset, price); event::emit(OracleEvent { asset, price }) } @@ -138,8 +133,9 @@ module aave_mock_oracle::oracle { public entry fun remove_asset_price(account: &signer, asset: address) acquires AssetPriceList { only_oracle_admin(account); let asset_price_list = borrow_global_mut(@aave_mock_oracle); - assert!(simple_map::contains_key(&asset_price_list.value, &asset), - E_ASSET_NOT_EXISTS); + assert!( + simple_map::contains_key(&asset_price_list.value, &asset), E_ASSET_NOT_EXISTS + ); let price = *simple_map::borrow(&asset_price_list.value, &asset); simple_map::remove(&mut asset_price_list.value, &asset); event::emit(OracleEvent { asset, price }) diff --git a/aave-core/aave-mock-oracle/sources/oracle_sentinel.move b/aave-core/aave-mock-oracle/sources/oracle_sentinel.move index 42017ce..b18d8e5 100644 --- a/aave-core/aave-mock-oracle/sources/oracle_sentinel.move +++ b/aave-core/aave-mock-oracle/sources/oracle_sentinel.move @@ -1,10 +1,18 @@ +/// @title PriceOracleSentinel +/// @author Aave +/// @notice It validates if operations are allowed depending on the PriceOracle health. +/// @dev Once the PriceOracle gets up after an outage/downtime, users can make their positions healthy during a grace +/// period. So the PriceOracle is considered completely up once its up and the grace period passed. module aave_mock_oracle::oracle_sentinel { use std::signer; use aptos_framework::event; use aptos_framework::timestamp; + use aave_acl::acl_manage; use aave_config::error as error_config; + friend aave_mock_oracle::oracle; + const E_ORACLE_NOT_ADMIN: u64 = 1; const E_RESOURCE_NOT_FOUND: u64 = 2; @@ -13,7 +21,7 @@ module aave_mock_oracle::oracle_sentinel { new_grace_period: u256, } - struct OrcaleSentinel has key, store { + struct OracleSentinel has key, store { grace_period: u256, is_down: bool, timestamp_got_up: u256, @@ -23,41 +31,43 @@ module aave_mock_oracle::oracle_sentinel { assert!(signer::address_of(account) == @aave_mock_oracle, E_ORACLE_NOT_ADMIN); } - fun only_pool_admin(account: &signer) { - let account_address = signer::address_of(account); - assert!(acl_manage::is_pool_admin(account_address), - error_config::get_ecaller_not_pool_admin()); - } - + /// @dev Only risk or pool admin can call functions marked by this modifier. fun only_risk_or_pool_admin(account: &signer) { let account_address = signer::address_of(account); - assert!(acl_manage::is_pool_admin(account_address) || acl_manage::is_risk_admin( - account_address), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + acl_manage::is_pool_admin(account_address) + || acl_manage::is_risk_admin(account_address), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); } - public fun init_oracle_sentinel(account: &signer) { - move_to(account, - OrcaleSentinel { grace_period: 0, is_down: false, timestamp_got_up: 0, }) + public(friend) fun init_oracle_sentinel(account: &signer) { + only_oracle_admin(account); + move_to( + account, + OracleSentinel { grace_period: 0, is_down: false, timestamp_got_up: 0, }, + ) } fun exists_at(): bool { - exists(@aave_mock_oracle) + exists(@aave_mock_oracle) } - public entry fun set_answer(account: &signer, is_down: bool, timestamp: u256) acquires OrcaleSentinel { + public entry fun set_answer( + account: &signer, is_down: bool, timestamp: u256 + ) acquires OracleSentinel { only_risk_or_pool_admin(account); assert!(exists_at(), E_RESOURCE_NOT_FOUND); - let oracle_sentinel = borrow_global_mut(@aave_mock_oracle); + let oracle_sentinel = borrow_global_mut(@aave_mock_oracle); oracle_sentinel.is_down = is_down; oracle_sentinel.timestamp_got_up = timestamp; } #[view] - public fun latest_round_data(): (u128, u256, u256, u256, u128) acquires OrcaleSentinel { + public fun latest_round_data(): (u128, u256, u256, u256, u128) acquires OracleSentinel { assert!(exists_at(), E_RESOURCE_NOT_FOUND); let is_down = 0; - let oracle_sentinel = borrow_global(@aave_mock_oracle); + let oracle_sentinel = borrow_global(@aave_mock_oracle); if (oracle_sentinel.is_down) { is_down = 1; }; @@ -65,33 +75,37 @@ module aave_mock_oracle::oracle_sentinel { } #[view] - public fun is_borrow_allowed(): bool acquires OrcaleSentinel { + public fun is_borrow_allowed(): bool acquires OracleSentinel { is_up_and_grace_period_passed() } #[view] - public fun is_liquidation_allowed(): bool acquires OrcaleSentinel { + public fun is_liquidation_allowed(): bool acquires OracleSentinel { is_up_and_grace_period_passed() } #[view] - public fun is_up_and_grace_period_passed(): bool acquires OrcaleSentinel { + public fun is_up_and_grace_period_passed(): bool acquires OracleSentinel { let (_, answer, _, last_update_timestamp, _) = latest_round_data(); - answer == 0 && (timestamp::now_seconds() as u256) - last_update_timestamp > get_grace_period() + answer == 0 + && (timestamp::now_seconds() as u256) - last_update_timestamp + > get_grace_period() } - public entry fun set_grace_period(account: &signer, new_grace_period: u256) acquires OrcaleSentinel { + public entry fun set_grace_period( + account: &signer, new_grace_period: u256 + ) acquires OracleSentinel { only_risk_or_pool_admin(account); assert!(exists_at(), E_RESOURCE_NOT_FOUND); - let oracle_sentinel = borrow_global_mut(@aave_mock_oracle); + let oracle_sentinel = borrow_global_mut(@aave_mock_oracle); oracle_sentinel.grace_period = new_grace_period; event::emit(GracePeriodUpdated { new_grace_period }); } #[view] - public fun get_grace_period(): u256 acquires OrcaleSentinel { + public fun get_grace_period(): u256 acquires OracleSentinel { assert!(exists_at(), E_RESOURCE_NOT_FOUND); - let oracle_sentinel = borrow_global(@aave_mock_oracle); + let oracle_sentinel = borrow_global(@aave_mock_oracle); oracle_sentinel.grace_period } } diff --git a/aave-core/aave-mock-oracle/tests/oracle_sentinel_tests.move b/aave-core/aave-mock-oracle/tests/oracle_sentinel_tests.move index 3c08cad..10daf06 100644 --- a/aave-core/aave-mock-oracle/tests/oracle_sentinel_tests.move +++ b/aave-core/aave-mock-oracle/tests/oracle_sentinel_tests.move @@ -20,7 +20,9 @@ module aave_mock_oracle::oracle_sentinel_tests { #[test(aptos_framework = @0x1, super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] fun test_mock_oracle_sentinel_functionalities( - aptos_framework: &signer, super_admin: &signer, oracle_admin: &signer, + aptos_framework: &signer, + super_admin: &signer, + oracle_admin: &signer, aave_mock_oracle: &signer ) { // init the acl module diff --git a/aave-core/aave-mock-oracle/tests/oracle_tests.move b/aave-core/aave-mock-oracle/tests/oracle_tests.move index 6e0df03..a48ffa5 100644 --- a/aave-core/aave-mock-oracle/tests/oracle_tests.move +++ b/aave-core/aave-mock-oracle/tests/oracle_tests.move @@ -1,12 +1,22 @@ #[test_only] module aave_mock_oracle::oracle_tests { use std::signer; + use std::vector; use aave_mock_oracle::oracle::{ test_init_oracle, get_asset_price, set_asset_price, update_asset_price, - remove_asset_price + remove_asset_price, + batch_set_asset_price, + create_reward_oracle, + decimals, + latest_answer, + latest_timestamp, + latest_round, + get_answer, + get_timestamp, + base_currency_unit, }; use aave_acl::acl_manage::{test_init_module, add_pool_admin, add_asset_listing_admin}; @@ -14,7 +24,7 @@ module aave_mock_oracle::oracle_tests { const TEST_FAILED: u64 = 2; #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] - fun test_mock_oracle_functionalities( + fun test_mock_oracle_get_set_prices( super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer ) { // init the acl module @@ -37,12 +47,89 @@ module aave_mock_oracle::oracle_tests { // assert the set price assert!(get_asset_price(dai_token_address) == 150, TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_batch_set_prices( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + // init the acl module + test_init_module(super_admin); + + // add the roles for the oracle admin + add_pool_admin(super_admin, signer::address_of(oracle_admin)); + add_asset_listing_admin(super_admin, signer::address_of(oracle_admin)); + + // init the oracle + test_init_oracle(aave_mock_oracle); + + // check assets which are not added return price of 0 + let undeclared_asset = @0x0; + assert!(get_asset_price(undeclared_asset) == 0, TEST_SUCCESS); + + // now set a price for a given token + let dai_token_address = @0x42; + let token_addres_43 = @0x43; + + let tokens = vector::empty
(); + vector::push_back(&mut tokens, dai_token_address); + vector::push_back(&mut tokens, token_addres_43); + + let prices = vector::empty(); + vector::push_back(&mut prices, 150); + vector::push_back(&mut prices, 89); + + batch_set_asset_price(aave_mock_oracle, tokens, prices); + + // assert the set price + assert!(get_asset_price(dai_token_address) == 150, TEST_SUCCESS); + assert!(get_asset_price(token_addres_43) == 89, TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_update_prices( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + // init the acl module + test_init_module(super_admin); + + // add the roles for the oracle admin + add_pool_admin(super_admin, signer::address_of(oracle_admin)); + add_asset_listing_admin(super_admin, signer::address_of(oracle_admin)); + + // init the oracle + test_init_oracle(aave_mock_oracle); + + // check assets which are not added return price of 0 + let undeclared_asset = @0x0; + let dai_token_address = @0x42; + + assert!(get_asset_price(undeclared_asset) == 0, TEST_SUCCESS); + set_asset_price(aave_mock_oracle, dai_token_address, 150); // update the oracle price update_asset_price(aave_mock_oracle, dai_token_address, 90); // assert the updated asset price assert!(get_asset_price(dai_token_address) == 90, TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_remove_price( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + // init the acl module + test_init_module(super_admin); + + // add the roles for the oracle admin + add_pool_admin(super_admin, signer::address_of(oracle_admin)); + add_asset_listing_admin(super_admin, signer::address_of(oracle_admin)); + + // init the oracle + test_init_oracle(aave_mock_oracle); + + let dai_token_address = @0x42; + set_asset_price(aave_mock_oracle, dai_token_address, 150); // remove the asset price remove_asset_price(aave_mock_oracle, dai_token_address); @@ -50,4 +137,74 @@ module aave_mock_oracle::oracle_tests { // check the asset price which should now be 0 assert!(get_asset_price(dai_token_address) == 0, TEST_SUCCESS); } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_decimals( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + let reward_oracle = create_reward_oracle(1); + + // check the decimals which should now be 0 + assert!(decimals(reward_oracle) == 0, TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_latest_answer( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + let reward_oracle = create_reward_oracle(1); + + // check the latest_answer which should now be 1 + assert!(latest_answer(reward_oracle) == 1, TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_latest_timestamp( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + let reward_oracle = create_reward_oracle(1); + + // check the latest_timestamp which should now be 0 + assert!(latest_timestamp(reward_oracle) == 0, TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_latest_round( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + let reward_oracle = create_reward_oracle(1); + + // check the latest_round which should now be 0 + assert!(latest_round(reward_oracle) == 0, TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_get_answer( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + let reward_oracle = create_reward_oracle(1); + + // check the get_answer which should now be 0 + assert!(get_answer(reward_oracle, 1) == 0, TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_get_timestamp( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + let reward_oracle = create_reward_oracle(1); + + // check the get_timestamp which should now be 0 + assert!(get_timestamp(reward_oracle, 1) == 0, TEST_SUCCESS); + } + + #[test(super_admin = @aave_acl, oracle_admin = @0x01, aave_mock_oracle = @aave_mock_oracle)] + fun test_mock_oracle_base_currency_unit( + super_admin: &signer, oracle_admin: &signer, aave_mock_oracle: &signer + ) { + let reward_oracle = create_reward_oracle(1); + + // check the base_currency_unit which should now be 0 + assert!(base_currency_unit(reward_oracle, 1) == 0, TEST_SUCCESS); + } } diff --git a/aave-core/aave-oracle/Move.toml b/aave-core/aave-oracle/Move.toml index 2f6fe88..e9cebc6 100644 --- a/aave-core/aave-oracle/Move.toml +++ b/aave-core/aave-oracle/Move.toml @@ -14,7 +14,7 @@ deployer = "_" wormhole = "_" [dependencies] -AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "main" } +AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "mainnet" } # The Pyth package, and the Wormhole package upon which it dependes, specify assorted # Aptos dependency revisions that conflict with the revisions specified in this and # other Aave packages, so to build this package for testing, you'll need to clone @@ -55,7 +55,7 @@ AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir # Pyth = { local = "pyth-crosschain/target_chains/aptos/contracts" } # # 6. Then you should be able to run aptos move test -Pyth = { git = "https://github.com/pyth-network/pyth-crosschain.git", subdir = "target_chains/aptos/contracts", rev = "main" } +Pyth = { git = "https://github.com/pyth-network/pyth-crosschain.git", subdir = "target_chains/aptos/contracts", rev = "mainnet" } AaveConfig = { local = "../aave-config" } AaveAcl = { local = "../aave-acl" } diff --git a/aave-core/aave-oracle/sources/oracle.move b/aave-core/aave-oracle/sources/oracle.move index 4c3bf53..47bb362 100644 --- a/aave-core/aave-oracle/sources/oracle.move +++ b/aave-core/aave-oracle/sources/oracle.move @@ -48,12 +48,14 @@ module aave_oracle::oracle { } fun init_module(account: &signer) { - move_to(account, + move_to( + account, OracleData { pairs_to_indentifiers: smart_table::new>(), pairs_to_vaas: smart_table::new>>(), base_currency: option::none() - }) + }, + ) } fun check_base_currency_set(base_currency: &Option) { @@ -61,8 +63,10 @@ module aave_oracle::oracle { } fun check_is_asset_listing_or_pool_admin(account: address) { - assert!(is_asset_listing_admin(account) || is_pool_admin(account), - NOT_ASSET_LISTING_OR_POOL_ADMIN); + assert!( + is_asset_listing_admin(account) || is_pool_admin(account), + NOT_ASSET_LISTING_OR_POOL_ADMIN, + ); } #[view] @@ -77,10 +81,9 @@ module aave_oracle::oracle { // ensure only admins can call this method check_is_asset_listing_or_pool_admin(signer::address_of(account)); let oracle_data = borrow_global_mut(@aave_oracle); - oracle_data.base_currency = option::some(BaseCurrency { - asset: base_currency_asset, - unit: base_currency_unit, - }) + oracle_data.base_currency = option::some( + BaseCurrency { asset: base_currency_asset, unit: base_currency_unit, }, + ) } /// Gets the oracle base currency @@ -105,19 +108,28 @@ module aave_oracle::oracle { // check the base currency is set check_base_currency_set(&oracle_data.base_currency); // check the base currency is different than the asset being added - assert!((*option::borrow(&oracle_data.base_currency)).asset != asset, - IDENTICAL_BASE_CURRENCY_ALREADY_ADDED); + assert!( + (*option::borrow(&oracle_data.base_currency)).asset != asset, + IDENTICAL_BASE_CURRENCY_ALREADY_ADDED, + ); // check the price_feed identifier exists - assert!(pyth::price_feed_exists(price_identifier::from_byte_vec( - price_feed_identifier)), - PRICE_FEED_IDENTIFIER_NOT_EXIST); + assert!( + pyth::price_feed_exists( + price_identifier::from_byte_vec(price_feed_identifier) + ), + PRICE_FEED_IDENTIFIER_NOT_EXIST, + ); // build the asset pair let asset_pair = - string_utils::format2(&b"{}_{}", asset, (*option::borrow(&oracle_data - .base_currency)).asset); + string_utils::format2( + &b"{}_{}", + asset, + (*option::borrow(&oracle_data.base_currency)).asset, + ); // store the identifier for the asset pair - smart_table::upsert(&mut oracle_data.pairs_to_indentifiers, asset_pair, - price_feed_identifier); + smart_table::upsert( + &mut oracle_data.pairs_to_indentifiers, asset_pair, price_feed_identifier + ); } /// Adds an asset with its vaa @@ -130,12 +142,17 @@ module aave_oracle::oracle { // check the base currency is set check_base_currency_set(&oracle_data.base_currency); // check the base currency is different than the asset being added - assert!((*option::borrow(&oracle_data.base_currency)).asset != asset, - IDENTICAL_BASE_CURRENCY_ALREADY_ADDED); + assert!( + (*option::borrow(&oracle_data.base_currency)).asset != asset, + IDENTICAL_BASE_CURRENCY_ALREADY_ADDED, + ); // build the asset pair let asset_pair = - string_utils::format2(&b"{}_{}", asset, (*option::borrow(&oracle_data - .base_currency)).asset); + string_utils::format2( + &b"{}_{}", + asset, + (*option::borrow(&oracle_data.base_currency)).asset, + ); // store the vaa for the asset pair smart_table::upsert(&mut oracle_data.pairs_to_vaas, asset_pair, vaa); } @@ -146,11 +163,16 @@ module aave_oracle::oracle { let oracle_data = borrow_global_mut(@aave_oracle); // construct the asset pair let asset_pair = - string_utils::format2(&b"{}_{}", asset, (*option::borrow(&oracle_data - .base_currency)).asset); + string_utils::format2( + &b"{}_{}", + asset, + (*option::borrow(&oracle_data.base_currency)).asset, + ); // check and return if listed if (smart_table::contains(&oracle_data.pairs_to_indentifiers, asset_pair)) { - option::some(*smart_table::borrow(&oracle_data.pairs_to_indentifiers, asset_pair)) + option::some( + *smart_table::borrow(&oracle_data.pairs_to_indentifiers, asset_pair) + ) } else { option::none>() } @@ -162,8 +184,11 @@ module aave_oracle::oracle { let oracle_data = borrow_global_mut(@aave_oracle); // construct the asset pair let asset_pair = - string_utils::format2(&b"{}_{}", asset, (*option::borrow(&oracle_data - .base_currency)).asset); + string_utils::format2( + &b"{}_{}", + asset, + (*option::borrow(&oracle_data.base_currency)).asset, + ); // check and return if listed if (smart_table::contains(&oracle_data.pairs_to_vaas, asset_pair)) { option::some(*smart_table::borrow(&oracle_data.pairs_to_vaas, asset_pair)) @@ -184,8 +209,11 @@ module aave_oracle::oracle { assert!(option::is_some(&price_vaa), MISSING_PRICE_VAA); // using the identifier fetch the price let price = - update_and_fetch_price(oracle_fee_payer, *option::borrow(&price_vaa), *option::borrow( - &price_feed_identifier)); + update_and_fetch_price( + oracle_fee_payer, + *option::borrow(&price_vaa), + *option::borrow(&price_feed_identifier), + ); // construct the price let price_positive = if (i64::get_is_negative(&price::get_price(&price))) { @@ -199,9 +227,11 @@ module aave_oracle::oracle { } else { i64::get_magnitude_if_positive(&price::get_expo(&price)) }; - (price_positive * pow(10, expo_magnitude), + ( + price_positive * pow(10, expo_magnitude), price::get_conf(&price), - price::get_timestamp(&price)) + price::get_timestamp(&price) + ) } /// Returns a constant for a mocked price @@ -211,12 +241,15 @@ module aave_oracle::oracle { /// Updates the price feeds by paying in aptos coins and fetches the price from the oracle for the asset pair fun update_and_fetch_price( - oracle_fee_payer: &signer, vaas: vector>, price_feed_identifier: vector + oracle_fee_payer: &signer, + vaas: vector>, + price_feed_identifier: vector ): Price { // See https://docs.pyth.network/documentation/pythnet-price-feeds for reference let coins = - coin::withdraw(oracle_fee_payer, - pyth::get_update_fee(&vaas)); // Get aptos coins to pay for the update + coin::withdraw( + oracle_fee_payer, pyth::get_update_fee(&vaas) + ); // Get aptos coins to pay for the update pyth::update_price_feeds(vaas, coins); // Update price feed with the provided vaas pyth::get_price(price_identifier::from_byte_vec(price_feed_identifier)) // Get recent price (will fail if price is too old) } diff --git a/aave-core/aave-oracle/tests/oracle_tests.move b/aave-core/aave-oracle/tests/oracle_tests.move index 7716f5d..16dbbe3 100644 --- a/aave-core/aave-oracle/tests/oracle_tests.move +++ b/aave-core/aave-oracle/tests/oracle_tests.move @@ -43,21 +43,31 @@ module aave_oracle::oracle_tests { // assert oracle base currency let expected_base_currency = create_base_currency(string::utf8(b"USD"), 1); - assert!(get_oracle_base_currency_for_testing() - == option::some(expected_base_currency), TEST_SUCCESS); + assert!( + get_oracle_base_currency_for_testing() == option::some( + expected_base_currency + ), + TEST_SUCCESS, + ); // asset price feed identifier - assert!(get_asset_identifier_for_testing(string::utf8(b"BTC")) - == option::none>(), - TEST_SUCCESS); - assert!(get_asset_vaa_for_testing(string::utf8(b"BTC")) - == option::none>>(), - TEST_SUCCESS); + assert!( + get_asset_identifier_for_testing(string::utf8(b"BTC")) + == option::none>(), + TEST_SUCCESS, + ); + assert!( + get_asset_vaa_for_testing(string::utf8(b"BTC")) + == option::none>>(), + TEST_SUCCESS, + ); let vaa = vector[vector[0, 1, 2], vector[3, 4, 5]]; add_asset_vaa(oracle_admin, string::utf8(b"BTC"), vaa); - assert!(get_asset_vaa_for_testing(string::utf8(b"BTC")) - == option::some>>(vaa), - TEST_SUCCESS); + assert!( + get_asset_vaa_for_testing(string::utf8(b"BTC")) + == option::some>>(vaa), + TEST_SUCCESS, + ); } } diff --git a/aave-core/aave-scripts/sources/post-publish.move b/aave-core/aave-scripts/sources/post-publish.move index 2bfade1..0b1ff2d 100644 --- a/aave-core/aave-scripts/sources/post-publish.move +++ b/aave-core/aave-scripts/sources/post-publish.move @@ -7,18 +7,42 @@ script { fun init_pool_addresses_provider(account: &signer) { pool_addresses_provider::set_acl_admin(account, @aave_acl); - debug::print(&string_utils::format1(&b">>>> Acl Admin set at address: {}",@aave_acl)); + debug::print( + &string_utils::format1(&b">>>> Acl Admin set at address: {}", @aave_acl) + ); pool_addresses_provider::set_acl_manager(account, @aave_acl); - debug::print(&string_utils::format1(&b">>>> Acl Manager set at address: {}",@aave_acl)); + debug::print( + &string_utils::format1(&b">>>> Acl Manager set at address: {}", @aave_acl) + ); pool_addresses_provider::set_pool_configurator(account, @aave_pool); - debug::print(&string_utils::format1(&b">>>> Pool Configurator set at address: {}",@aave_pool)); + debug::print( + &string_utils::format1( + &b">>>> Pool Configurator set at address: {}", @aave_pool + ) + ); pool_addresses_provider::set_pool_data_provider(account, @aave_pool); - debug::print(&string_utils::format1(&b">>>> Pool Data Provider set at address: {}",@aave_pool)); + debug::print( + &string_utils::format1( + &b">>>> Pool Data Provider set at address: {}", @aave_pool + ) + ); pool_addresses_provider::set_pool_impl(account, @aave_pool); - debug::print(&string_utils::format1(&b">>>> Pool Implementation set at address: {}",@aave_pool)); + debug::print( + &string_utils::format1( + &b">>>> Pool Implementation set at address: {}", @aave_pool + ), + ); pool_addresses_provider::set_price_oracle(account, @aave_mock_oracle); - debug::print(&string_utils::format1(&b">>>> Mock Oracle set at address: {}",@aave_mock_oracle)); + debug::print( + &string_utils::format1( + &b">>>> Mock Oracle set at address: {}", @aave_mock_oracle + ) + ); pool_addresses_provider::set_price_oracle_sentinel(account, @aave_mock_oracle); - debug::print(&string_utils::format1(&b">>>> Mock Oracle Sentinel set at address: {}",@aave_mock_oracle)); + debug::print( + &string_utils::format1( + &b">>>> Mock Oracle Sentinel set at address: {}", @aave_mock_oracle + ), + ); } -} \ No newline at end of file +} diff --git a/aave-core/doc/a_token_factory.md b/aave-core/doc/a_token_factory.md index bcc1e66..e5e457e 100644 --- a/aave-core/doc/a_token_factory.md +++ b/aave-core/doc/a_token_factory.md @@ -1,38 +1,35 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory` -- [Struct `Initialized`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_Initialized) -- [Struct `BalanceTransfer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_BalanceTransfer) +- [Struct `Initialized`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_Initialized) +- [Struct `BalanceTransfer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_BalanceTransfer) - [Constants](#@Constants_0) -- [Function `create_token`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_create_token) -- [Function `rescue_tokens`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_rescue_tokens) -- [Function `mint`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_mint) -- [Function `burn`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_burn) -- [Function `mint_to_treasury`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_mint_to_treasury) -- [Function `transfer_underlying_to`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_transfer_underlying_to) -- [Function `transfer_on_liquidation`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_transfer_on_liquidation) -- [Function `handle_repayment`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_handle_repayment) -- [Function `get_revision`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_get_revision) -- [Function `get_token_account_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_get_token_account_address) -- [Function `get_metadata_by_symbol`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_get_metadata_by_symbol) -- [Function `token_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_token_address) -- [Function `asset_metadata`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_asset_metadata) -- [Function `get_reserve_treasury_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_get_reserve_treasury_address) -- [Function `get_underlying_asset_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_get_underlying_asset_address) -- [Function `get_previous_index`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_get_previous_index) -- [Function `get_scaled_user_balance_and_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_get_scaled_user_balance_and_supply) -- [Function `scale_balance_of`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_scale_balance_of) -- [Function `balance_of`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_balance_of) -- [Function `scale_total_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_scale_total_supply) -- [Function `supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_supply) -- [Function `maximum`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_maximum) -- [Function `name`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_name) -- [Function `symbol`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_symbol) -- [Function `decimals`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_a_token_factory_decimals) +- [Function `create_token`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_create_token) +- [Function `rescue_tokens`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_rescue_tokens) +- [Function `mint`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_mint) +- [Function `burn`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_burn) +- [Function `mint_to_treasury`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_mint_to_treasury) +- [Function `transfer_underlying_to`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_transfer_underlying_to) +- [Function `transfer_on_liquidation`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_transfer_on_liquidation) +- [Function `handle_repayment`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_handle_repayment) +- [Function `get_revision`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_get_revision) +- [Function `get_token_account_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_get_token_account_address) +- [Function `get_metadata_by_symbol`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_get_metadata_by_symbol) +- [Function `token_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_token_address) +- [Function `asset_metadata`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_asset_metadata) +- [Function `get_reserve_treasury_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_get_reserve_treasury_address) +- [Function `get_underlying_asset_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_get_underlying_asset_address) +- [Function `get_previous_index`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_get_previous_index) +- [Function `get_scaled_user_balance_and_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_get_scaled_user_balance_and_supply) +- [Function `scaled_balance_of`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_scaled_balance_of) +- [Function `scaled_total_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_scaled_total_supply) +- [Function `name`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_name) +- [Function `symbol`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_symbol) +- [Function `decimals`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_a_token_factory_decimals)
use 0x1::account;
@@ -40,38 +37,48 @@
 use 0x1::event;
 use 0x1::fungible_asset;
 use 0x1::object;
-use 0x1::option;
 use 0x1::resource_account;
 use 0x1::signer;
 use 0x1::string;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::token_base;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::token_base;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
 
- + ## Struct `Initialized` +@dev Emitted when an aToken is initialized +@param underlyingAsset The address of the underlying asset +@param treasury The address of the treasury +@param a_token_decimals The decimals of the underlying +@param a_token_name The name of the aToken +@param a_token_symbol The symbol of the aToken
#[event]
-struct Initialized has drop, store
+struct Initialized has drop, store
 
- + ## Struct `BalanceTransfer` +@dev Emitted during the transfer action +@param from The user whose tokens are being transferred +@param to The recipient +@param value The scaled amount being transferred +@param index The next liquidity index of the reserve
#[event]
-struct BalanceTransfer has drop, store
+struct BalanceTransfer has drop, store
 
@@ -81,311 +88,350 @@ ## Constants - + -
const ATOKEN_REVISION: u256 = 1;
+
const ATOKEN_REVISION: u256 = 1;
 
- + -
const E_NOT_A_TOKEN_ADMIN: u64 = 1;
+
const E_NOT_A_TOKEN_ADMIN: u64 = 1;
 
- + ## Function `create_token` +@notice Creates a new aToken +@param signer The signer of the transaction +@param name The name of the aToken +@param symbol The symbol of the aToken +@param decimals The decimals of the aToken +@param icon_uri The icon URI of the aToken +@param project_uri The project URI of the aToken +@param underlying_asset The address of the underlying asset +@param treasury The address of the treasury -
public(friend) fun create_token(signer: &signer, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String, underlying_asset: address, treasury: address)
+
public(friend) fun create_token(signer: &signer, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String, underlying_asset: address, treasury: address)
 
- + ## Function `rescue_tokens` +@notice Rescue and transfer tokens locked in this contract +@param token The address of the token +@param to The address of the recipient +@param amount The amount of token to transfer -
public entry fun rescue_tokens(account: &signer, token: address, to: address, amount: u256)
+
public entry fun rescue_tokens(account: &signer, token: address, to: address, amount: u256)
 
- + ## Function `mint` +@notice Mints amount aTokens to user +@param caller The address performing the mint +@param on_behalf_of The address of the user that will receive the minted aTokens +@param amount The amount of tokens getting minted +@param index The next liquidity index of the reserve +@param metadata_address The address of the aToken -
public(friend) fun mint(caller: address, on_behalf_of: address, amount: u256, index: u256, metadata_address: address)
+
public(friend) fun mint(caller: address, on_behalf_of: address, amount: u256, index: u256, metadata_address: address)
 
- + ## Function `burn` +@notice Burns aTokens from user and sends the equivalent amount of underlying to receiverOfUnderlying +@dev In some instances, the mint event could be emitted from a burn transaction +if the amount to burn is less than the interest that the user accrued +@param from The address from which the aTokens will be burned +@param receiver_of_underlying The address that will receive the underlying +@param amount The amount being burned +@param index The next liquidity index of the reserve +@param metadata_address The address of the aToken -
public(friend) fun burn(from: address, receiver_of_underlying: address, amount: u256, index: u256, metadata_address: address)
+
public(friend) fun burn(from: address, receiver_of_underlying: address, amount: u256, index: u256, metadata_address: address)
 
- + ## Function `mint_to_treasury` +@notice Mints aTokens to the reserve treasury +@param amount The amount of tokens getting minted +@param index The next liquidity index of the reserve +@param metadata_address The address of the aToken -
public(friend) fun mint_to_treasury(amount: u256, index: u256, metadata_address: address)
+
public(friend) fun mint_to_treasury(amount: u256, index: u256, metadata_address: address)
 
- + ## Function `transfer_underlying_to` +@notice Transfers the underlying asset to target. +@dev Used by the Pool to transfer assets in borrow(), withdraw() and flashLoan() +@param to The recipient of the underlying +@param amount The amount getting transferred +@param metadata_address The address of the aToken -
public(friend) fun transfer_underlying_to(to: address, amount: u256, metadata_address: address)
+
public(friend) fun transfer_underlying_to(to: address, amount: u256, metadata_address: address)
 
- + ## Function `transfer_on_liquidation` +@notice Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken +@param from The address getting liquidated, current owner of the aTokens +@param to The recipient +@param amount The amount of tokens getting transferred +@param index The next liquidity index of the reserve +@param metadata_address The address of the aToken -
public(friend) fun transfer_on_liquidation(from: address, to: address, amount: u256, index: u256, metadata_address: address)
+
public(friend) fun transfer_on_liquidation(from: address, to: address, amount: u256, index: u256, metadata_address: address)
 
- + ## Function `handle_repayment` +@notice Handles the underlying received by the aToken after the transfer has been completed. +@dev The default implementation is empty as with standard ERC20 tokens, nothing needs to be done after the +transfer is concluded. However in the future there may be aTokens that allow for example to stake the underlying +to receive LM rewards. In that case, handleRepayment() would perform the staking of the underlying asset. +@param user The user executing the repayment +@param on_behalf_of The address of the user who will get his debt reduced/removed +@param amount The amount getting repaid +@param metadata_address The address of the aToken -
public fun handle_repayment(_user: address, _onBehalfOf: address, _amount: u256, _metadata_address: address)
+
public fun handle_repayment(_user: address, _onBehalfOf: address, _amount: u256, _metadata_address: address)
 
- + ## Function `get_revision`
#[view]
-public fun get_revision(): u256
+public fun get_revision(): u256
 
- + ## Function `get_token_account_address` +@notice Return the address of the managed fungible asset that's created resource account. +@param metadata_address The address of the aToken
#[view]
-public fun get_token_account_address(metadata_address: address): address
+public fun get_token_account_address(metadata_address: address): address
 
- + ## Function `get_metadata_by_symbol` -Return the address of the managed fungible asset that's created when this module is deployed.
#[view]
-public fun get_metadata_by_symbol(owner: address, symbol: string::String): object::Object<fungible_asset::Metadata>
+public fun get_metadata_by_symbol(owner: address, symbol: string::String): object::Object<fungible_asset::Metadata>
 
- + ## Function `token_address`
#[view]
-public fun token_address(owner: address, symbol: string::String): address
+public fun token_address(owner: address, symbol: string::String): address
 
- + ## Function `asset_metadata`
#[view]
-public fun asset_metadata(owner: address, symbol: string::String): object::Object<fungible_asset::Metadata>
+public fun asset_metadata(owner: address, symbol: string::String): object::Object<fungible_asset::Metadata>
 
- + ## Function `get_reserve_treasury_address` +@notice Returns the address of the Aave treasury, receiving the fees on this aToken. +@param metadata_address The address of the aToken +@return Address of the Aave treasury
#[view]
-public fun get_reserve_treasury_address(metadata_address: address): address
+public fun get_reserve_treasury_address(metadata_address: address): address
 
- + ## Function `get_underlying_asset_address` +@notice Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) +@param metadata_address The address of the aToken +@return The address of the underlying asset
#[view]
-public fun get_underlying_asset_address(metadata_address: address): address
+public fun get_underlying_asset_address(metadata_address: address): address
 
- + ## Function `get_previous_index` +@notice Returns last index interest was accrued to the user's balance +@param user The address of the user +@param metadata_address The address of the aToken +@return The last index interest was accrued to the user's balance, expressed in ray
#[view]
-public fun get_previous_index(user: address, metadata_address: address): u256
+public fun get_previous_index(user: address, metadata_address: address): u256
 
- + ## Function `get_scaled_user_balance_and_supply` +@notice Returns the scaled balance of the user and the scaled total supply. +@param owner The address of the user +@param metadata_address The address of the aToken +@return The scaled balance of the user +@return The scaled total supply
#[view]
-public fun get_scaled_user_balance_and_supply(owner: address, metadata_address: address): (u256, u256)
+public fun get_scaled_user_balance_and_supply(owner: address, metadata_address: address): (u256, u256)
 
- + -## Function `scale_balance_of` +## Function `scaled_balance_of` +@notice Returns the scaled balance of the user. +@dev The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index +at the moment of the update +@param owner The user whose balance is calculated +@param metadata_address The address of the aToken +@return The scaled balance of the user
#[view]
-public fun scale_balance_of(owner: address, metadata_address: address): u256
+public fun scaled_balance_of(owner: address, metadata_address: address): u256
 
- + -## Function `balance_of` +## Function `scaled_total_supply` +@notice Returns the scaled total supply of the scaled balance token. Represents sum(debt/index) +@param metadata_address The address of the aToken +@return The scaled total supply
#[view]
-public fun balance_of(owner: address, metadata_address: address): u256
+public fun scaled_total_supply(metadata_address: address): u256
 
- - -## Function `scale_total_supply` - - - -
#[view]
-public fun scale_total_supply(metadata_address: address): u256
-
- - - - - -## Function `supply` - - - -
#[view]
-public fun supply(metadata_address: address): u256
-
- - - - - -## Function `maximum` - - - -
#[view]
-public fun maximum(metadata_address: address): option::Option<u128>
-
- - - - + ## Function `name`
#[view]
-public fun name(metadata_address: address): string::String
+public fun name(metadata_address: address): string::String
 
- + ## Function `symbol`
#[view]
-public fun symbol(metadata_address: address): string::String
+public fun symbol(metadata_address: address): string::String
 
- + ## Function `decimals`
#[view]
-public fun decimals(metadata_address: address): u8
+public fun decimals(metadata_address: address): u8
 
diff --git a/aave-core/doc/admin_controlled_ecosystem_reserve.md b/aave-core/doc/admin_controlled_ecosystem_reserve.md index b9e0293..97353bc 100644 --- a/aave-core/doc/admin_controlled_ecosystem_reserve.md +++ b/aave-core/doc/admin_controlled_ecosystem_reserve.md @@ -1,20 +1,20 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::admin_controlled_ecosystem_reserve` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::admin_controlled_ecosystem_reserve` -- [Struct `NewFundsAdmin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_admin_controlled_ecosystem_reserve_NewFundsAdmin) -- [Resource `AdminControlledEcosystemReserveData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_admin_controlled_ecosystem_reserve_AdminControlledEcosystemReserveData) +- [Struct `NewFundsAdmin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_admin_controlled_ecosystem_reserve_NewFundsAdmin) +- [Resource `AdminControlledEcosystemReserveData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_admin_controlled_ecosystem_reserve_AdminControlledEcosystemReserveData) - [Constants](#@Constants_0) -- [Function `initialize`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_admin_controlled_ecosystem_reserve_initialize) -- [Function `check_is_funds_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_admin_controlled_ecosystem_reserve_check_is_funds_admin) -- [Function `get_revision`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_admin_controlled_ecosystem_reserve_get_revision) -- [Function `get_funds_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_admin_controlled_ecosystem_reserve_get_funds_admin) -- [Function `admin_controlled_ecosystem_reserve_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_admin_controlled_ecosystem_reserve_admin_controlled_ecosystem_reserve_address) -- [Function `admin_controlled_ecosystem_reserve_object`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_admin_controlled_ecosystem_reserve_admin_controlled_ecosystem_reserve_object) -- [Function `transfer_out`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_admin_controlled_ecosystem_reserve_transfer_out) +- [Function `initialize`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_admin_controlled_ecosystem_reserve_initialize) +- [Function `check_is_funds_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_admin_controlled_ecosystem_reserve_check_is_funds_admin) +- [Function `get_revision`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_admin_controlled_ecosystem_reserve_get_revision) +- [Function `get_funds_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_admin_controlled_ecosystem_reserve_get_funds_admin) +- [Function `admin_controlled_ecosystem_reserve_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_admin_controlled_ecosystem_reserve_admin_controlled_ecosystem_reserve_address) +- [Function `admin_controlled_ecosystem_reserve_object`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_admin_controlled_ecosystem_reserve_admin_controlled_ecosystem_reserve_object) +- [Function `transfer_out`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_admin_controlled_ecosystem_reserve_transfer_out)
use 0x1::event;
@@ -23,30 +23,30 @@
 use 0x1::primary_fungible_store;
 use 0x1::signer;
 use 0x1::smart_table;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
 
- + ## Struct `NewFundsAdmin`
#[event]
-struct NewFundsAdmin has drop, store
+struct NewFundsAdmin has drop, store
 
- + ## Resource `AdminControlledEcosystemReserveData` -
struct AdminControlledEcosystemReserveData has key
+
struct AdminControlledEcosystemReserveData has key
 
@@ -56,133 +56,133 @@ ## Constants - + -
const ADMIN_CONTROLLED_ECOSYSTEM_RESERVE: vector<u8> = [65, 68, 77, 73, 78, 95, 67, 79, 78, 84, 82, 79, 76, 76, 69, 68, 95, 69, 67, 79, 83, 89, 83, 84, 69, 77, 95, 82, 69, 83, 69, 82, 86, 69];
+
const ADMIN_CONTROLLED_ECOSYSTEM_RESERVE: vector<u8> = [65, 68, 77, 73, 78, 95, 67, 79, 78, 84, 82, 79, 76, 76, 69, 68, 95, 69, 67, 79, 83, 89, 83, 84, 69, 77, 95, 82, 69, 83, 69, 82, 86, 69];
 
- + -
const NOT_FUNDS_ADMIN: u64 = 1;
+
const NOT_FUNDS_ADMIN: u64 = 1;
 
- + -
const ONLY_BY_FUNDS_ADMIN: u64 = 1;
+
const ONLY_BY_FUNDS_ADMIN: u64 = 3;
 
- + -
const REVISION: u256 = 1;
+
const REVISION: u256 = 2;
 
- + -
const TEST_FAILED: u64 = 2;
+
const TEST_FAILED: u64 = 2;
 
- + -
const TEST_SUCCESS: u64 = 1;
+
const TEST_SUCCESS: u64 = 1;
 
- + ## Function `initialize` -
public fun initialize(sender: &signer)
+
public fun initialize(sender: &signer)
 
- + ## Function `check_is_funds_admin` -
public fun check_is_funds_admin(account: address)
+
public fun check_is_funds_admin(account: address)
 
- + ## Function `get_revision` -
public fun get_revision(): u256
+
public fun get_revision(): u256
 
- + ## Function `get_funds_admin` -
public fun get_funds_admin(): address
+
public fun get_funds_admin(): address
 
- + ## Function `admin_controlled_ecosystem_reserve_address`
#[view]
-public fun admin_controlled_ecosystem_reserve_address(): address
+public fun admin_controlled_ecosystem_reserve_address(): address
 
- + ## Function `admin_controlled_ecosystem_reserve_object`
#[view]
-public fun admin_controlled_ecosystem_reserve_object(): object::Object<admin_controlled_ecosystem_reserve::AdminControlledEcosystemReserveData>
+public fun admin_controlled_ecosystem_reserve_object(): object::Object<admin_controlled_ecosystem_reserve::AdminControlledEcosystemReserveData>
 
- + ## Function `transfer_out` -
public fun transfer_out(sender: &signer, asset_metadata: object::Object<fungible_asset::Metadata>, receiver: address, amount: u64)
+
public fun transfer_out(sender: &signer, asset_metadata: object::Object<fungible_asset::Metadata>, receiver: address, amount: u64)
 
diff --git a/aave-core/doc/borrow_logic.md b/aave-core/doc/borrow_logic.md index dc5d552..3cf0183 100644 --- a/aave-core/doc/borrow_logic.md +++ b/aave-core/doc/borrow_logic.md @@ -1,110 +1,176 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::borrow_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::borrow_logic` +@title borrow_logic module +@author Aave +@notice Implements the base logic for all the actions related to borrowing -- [Struct `Borrow`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_borrow_logic_Borrow) -- [Struct `Repay`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_borrow_logic_Repay) -- [Struct `IsolationModeTotalDebtUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_borrow_logic_IsolationModeTotalDebtUpdated) -- [Function `borrow`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_borrow_logic_borrow) -- [Function `internal_borrow`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_borrow_logic_internal_borrow) -- [Function `repay`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_borrow_logic_repay) -- [Function `repay_with_a_tokens`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_borrow_logic_repay_with_a_tokens) +- [Struct `Borrow`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_borrow_logic_Borrow) +- [Struct `Repay`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_borrow_logic_Repay) +- [Struct `IsolationModeTotalDebtUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_borrow_logic_IsolationModeTotalDebtUpdated) +- [Function `borrow`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_borrow_logic_borrow) +- [Function `internal_borrow`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_borrow_logic_internal_borrow) +- [Function `repay`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_borrow_logic_repay) +- [Function `repay_with_a_tokens`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_borrow_logic_repay_with_a_tokens)
use 0x1::event;
 use 0x1::signer;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::emode_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::isolation_mode_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::validation_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::variable_token_factory;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::emode_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::isolation_mode_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::validation_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::variable_debt_token_factory;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `Borrow` +@dev Emitted on borrow() and flashLoan() when debt needs to be opened +@param reserve The address of the underlying asset being borrowed +@param user The address of the user initiating the borrow(), receiving the funds on borrow() or just +initiator of the transaction on flashLoan() +@param on_behalf_of The address that will be getting the debt +@param amount The amount borrowed out +@param interest_rate_mode The rate mode: 2 for Variable +@param borrow_rate The numeric rate at which the user has borrowed, expressed in ray +@param referral_code The referral code used
#[event]
-struct Borrow has copy, drop, store
+struct Borrow has copy, drop, store
 
- + ## Struct `Repay` +@dev Emitted on repay() +@param reserve The address of the underlying asset of the reserve +@param user The beneficiary of the repayment, getting his debt reduced +@param repayer The address of the user initiating the repay(), providing the funds +@param amount The amount repaid +@param use_a_tokens True if the repayment is done using aTokens, false if done with underlying asset directly
#[event]
-struct Repay has drop, store
+struct Repay has drop, store
 
- + ## Struct `IsolationModeTotalDebtUpdated` +@dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets +@param asset The address of the underlying asset of the reserve +@param totalDebt The total isolation mode debt for the reserve
#[event]
-struct IsolationModeTotalDebtUpdated has drop, store
+struct IsolationModeTotalDebtUpdated has drop, store
 
- + ## Function `borrow` - - -
public entry fun borrow(account: &signer, asset: address, on_behalf_of: address, amount: u256, interest_rate_mode: u8, referral_code: u16)
+@notice Allows users to borrow a specific amount of the reserve underlying asset, provided that the borrower
+already supplied enough collateral, or he was given enough allowance by a credit delegator on the
+corresponding debt token VariableDebtToken
+- E.g. User borrows 100 USDC passing as on_behalf_of his own address, receiving the 100 USDC in his wallet
+and 100 stable/variable debt tokens, depending on the interest_rate_mode
+@param asset The address of the underlying asset to borrow
+@param amount The amount to be borrowed
+@param interest_rate_mode The interest rate mode at which the user wants to borrow: 2 for Variable
+@param referral_code The code used to register the integrator originating the operation, for potential rewards.
+0 if the action is executed directly by the user, without any middle-man
+@param on_behalf_of The address of the user who will receive the debt. Should be the address of the borrower itself
+calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
+if he has been given credit delegation allowance
+
+
+
public entry fun borrow(account: &signer, asset: address, amount: u256, interest_rate_mode: u8, referral_code: u16, on_behalf_of: address)
 
- + ## Function `internal_borrow` - - -
public(friend) fun internal_borrow(account: &signer, asset: address, on_behalf_of: address, amount: u256, interest_rate_mode: u8, referral_code: u16, release_underlying: bool)
+@notice Implements the borrow feature. Borrowing allows users that provided collateral to draw liquidity from the
+Aave protocol proportionally to their collateralization power. For isolated positions, it also increases the
+isolated debt.
+@dev  Emits the Borrow() event
+@param account The signer account
+@param asset The address of the underlying asset to borrow
+@param amount The amount to be borrowed
+@param interest_rate_mode The interest rate mode at which the user wants to borrow: 2 for Variable
+@param referral_code The code used to register the integrator originating the operation, for potential rewards.
+0 if the action is executed directly by the user, without any middle
+@param on_behalf_of The address of the user who will receive the debt. Should be the address of the borrower itself
+calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
+if he has been given credit delegation allowance
+@param release_underlying If true, the underlying asset will be transferred to the user, otherwise it will stay
+
+
+
public(friend) fun internal_borrow(account: &signer, asset: address, amount: u256, interest_rate_mode: u8, referral_code: u16, on_behalf_of: address, release_underlying: bool)
 
- + ## Function `repay` +@notice Repays a borrowed amount on a specific reserve, burning the equivalent debt tokens owned +- E.g. User repays 100 USDC, burning 100 variable debt tokens of the on_behalf_of address +@param asset The address of the borrowed underlying asset previously borrowed +@param amount The amount to repay +- Send the value math_utils::u256_max() in order to repay the whole debt for asset on the specific debtMode +@param interest_rate_mode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable +@param on_behalf_of The address of the user who will get his debt reduced/removed. Should be the address of the +user calling the function if he wants to reduce/remove his own debt, or the address of any other +other borrower whose debt should be removed -
public entry fun repay(account: &signer, asset: address, amount: u256, interest_rate_mode: u8, on_behalf_of: address)
+
public entry fun repay(account: &signer, asset: address, amount: u256, interest_rate_mode: u8, on_behalf_of: address)
 
- + ## Function `repay_with_a_tokens` +@notice Repays a borrowed amount on a specific reserve using the reserve aTokens, burning the +equivalent debt tokens +- E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable debt tokens +@dev Passing math_utils::u256_max() as amount will clean up any residual aToken dust balance, if the user aToken +balance is not enough to cover the whole debt +@param account The signer account +@param asset The address of the borrowed underlying asset previously borrowed +@param amount The amount to repay +@param interest_rate_mode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable -
public entry fun repay_with_a_tokens(account: &signer, asset: address, amount: u256, interest_rate_mode: u8)
+
public entry fun repay_with_a_tokens(account: &signer, asset: address, amount: u256, interest_rate_mode: u8)
 
diff --git a/aave-core/doc/bridge_logic.md b/aave-core/doc/bridge_logic.md index 51d56b4..faa6545 100644 --- a/aave-core/doc/bridge_logic.md +++ b/aave-core/doc/bridge_logic.md @@ -1,86 +1,116 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::bridge_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::bridge_logic` -- [Struct `ReserveUsedAsCollateralEnabled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_bridge_logic_ReserveUsedAsCollateralEnabled) -- [Struct `MintUnbacked`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_bridge_logic_MintUnbacked) -- [Struct `BackUnbacked`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_bridge_logic_BackUnbacked) -- [Function `mint_unbacked`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_bridge_logic_mint_unbacked) -- [Function `back_unbacked`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_bridge_logic_back_unbacked) +- [Struct `ReserveUsedAsCollateralEnabled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_bridge_logic_ReserveUsedAsCollateralEnabled) +- [Struct `MintUnbacked`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_bridge_logic_MintUnbacked) +- [Struct `BackUnbacked`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_bridge_logic_BackUnbacked) +- [Function `mint_unbacked`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_bridge_logic_mint_unbacked) +- [Function `back_unbacked`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_bridge_logic_back_unbacked)
use 0x1::event;
 use 0x1::signer;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool_validation;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::validation_logic;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool_validation;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::validation_logic;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `ReserveUsedAsCollateralEnabled` +@dev Emitted on setUserUseReserveAsCollateral() +@param reserve The address of the underlying asset of the reserve +@param user The address of the user enabling the usage as collateral
#[event]
-struct ReserveUsedAsCollateralEnabled has drop, store
+struct ReserveUsedAsCollateralEnabled has drop, store
 
- + ## Struct `MintUnbacked` +@dev Emitted on mint_unbacked() +@param reserve The address of the underlying asset of the reserve +@param user The address initiating the supply +@param on_behalf_of The beneficiary of the supplied assets, receiving the aTokens +@param amount The amount of supplied assets +@param referral_code The referral code used
#[event]
-struct MintUnbacked has drop, store
+struct MintUnbacked has drop, store
 
- + ## Struct `BackUnbacked` +@dev Emitted on back_unbacked() +@param reserve The address of the underlying asset of the reserve +@param backer The address paying for the backing +@param amount The amount added as backing +@param fee The amount paid in fees
#[event]
-struct BackUnbacked has drop, store
+struct BackUnbacked has drop, store
 
- + ## Function `mint_unbacked` +@notice Mint unbacked aTokens to a user and updates the unbacked for the reserve. +@dev Essentially a supply without transferring the underlying. +@dev Emits the MintUnbacked event +@dev Emits the ReserveUsedAsCollateralEnabled if asset is set as collateral +@param asset The address of the underlying asset to mint aTokens of +@param amount The amount to mint +@param on_behalf_of The address that will receive the aTokens +@param referral_code Code used to register the integrator originating the operation, for potential rewards. +0 if the action is executed directly by the user, without any middle-man -
public entry fun mint_unbacked(account: &signer, asset: address, amount: u256, on_behalf_of: address, referral_code: u16)
+
public entry fun mint_unbacked(account: &signer, asset: address, amount: u256, on_behalf_of: address, referral_code: u16)
 
- + ## Function `back_unbacked` +@notice Back the current unbacked with amount and pay fee. +@dev It is not possible to back more than the existing unbacked amount of the reserve +@dev Emits the BackUnbacked event +@param asset The address of the underlying asset to repay +@param amount The amount to back +@param fee The amount paid in fees +@return The backed amount -
public entry fun back_unbacked(account: &signer, asset: address, amount: u256, fee: u256, protocol_fee_bps: u256)
+
public entry fun back_unbacked(account: &signer, asset: address, amount: u256, fee: u256)
 
diff --git a/aave-core/doc/coin_wrapper.md b/aave-core/doc/coin_wrapper.md index a51cee9..d306c0a 100644 --- a/aave-core/doc/coin_wrapper.md +++ b/aave-core/doc/coin_wrapper.md @@ -1,25 +1,25 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::coin_wrapper` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::coin_wrapper` -- [Struct `FungibleAssetData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_FungibleAssetData) -- [Resource `WrapperAccount`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_WrapperAccount) +- [Struct `FungibleAssetData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_FungibleAssetData) +- [Resource `WrapperAccount`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_WrapperAccount) - [Constants](#@Constants_0) -- [Function `initialize`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_initialize) -- [Function `is_initialized`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_is_initialized) -- [Function `wrapper_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_wrapper_address) -- [Function `is_supported`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_is_supported) -- [Function `is_wrapper`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_is_wrapper) -- [Function `get_coin_type`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_get_coin_type) -- [Function `get_wrapper`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_get_wrapper) -- [Function `get_original`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_get_original) -- [Function `format_fungible_asset`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_format_fungible_asset) -- [Function `wrap`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_wrap) -- [Function `unwrap`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_unwrap) -- [Function `create_fungible_asset`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_coin_wrapper_create_fungible_asset) +- [Function `initialize`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_initialize) +- [Function `is_initialized`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_is_initialized) +- [Function `wrapper_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_wrapper_address) +- [Function `is_supported`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_is_supported) +- [Function `is_wrapper`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_is_wrapper) +- [Function `get_coin_type`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_get_coin_type) +- [Function `get_wrapper`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_get_wrapper) +- [Function `get_original`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_get_original) +- [Function `format_fungible_asset`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_format_fungible_asset) +- [Function `wrap`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_wrap) +- [Function `unwrap`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_unwrap) +- [Function `create_fungible_asset`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_coin_wrapper_create_fungible_asset)
use 0x1::account;
@@ -34,24 +34,24 @@
 use 0x1::string;
 use 0x1::string_utils;
 use 0x1::type_info;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::package_manager;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::package_manager;
 
- + ## Struct `FungibleAssetData` Stores the refs for a specific fungible asset wrapper for wrapping and unwrapping. -
struct FungibleAssetData has store
+
struct FungibleAssetData has store
 
- + ## Resource `WrapperAccount` @@ -60,7 +60,7 @@ This main resource account will also be the one holding all the deposited coins, CoinStore resource. See coin_wrapper.move in the Aptos Framework for more details. -
struct WrapperAccount has key
+
struct WrapperAccount has key
 
@@ -70,40 +70,40 @@ CoinStore resource. See coin_wrapper.move in the Aptos Framework for m ## Constants - + -
const COIN_WRAPPER_NAME: vector<u8> = [67, 79, 73, 78, 95, 87, 82, 65, 80, 80, 69, 82];
+
const COIN_WRAPPER_NAME: vector<u8> = [67, 79, 73, 78, 95, 87, 82, 65, 80, 80, 69, 82];
 
- + ## Function `initialize` Create the coin wrapper account to host all the deposited coins. -
public entry fun initialize()
+
public entry fun initialize()
 
- + ## Function `is_initialized`
#[view]
-public fun is_initialized(): bool
+public fun is_initialized(): bool
 
- + ## Function `wrapper_address` @@ -111,12 +111,12 @@ Return the address of the resource account that stores all deposited coins.
#[view]
-public fun wrapper_address(): address
+public fun wrapper_address(): address
 
- + ## Function `is_supported` @@ -125,12 +125,12 @@ call has been made for that CoinType.
#[view]
-public fun is_supported<CoinType>(): bool
+public fun is_supported<CoinType>(): bool
 
- + ## Function `is_wrapper` @@ -138,12 +138,12 @@ Return true if the given fungible asset is a wrapper fungible asset.
#[view]
-public fun is_wrapper(metadata: object::Object<fungible_asset::Metadata>): bool
+public fun is_wrapper(metadata: object::Object<fungible_asset::Metadata>): bool
 
- + ## Function `get_coin_type` @@ -151,12 +151,12 @@ Return the original CoinType for a specific wrapper fungible asset. This errors
#[view]
-public fun get_coin_type(metadata: object::Object<fungible_asset::Metadata>): string::String
+public fun get_coin_type(metadata: object::Object<fungible_asset::Metadata>): string::String
 
- + ## Function `get_wrapper` @@ -164,12 +164,12 @@ Return the wrapper fungible asset for a specific CoinType. This errors out if th
#[view]
-public fun get_wrapper<CoinType>(): object::Object<fungible_asset::Metadata>
+public fun get_wrapper<CoinType>(): object::Object<fungible_asset::Metadata>
 
- + ## Function `get_original` @@ -180,12 +180,12 @@ fungible asset.
#[view]
-public fun get_original(fungible_asset: object::Object<fungible_asset::Metadata>): string::String
+public fun get_original(fungible_asset: object::Object<fungible_asset::Metadata>): string::String
 
- + ## Function `format_fungible_asset` @@ -193,12 +193,12 @@ Return the address string of a fungible asset (e.g. "0x1234").
#[view]
-public fun format_fungible_asset(fungible_asset: object::Object<fungible_asset::Metadata>): string::String
+public fun format_fungible_asset(fungible_asset: object::Object<fungible_asset::Metadata>): string::String
 
- + ## Function `wrap` @@ -206,12 +206,12 @@ Wrap the given coins into fungible asset. This will also create the fungible ass yet. The coins will be deposited into the main resource account. -
public(friend) fun wrap<CoinType>(coins: coin::Coin<CoinType>): fungible_asset::FungibleAsset
+
public(friend) fun wrap<CoinType>(coins: coin::Coin<CoinType>): fungible_asset::FungibleAsset
 
- + ## Function `unwrap` @@ -220,17 +220,17 @@ the main resource account. This errors out if the given fungible asset is not a wrapper fungible asset. -
public(friend) fun unwrap<CoinType>(fa: fungible_asset::FungibleAsset): coin::Coin<CoinType>
+
public(friend) fun unwrap<CoinType>(fa: fungible_asset::FungibleAsset): coin::Coin<CoinType>
 
- + ## Function `create_fungible_asset` Create the fungible asset wrapper for the given CoinType if it doesn't exist yet. -
public(friend) fun create_fungible_asset<CoinType>(): object::Object<fungible_asset::Metadata>
+
public(friend) fun create_fungible_asset<CoinType>(): object::Object<fungible_asset::Metadata>
 
diff --git a/aave-core/doc/collector.md b/aave-core/doc/collector.md index 8e93b0c..0d68ec8 100644 --- a/aave-core/doc/collector.md +++ b/aave-core/doc/collector.md @@ -1,19 +1,19 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::collector` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::collector` -- [Resource `CollectorData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_collector_CollectorData) +- [Resource `CollectorData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_collector_CollectorData) - [Constants](#@Constants_0) -- [Function `check_is_funds_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_collector_check_is_funds_admin) -- [Function `get_revision`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_collector_get_revision) -- [Function `collector_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_collector_collector_address) -- [Function `collector_object`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_collector_collector_object) -- [Function `deposit`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_collector_deposit) -- [Function `withdraw`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_collector_withdraw) -- [Function `get_collected_fees`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_collector_get_collected_fees) +- [Function `check_is_funds_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_collector_check_is_funds_admin) +- [Function `get_revision`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_collector_get_revision) +- [Function `collector_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_collector_collector_address) +- [Function `collector_object`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_collector_collector_object) +- [Function `deposit`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_collector_deposit) +- [Function `withdraw`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_collector_withdraw) +- [Function `get_collected_fees`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_collector_get_collected_fees)
use 0x1::fungible_asset;
@@ -21,19 +21,19 @@
 use 0x1::primary_fungible_store;
 use 0x1::signer;
 use 0x1::smart_table;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
 
- + ## Resource `CollectorData`
#[resource_group_member(#[group = 0x1::object::ObjectGroup])]
-struct CollectorData has key
+struct CollectorData has key
 
@@ -43,58 +43,58 @@ ## Constants - + -
const NOT_FUNDS_ADMIN: u64 = 1;
+
const NOT_FUNDS_ADMIN: u64 = 1;
 
- + Contract revision -
const REVISION: u64 = 1;
+
const REVISION: u64 = 1;
 
- + Collector name -
const COLLECTOR_NAME: vector<u8> = [65, 65, 86, 69, 95, 67, 79, 76, 76, 69, 67, 84, 79, 82];
+
const COLLECTOR_NAME: vector<u8> = [65, 65, 86, 69, 95, 67, 79, 76, 76, 69, 67, 84, 79, 82];
 
- + Only fungible asset metadata owner can make changes. -
const ERR_NOT_OWNER: u64 = 1;
+
const ERR_NOT_OWNER: u64 = 1;
 
- + ## Function `check_is_funds_admin`
#[view]
-public fun check_is_funds_admin(account: address): bool
+public fun check_is_funds_admin(account: address): bool
 
- + ## Function `get_revision` @@ -102,63 +102,63 @@ Return the revision of the aave token implementation
#[view]
-public fun get_revision(): u64
+public fun get_revision(): u64
 
- + ## Function `collector_address`
#[view]
-public fun collector_address(): address
+public fun collector_address(): address
 
- + ## Function `collector_object`
#[view]
-public fun collector_object(): object::Object<collector::CollectorData>
+public fun collector_object(): object::Object<collector::CollectorData>
 
- + ## Function `deposit` -
public fun deposit(sender: &signer, fa: fungible_asset::FungibleAsset)
+
public fun deposit(sender: &signer, fa: fungible_asset::FungibleAsset)
 
- + ## Function `withdraw` -
public fun withdraw(sender: &signer, asset_metadata: object::Object<fungible_asset::Metadata>, receiver: address, amount: u64)
+
public fun withdraw(sender: &signer, asset_metadata: object::Object<fungible_asset::Metadata>, receiver: address, amount: u64)
 
- + ## Function `get_collected_fees`
#[view]
-public fun get_collected_fees(asset_metadata: object::Object<fungible_asset::Metadata>): u64
+public fun get_collected_fees(asset_metadata: object::Object<fungible_asset::Metadata>): u64
 
diff --git a/aave-core/doc/default_reserve_interest_rate_strategy.md b/aave-core/doc/default_reserve_interest_rate_strategy.md index dfae4e2..5e0a89f 100644 --- a/aave-core/doc/default_reserve_interest_rate_strategy.md +++ b/aave-core/doc/default_reserve_interest_rate_strategy.md @@ -1,182 +1,230 @@ - + + +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::default_reserve_interest_rate_strategy` + +@title default_reserve_interest_rate_strategy module +@author Aave +@notice Implements the calculation of the interest rates depending on the reserve state +@dev The model of interest rate is based on 2 slopes, one before the OPTIMAL_USAGE_RATIO +point of usage and another from that one to 100%. + + +- [Struct `ReserveInterestRateStrategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_ReserveInterestRateStrategy) +- [Resource `DefaultReserveInterestRateStrategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_DefaultReserveInterestRateStrategy) +- [Resource `ReserveInterestRateStrategyMap`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_ReserveInterestRateStrategyMap) +- [Struct `CalcInterestRatesLocalVars`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_CalcInterestRatesLocalVars) +- [Function `init_interest_rate_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_init_interest_rate_strategy) +- [Function `set_reserve_interest_rate_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_set_reserve_interest_rate_strategy) +- [Function `asset_interest_rate_exists`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_asset_interest_rate_exists) +- [Function `get_reserve_interest_rate_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_get_reserve_interest_rate_strategy) +- [Function `get_optimal_usage_ratio`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_get_optimal_usage_ratio) +- [Function `get_max_excess_usage_ratio`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_get_max_excess_usage_ratio) +- [Function `get_variable_rate_slope1`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_get_variable_rate_slope1) +- [Function `get_variable_rate_slope2`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_get_variable_rate_slope2) +- [Function `get_base_variable_borrow_rate`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_get_base_variable_borrow_rate) +- [Function `get_max_variable_borrow_rate`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_get_max_variable_borrow_rate) +- [Function `calculate_interest_rates`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_default_reserve_interest_rate_strategy_calculate_interest_rates) + + +
use 0x1::event;
+use 0x1::signer;
+use 0x1::smart_table;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+
-# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::default_reserve_interest_rate_strategy` + -- [Resource `DefaultReserveInterestRateStrategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_DefaultReserveInterestRateStrategy) -- [Resource `ReserveInterestRateStrategyMap`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_ReserveInterestRateStrategyMap) -- [Struct `CalcInterestRatesLocalVars`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_CalcInterestRatesLocalVars) -- [Function `init_interest_rate_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_init_interest_rate_strategy) -- [Function `set_reserve_interest_rate_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_set_reserve_interest_rate_strategy) -- [Function `get_reserve_interest_rate_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_get_reserve_interest_rate_strategy) -- [Function `get_optimal_usage_ratio`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_get_optimal_usage_ratio) -- [Function `get_max_excess_usage_ratio`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_get_max_excess_usage_ratio) -- [Function `get_variable_rate_slope1`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_get_variable_rate_slope1) -- [Function `get_variable_rate_slope2`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_get_variable_rate_slope2) -- [Function `get_base_variable_borrow_rate`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_get_base_variable_borrow_rate) -- [Function `get_max_variable_borrow_rate`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_get_max_variable_borrow_rate) -- [Function `calculate_interest_rates`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_default_reserve_interest_rate_strategy_calculate_interest_rates) +## Struct `ReserveInterestRateStrategy` -
use 0x1::signer;
-use 0x1::smart_table;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
+
+
#[event]
+struct ReserveInterestRateStrategy has drop, store
 
- + ## Resource `DefaultReserveInterestRateStrategy` -
struct DefaultReserveInterestRateStrategy has copy, drop, store, key
+
struct DefaultReserveInterestRateStrategy has copy, drop, store, key
 
- + ## Resource `ReserveInterestRateStrategyMap` -
struct ReserveInterestRateStrategyMap has key
+
struct ReserveInterestRateStrategyMap has key
 
- + ## Struct `CalcInterestRatesLocalVars` -
struct CalcInterestRatesLocalVars has drop
+
struct CalcInterestRatesLocalVars has drop
 
- + ## Function `init_interest_rate_strategy` +@notice Initializes the interest rate strategy -
public(friend) fun init_interest_rate_strategy(account: &signer)
+
public(friend) fun init_interest_rate_strategy(account: &signer)
 
- + ## Function `set_reserve_interest_rate_strategy` +@notice Sets the interest rate strategy of a reserve +@param asset The address of the reserve +@param optimal_usage_ratio The optimal usage ratio +@param base_variable_borrow_rate The base variable borrow rate +@param variable_rate_slope1 The variable rate slope below optimal usage ratio +@param variable_rate_slope2 The variable rate slope above optimal usage ratio + + +
public entry fun set_reserve_interest_rate_strategy(account: &signer, asset: address, optimal_usage_ratio: u256, base_variable_borrow_rate: u256, variable_rate_slope1: u256, variable_rate_slope2: u256)
+
+ + + + + +## Function `asset_interest_rate_exists` + -
public entry fun set_reserve_interest_rate_strategy(account: &signer, asset: address, optimal_usage_ratio: u256, base_variable_borrow_rate: u256, variable_rate_slope1: u256, variable_rate_slope2: u256)
+
public fun asset_interest_rate_exists(asset: address)
 
- + ## Function `get_reserve_interest_rate_strategy`
#[view]
-public fun get_reserve_interest_rate_strategy(asset: address): default_reserve_interest_rate_strategy::DefaultReserveInterestRateStrategy
+public fun get_reserve_interest_rate_strategy(asset: address): default_reserve_interest_rate_strategy::DefaultReserveInterestRateStrategy
 
- + ## Function `get_optimal_usage_ratio`
#[view]
-public fun get_optimal_usage_ratio(asset: address): u256
+public fun get_optimal_usage_ratio(asset: address): u256
 
- + ## Function `get_max_excess_usage_ratio`
#[view]
-public fun get_max_excess_usage_ratio(asset: address): u256
+public fun get_max_excess_usage_ratio(asset: address): u256
 
- + ## Function `get_variable_rate_slope1`
#[view]
-public fun get_variable_rate_slope1(asset: address): u256
+public fun get_variable_rate_slope1(asset: address): u256
 
- + ## Function `get_variable_rate_slope2`
#[view]
-public fun get_variable_rate_slope2(asset: address): u256
+public fun get_variable_rate_slope2(asset: address): u256
 
- + ## Function `get_base_variable_borrow_rate`
#[view]
-public fun get_base_variable_borrow_rate(asset: address): u256
+public fun get_base_variable_borrow_rate(asset: address): u256
 
- + ## Function `get_max_variable_borrow_rate`
#[view]
-public fun get_max_variable_borrow_rate(asset: address): u256
+public fun get_max_variable_borrow_rate(asset: address): u256
 
- + ## Function `calculate_interest_rates` +@notice Calculates the interest rates depending on the reserve's state and configurations +@param unbacked The amount of unbacked liquidity +@param liquidity_added The amount of liquidity added +@param liquidity_taken The amount of liquidity taken +@param total_variable_debt The total variable debt of the reserve +@param reserve_factor The reserve factor +@param reserve The address of the reserve +@param a_token_address The address of the aToken +@return current_liquidity_rate The liquidity rate expressed in rays +@return current_variable_borrow_rate The variable borrow rate expressed in rays
#[view]
-public fun calculate_interest_rates(unbacked: u256, liquidity_added: u256, liquidity_taken: u256, total_variable_debt: u256, reserve_factor: u256, reserve: address, a_token_address: address): (u256, u256)
+public fun calculate_interest_rates(unbacked: u256, liquidity_added: u256, liquidity_taken: u256, total_variable_debt: u256, reserve_factor: u256, reserve: address, a_token_address: address): (u256, u256)
 
diff --git a/aave-core/doc/eac_aggregator_proxy.md b/aave-core/doc/eac_aggregator_proxy.md index 891de16..1fa2bce 100644 --- a/aave-core/doc/eac_aggregator_proxy.md +++ b/aave-core/doc/eac_aggregator_proxy.md @@ -1,84 +1,84 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::eac_aggregator_proxy` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::eac_aggregator_proxy` -- [Resource `MockEacAggregatorProxy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_eac_aggregator_proxy_MockEacAggregatorProxy) -- [Struct `AnswerUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_eac_aggregator_proxy_AnswerUpdated) -- [Struct `NewRound`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_eac_aggregator_proxy_NewRound) -- [Function `decimals`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_eac_aggregator_proxy_decimals) -- [Function `latest_answer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_eac_aggregator_proxy_latest_answer) -- [Function `create_eac_aggregator_proxy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_eac_aggregator_proxy_create_eac_aggregator_proxy) +- [Resource `MockEacAggregatorProxy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_eac_aggregator_proxy_MockEacAggregatorProxy) +- [Struct `AnswerUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_eac_aggregator_proxy_AnswerUpdated) +- [Struct `NewRound`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_eac_aggregator_proxy_NewRound) +- [Function `decimals`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_eac_aggregator_proxy_decimals) +- [Function `latest_answer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_eac_aggregator_proxy_latest_answer) +- [Function `create_eac_aggregator_proxy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_eac_aggregator_proxy_create_eac_aggregator_proxy)
- + ## Resource `MockEacAggregatorProxy` -
struct MockEacAggregatorProxy has copy, drop, store, key
+
struct MockEacAggregatorProxy has copy, drop, store, key
 
- + ## Struct `AnswerUpdated`
#[event]
-struct AnswerUpdated has drop, store
+struct AnswerUpdated has drop, store
 
- + ## Struct `NewRound`
#[event]
-struct NewRound has drop, store
+struct NewRound has drop, store
 
- + ## Function `decimals` -
public fun decimals(): u8
+
public fun decimals(): u8
 
- + ## Function `latest_answer` -
public fun latest_answer(): u256
+
public fun latest_answer(): u256
 
- + ## Function `create_eac_aggregator_proxy` -
public fun create_eac_aggregator_proxy(): eac_aggregator_proxy::MockEacAggregatorProxy
+
public fun create_eac_aggregator_proxy(): eac_aggregator_proxy::MockEacAggregatorProxy
 
diff --git a/aave-core/doc/ecosystem_reserve_v2.md b/aave-core/doc/ecosystem_reserve_v2.md index 8b85ae1..cfa5adb 100644 --- a/aave-core/doc/ecosystem_reserve_v2.md +++ b/aave-core/doc/ecosystem_reserve_v2.md @@ -1,20 +1,20 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::ecosystem_reserve_v2` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::ecosystem_reserve_v2` -- [Resource `EcosystemReserveV2Data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ecosystem_reserve_v2_EcosystemReserveV2Data) -- [Struct `CreateStream`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ecosystem_reserve_v2_CreateStream) -- [Struct `WithdrawFromStream`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ecosystem_reserve_v2_WithdrawFromStream) -- [Struct `CancelStream`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ecosystem_reserve_v2_CancelStream) +- [Resource `EcosystemReserveV2Data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ecosystem_reserve_v2_EcosystemReserveV2Data) +- [Struct `CreateStream`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ecosystem_reserve_v2_CreateStream) +- [Struct `WithdrawFromStream`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ecosystem_reserve_v2_WithdrawFromStream) +- [Struct `CancelStream`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ecosystem_reserve_v2_CancelStream) - [Constants](#@Constants_0) -- [Function `initialize`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ecosystem_reserve_v2_initialize) -- [Function `ecosystem_reserve_v2_data_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ecosystem_reserve_v2_ecosystem_reserve_v2_data_address) -- [Function `ecosystem_reserve_v2_data_object`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ecosystem_reserve_v2_ecosystem_reserve_v2_data_object) -- [Function `delta_of`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ecosystem_reserve_v2_delta_of) -- [Function `balance_of`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ecosystem_reserve_v2_balance_of) +- [Function `initialize`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ecosystem_reserve_v2_initialize) +- [Function `ecosystem_reserve_v2_data_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ecosystem_reserve_v2_ecosystem_reserve_v2_data_address) +- [Function `ecosystem_reserve_v2_data_object`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ecosystem_reserve_v2_ecosystem_reserve_v2_data_object) +- [Function `delta_of`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ecosystem_reserve_v2_delta_of) +- [Function `balance_of`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ecosystem_reserve_v2_balance_of)
use 0x1::event;
@@ -22,57 +22,57 @@
 use 0x1::signer;
 use 0x1::smart_table;
 use 0x1::timestamp;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::admin_controlled_ecosystem_reserve;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::stream;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::admin_controlled_ecosystem_reserve;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::stream;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
 
- + ## Resource `EcosystemReserveV2Data` -
struct EcosystemReserveV2Data has key
+
struct EcosystemReserveV2Data has key
 
- + ## Struct `CreateStream`
#[event]
-struct CreateStream has drop, store
+struct CreateStream has drop, store
 
- + ## Struct `WithdrawFromStream`
#[event]
-struct WithdrawFromStream has drop, store
+struct WithdrawFromStream has drop, store
 
- + ## Struct `CancelStream`
#[event]
-struct CancelStream has drop, store
+struct CancelStream has drop, store
 
@@ -82,193 +82,193 @@ ## Constants - + -
const EROLE_NOT_EXISTS: u64 = 1;
+
const EROLE_NOT_EXISTS: u64 = 1;
 
- + -
const NOT_FUNDS_ADMIN: u64 = 1;
+
const NOT_FUNDS_ADMIN: u64 = 3;
 
- + -
const TEST_FAILED: u64 = 2;
+
const TEST_FAILED: u64 = 2;
 
- + -
const TEST_SUCCESS: u64 = 1;
+
const TEST_SUCCESS: u64 = 1;
 
- + -
const EAMOUNT_EXCEEDS_THE_AVAILABLE_BALANCE: u64 = 1;
+
const EAMOUNT_EXCEEDS_THE_AVAILABLE_BALANCE: u64 = 12;
 
- + -
const EAMOUNT_IS_ZERO: u64 = 1;
+
const EAMOUNT_IS_ZERO: u64 = 11;
 
- + -
const ECOSYSTEM_RESERVE_V2_NAME: vector<u8> = [65, 65, 86, 69, 95, 69, 67, 79, 83, 89, 83, 84, 69, 77, 95, 82, 69, 83, 69, 82, 86, 69, 95, 86, 50];
+
const ECOSYSTEM_RESERVE_V2_NAME: vector<u8> = [65, 65, 86, 69, 95, 69, 67, 79, 83, 89, 83, 84, 69, 77, 95, 82, 69, 83, 69, 82, 86, 69, 95, 86, 50];
 
- + -
const EDEPOSIT_IS_ZERO: u64 = 1;
+
const EDEPOSIT_IS_ZERO: u64 = 6;
 
- + -
const EDEPOSIT_NOT_MULTIPLE_OF_TIME_DELTA: u64 = 1;
+
const EDEPOSIT_NOT_MULTIPLE_OF_TIME_DELTA: u64 = 10;
 
- + -
const EDEPOSIT_SMALLER_THAN_TIME_DELTA: u64 = 1;
+
const EDEPOSIT_SMALLER_THAN_TIME_DELTA: u64 = 9;
 
- + -
const ESTART_TIME_BEFORE_BLOCK_TIMESTAMP: u64 = 1;
+
const ESTART_TIME_BEFORE_BLOCK_TIMESTAMP: u64 = 7;
 
- + -
const ESTOP_TIME_BEFORE_THE_START_TIME: u64 = 1;
+
const ESTOP_TIME_BEFORE_THE_START_TIME: u64 = 8;
 
- + -
const ESTREAM_NOT_EXISTS: u64 = 1;
+
const ESTREAM_NOT_EXISTS: u64 = 2;
 
- + -
const ESTREAM_TO_THE_CALLER: u64 = 1;
+
const ESTREAM_TO_THE_CALLER: u64 = 5;
 
- + -
const ESTREAM_TO_THE_CONTRACT_ITSELF: u64 = 1;
+
const ESTREAM_TO_THE_CONTRACT_ITSELF: u64 = 4;
 
- + ## Function `initialize` -
public fun initialize(sender: &signer)
+
public fun initialize(sender: &signer)
 
- + ## Function `ecosystem_reserve_v2_data_address`
#[view]
-public fun ecosystem_reserve_v2_data_address(): address
+public fun ecosystem_reserve_v2_data_address(): address
 
- + ## Function `ecosystem_reserve_v2_data_object`
#[view]
-public fun ecosystem_reserve_v2_data_object(): object::Object<ecosystem_reserve_v2::EcosystemReserveV2Data>
+public fun ecosystem_reserve_v2_data_object(): object::Object<ecosystem_reserve_v2::EcosystemReserveV2Data>
 
- + ## Function `delta_of`
#[view]
-public fun delta_of(stream_id: u256): u256
+public fun delta_of(stream_id: u256): u256
 
- + ## Function `balance_of` -
public fun balance_of(stream_id: u256, who: address): u256
+
public fun balance_of(stream_id: u256, who: address): u256
 
diff --git a/aave-core/doc/emission_manager.md b/aave-core/doc/emission_manager.md index bd58cb9..038226b 100644 --- a/aave-core/doc/emission_manager.md +++ b/aave-core/doc/emission_manager.md @@ -1,60 +1,60 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::emission_manager` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::emission_manager` -- [Resource `EmissionManagerData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_EmissionManagerData) -- [Struct `EmissionAdminUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_EmissionAdminUpdated) +- [Resource `EmissionManagerData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_EmissionManagerData) +- [Struct `EmissionAdminUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_EmissionAdminUpdated) - [Constants](#@Constants_0) -- [Function `initialize`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_initialize) -- [Function `emission_manager_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_emission_manager_address) -- [Function `emission_manager_object`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_emission_manager_object) -- [Function `configure_assets`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_configure_assets) -- [Function `set_pull_rewards_transfer_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_set_pull_rewards_transfer_strategy) -- [Function `set_staked_token_transfer_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_set_staked_token_transfer_strategy) -- [Function `set_reward_oracle`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_set_reward_oracle) -- [Function `set_distribution_end`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_set_distribution_end) -- [Function `set_emission_per_second`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_set_emission_per_second) -- [Function `set_claimer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_set_claimer) -- [Function `set_emission_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_set_emission_admin) -- [Function `set_rewards_controller`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_set_rewards_controller) -- [Function `get_rewards_controller`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_get_rewards_controller) -- [Function `get_emission_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emission_manager_get_emission_admin) +- [Function `initialize`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_initialize) +- [Function `emission_manager_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_emission_manager_address) +- [Function `emission_manager_object`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_emission_manager_object) +- [Function `configure_assets`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_configure_assets) +- [Function `set_pull_rewards_transfer_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_set_pull_rewards_transfer_strategy) +- [Function `set_staked_token_transfer_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_set_staked_token_transfer_strategy) +- [Function `set_reward_oracle`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_set_reward_oracle) +- [Function `set_distribution_end`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_set_distribution_end) +- [Function `set_emission_per_second`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_set_emission_per_second) +- [Function `set_claimer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_set_claimer) +- [Function `set_emission_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_set_emission_admin) +- [Function `set_rewards_controller`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_set_rewards_controller) +- [Function `get_rewards_controller`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_get_rewards_controller) +- [Function `get_emission_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emission_manager_get_emission_admin)
use 0x1::event;
 use 0x1::object;
 use 0x1::signer;
 use 0x1::smart_table;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::rewards_controller;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::transfer_strategy;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::rewards_controller;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::transfer_strategy;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle;
 
- + ## Resource `EmissionManagerData`
#[resource_group_member(#[group = 0x1::object::ObjectGroup])]
-struct EmissionManagerData has key
+struct EmissionManagerData has key
 
- + ## Struct `EmissionAdminUpdated`
#[event]
-struct EmissionAdminUpdated has drop, store
+struct EmissionAdminUpdated has drop, store
 
@@ -64,192 +64,192 @@ ## Constants - + -
const ENOT_MANAGEMENT: u64 = 1;
+
const ENOT_MANAGEMENT: u64 = 1;
 
- + -
const EMISSION_MANAGER_NAME: vector<u8> = [69, 77, 73, 83, 83, 73, 79, 78, 95, 77, 65, 78, 65, 71, 69, 82];
+
const EMISSION_MANAGER_NAME: vector<u8> = [69, 77, 73, 83, 83, 73, 79, 78, 95, 77, 65, 78, 65, 71, 69, 82];
 
- + -
const NOT_EMISSION_ADMIN: u64 = 1;
+
const NOT_EMISSION_ADMIN: u64 = 2;
 
- + -
const ONLY_EMISSION_ADMIN: u64 = 1;
+
const ONLY_EMISSION_ADMIN: u64 = 3;
 
- + ## Function `initialize` -
public fun initialize(sender: &signer, rewards_controller: address)
+
public fun initialize(sender: &signer, rewards_controller: address)
 
- + ## Function `emission_manager_address`
#[view]
-public fun emission_manager_address(): address
+public fun emission_manager_address(): address
 
- + ## Function `emission_manager_object`
#[view]
-public fun emission_manager_object(): object::Object<emission_manager::EmissionManagerData>
+public fun emission_manager_object(): object::Object<emission_manager::EmissionManagerData>
 
- + ## Function `configure_assets` -
public fun configure_assets(account: &signer, config: vector<transfer_strategy::RewardsConfigInput>)
+
public fun configure_assets(account: &signer, config: vector<transfer_strategy::RewardsConfigInput>)
 
- + ## Function `set_pull_rewards_transfer_strategy` -
public fun set_pull_rewards_transfer_strategy(caller: &signer, reward: address, pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy)
+
public fun set_pull_rewards_transfer_strategy(caller: &signer, reward: address, pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy)
 
- + ## Function `set_staked_token_transfer_strategy` -
public fun set_staked_token_transfer_strategy(caller: &signer, reward: address, staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy)
+
public fun set_staked_token_transfer_strategy(caller: &signer, reward: address, staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy)
 
- + ## Function `set_reward_oracle` -
public fun set_reward_oracle(caller: &signer, reward: address, reward_oracle: oracle::RewardOracle)
+
public fun set_reward_oracle(caller: &signer, reward: address, reward_oracle: oracle::RewardOracle)
 
- + ## Function `set_distribution_end` -
public fun set_distribution_end(caller: &signer, asset: address, reward: address, new_distribution_end: u32)
+
public fun set_distribution_end(caller: &signer, asset: address, reward: address, new_distribution_end: u32)
 
- + ## Function `set_emission_per_second` -
public fun set_emission_per_second(caller: &signer, asset: address, rewards: vector<address>, new_emissions_per_second: vector<u128>)
+
public fun set_emission_per_second(caller: &signer, asset: address, rewards: vector<address>, new_emissions_per_second: vector<u128>)
 
- + ## Function `set_claimer` -
public fun set_claimer(account: &signer, user: address, claimer: address)
+
public fun set_claimer(account: &signer, user: address, claimer: address)
 
- + ## Function `set_emission_admin` -
public fun set_emission_admin(account: &signer, reward: address, new_admin: address)
+
public fun set_emission_admin(account: &signer, reward: address, new_admin: address)
 
- + ## Function `set_rewards_controller` -
public fun set_rewards_controller(account: &signer, controller: address)
+
public fun set_rewards_controller(account: &signer, controller: address)
 
- + ## Function `get_rewards_controller` -
public fun get_rewards_controller(): address
+
public fun get_rewards_controller(): address
 
- + ## Function `get_emission_admin` -
public fun get_emission_admin(reward: address): address
+
public fun get_emission_admin(reward: address): address
 
diff --git a/aave-core/doc/emode_logic.md b/aave-core/doc/emode_logic.md index 26f64d8..4b3981a 100644 --- a/aave-core/doc/emode_logic.md +++ b/aave-core/doc/emode_logic.md @@ -1,86 +1,94 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::emode_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::emode_logic` +@title emode_logic module +@author Aave +@notice Implements the base logic for all the actions related to the eMode -- [Struct `UserEModeSet`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_UserEModeSet) -- [Struct `EModeCategory`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_EModeCategory) -- [Resource `EModeCategoryList`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_EModeCategoryList) -- [Resource `UsersEmodeCategory`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_UsersEmodeCategory) +- [Struct `UserEModeSet`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_UserEModeSet) +- [Struct `EModeCategory`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_EModeCategory) +- [Resource `EModeCategoryList`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_EModeCategoryList) +- [Resource `UsersEmodeCategory`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_UsersEmodeCategory) - [Constants](#@Constants_0) -- [Function `init_emode`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_init_emode) -- [Function `set_user_emode`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_set_user_emode) -- [Function `get_user_emode`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_user_emode) -- [Function `get_emode_e_mode_price_source`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_e_mode_price_source) -- [Function `get_emode_configuration`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_configuration) -- [Function `get_emode_e_mode_label`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_e_mode_label) -- [Function `get_emode_e_mode_liquidation_bonus`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_e_mode_liquidation_bonus) -- [Function `configure_emode_category`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_configure_emode_category) -- [Function `is_in_emode_category`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_is_in_emode_category) -- [Function `get_emode_category_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_category_data) -- [Function `get_emode_category_ltv`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_category_ltv) -- [Function `get_emode_category_liquidation_threshold`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_category_liquidation_threshold) -- [Function `get_emode_category_liquidation_bonus`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_category_liquidation_bonus) -- [Function `get_emode_category_price_source`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_category_price_source) -- [Function `get_emode_category_label`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_emode_logic_get_emode_category_label) +- [Function `init_emode`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_init_emode) +- [Function `set_user_emode`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_set_user_emode) +- [Function `get_user_emode`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_user_emode) +- [Function `get_emode_e_mode_price_source`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_e_mode_price_source) +- [Function `get_emode_configuration`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_configuration) +- [Function `get_emode_e_mode_label`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_e_mode_label) +- [Function `get_emode_e_mode_liquidation_bonus`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_e_mode_liquidation_bonus) +- [Function `configure_emode_category`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_configure_emode_category) +- [Function `is_in_emode_category`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_is_in_emode_category) +- [Function `get_emode_category_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_category_data) +- [Function `get_emode_category_ltv`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_category_ltv) +- [Function `get_emode_category_liquidation_threshold`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_category_liquidation_threshold) +- [Function `get_emode_category_liquidation_bonus`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_category_liquidation_bonus) +- [Function `get_emode_category_price_source`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_category_price_source) +- [Function `get_emode_category_label`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_emode_logic_get_emode_category_label)
use 0x1::event;
 use 0x1::signer;
 use 0x1::smart_table;
 use 0x1::string;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool_validation;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool_validation;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `UserEModeSet` +@dev Emitted when the user selects a certain asset category for eMode +@param user The address of the user +@param category_id The category id
#[event]
-struct UserEModeSet has drop, store
+struct UserEModeSet has drop, store
 
- + ## Struct `EModeCategory` -
struct EModeCategory has copy, drop, store
+
struct EModeCategory has copy, drop, store
 
- + ## Resource `EModeCategoryList` +List of eMode categories as a map (emode_category_id => EModeCategory). -
struct EModeCategoryList has key
+
struct EModeCategoryList has key
 
- + ## Resource `UsersEmodeCategory` +Map of users address and their eMode category (user_address => emode_category_id) -
struct UsersEmodeCategory has store, key
+
struct UsersEmodeCategory has store, key
 
@@ -90,176 +98,230 @@ ## Constants - + -
const EMPTY_STRING: vector<u8> = [];
+
const EMPTY_STRING: vector<u8> = [];
 
- + ## Function `init_emode` +@notice Initializes the eMode -
public(friend) fun init_emode(account: &signer)
+
public(friend) fun init_emode(account: &signer)
 
- + ## Function `set_user_emode` +@notice Updates the user efficiency mode category +@dev Will revert if user is borrowing non-compatible asset or change will drop HF < HEALTH_FACTOR_LIQUIDATION_THRESHOLD +@dev Emits the UserEModeSet event +@param category_id The state of all users efficiency mode category -
public entry fun set_user_emode(account: &signer, category_id: u8)
+
public entry fun set_user_emode(account: &signer, category_id: u8)
 
- + ## Function `get_user_emode` +@notice Returns the eMode the user is using +@param user The address of the user +@return The eMode id
#[view]
-public fun get_user_emode(user: address): u256
+public fun get_user_emode(user: address): u256
 
- + ## Function `get_emode_e_mode_price_source` +@notice Get the price source of the eMode category +@param user_emode_category The user eMode category +@return The price source of the eMode category -
public fun get_emode_e_mode_price_source(user_emode_category: u8): address
+
public fun get_emode_e_mode_price_source(user_emode_category: u8): address
 
- + ## Function `get_emode_configuration` +@notice Gets the eMode configuration and calculates the eMode asset price if a custom oracle is configured +@dev The eMode asset price returned is 0 if no oracle is specified +@param category The user eMode category +@return The eMode ltv +@return The eMode liquidation threshold +@return The eMode asset price -
public fun get_emode_configuration(user_emode_category: u8): (u256, u256, u256)
+
public fun get_emode_configuration(user_emode_category: u8): (u256, u256, u256)
 
- + ## Function `get_emode_e_mode_label` +@notice Gets the eMode category label +@param user_emode_category The user eMode category +@return The label of the eMode category -
public fun get_emode_e_mode_label(user_emode_category: u8): string::String
+
public fun get_emode_e_mode_label(user_emode_category: u8): string::String
 
- + ## Function `get_emode_e_mode_liquidation_bonus` +@notice Gets the eMode category liquidation_bonus +@param user_emode_category The user eMode category +@return The liquidation bonus of the eMode category -
public fun get_emode_e_mode_liquidation_bonus(user_emode_category: u8): u16
+
public fun get_emode_e_mode_liquidation_bonus(user_emode_category: u8): u16
 
- + ## Function `configure_emode_category` +@notice Configures a new category for the eMode. +@dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category. +The category 0 is reserved as it's the default for volatile assets +@param id The id of the category +@param ltv The loan to value ratio +@param liquidation_threshold The liquidation threshold +@param liquidation_bonus The liquidation bonus +@param price_source The address of the oracle to override the individual assets price oracles +@param label The label of the category -
public(friend) fun configure_emode_category(id: u8, ltv: u16, liquidation_threshold: u16, liquidation_bonus: u16, price_source: address, label: string::String)
+
public(friend) fun configure_emode_category(id: u8, ltv: u16, liquidation_threshold: u16, liquidation_bonus: u16, price_source: address, label: string::String)
 
- + ## Function `is_in_emode_category` +@notice Checks if eMode is active for a user and if yes, if the asset belongs to the eMode category chosen +@param emode_user_category The user eMode category +@param emode_asset_category The asset eMode category +@return True if eMode is active and the asset belongs to the eMode category chosen by the user, false otherwise -
public fun is_in_emode_category(emode_user_category: u256, emode_assert_category: u256): bool
+
public fun is_in_emode_category(emode_user_category: u256, emode_assert_category: u256): bool
 
- + ## Function `get_emode_category_data` +@notice Returns the data of an eMode category +@param id The id of the category +@return The configuration data of the category
#[view]
-public fun get_emode_category_data(id: u8): emode_logic::EModeCategory
+public fun get_emode_category_data(id: u8): emode_logic::EModeCategory
 
- + ## Function `get_emode_category_ltv` +@notice Get the ltv of the eMode category +@param emode_category The eMode category +@return The ltv of the eMode category -
public fun get_emode_category_ltv(emode_category: &emode_logic::EModeCategory): u16
+
public fun get_emode_category_ltv(emode_category: &emode_logic::EModeCategory): u16
 
- + ## Function `get_emode_category_liquidation_threshold` +@notice Get the liquidation threshold of the eMode category +@param emode_category The eMode category +@return The liquidation threshold of the eMode category -
public fun get_emode_category_liquidation_threshold(emode_category: &emode_logic::EModeCategory): u16
+
public fun get_emode_category_liquidation_threshold(emode_category: &emode_logic::EModeCategory): u16
 
- + ## Function `get_emode_category_liquidation_bonus` +@notice Get the liquidation bonus of the eMode category +@param emode_category The eMode category +@return The liquidation bonus of the eMode category -
public fun get_emode_category_liquidation_bonus(emode_category: &emode_logic::EModeCategory): u16
+
public fun get_emode_category_liquidation_bonus(emode_category: &emode_logic::EModeCategory): u16
 
- + ## Function `get_emode_category_price_source` +@notice Get the price source of the eMode category +@param emode_category The eMode category +@return The price source of the eMode category -
public fun get_emode_category_price_source(emode_category: &emode_logic::EModeCategory): address
+
public fun get_emode_category_price_source(emode_category: &emode_logic::EModeCategory): address
 
- + ## Function `get_emode_category_label` +@notice Get the label of the eMode category +@param emode_category The eMode category +@return The label of the eMode category -
public fun get_emode_category_label(emode_category: &emode_logic::EModeCategory): string::String
+
public fun get_emode_category_label(emode_category: &emode_logic::EModeCategory): string::String
 
diff --git a/aave-core/doc/flash_loan.md b/aave-core/doc/flash_loan.md index 2365840..c5cc34c 100644 --- a/aave-core/doc/flash_loan.md +++ b/aave-core/doc/flash_loan.md @@ -1,109 +1,167 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::flashloan_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::flashloan_logic` +@title flashloan_logic module +@author Aave +@notice Implements the logic for the flash loans -- [Struct `FlashLoan`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_flashloan_logic_FlashLoan) -- [Struct `FlashLoanLocalVars`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_flashloan_logic_FlashLoanLocalVars) -- [Struct `SimpleFlashLoansReceipt`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_flashloan_logic_SimpleFlashLoansReceipt) -- [Struct `ComplexFlashLoansReceipt`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_flashloan_logic_ComplexFlashLoansReceipt) -- [Struct `FlashLoanRepaymentParams`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_flashloan_logic_FlashLoanRepaymentParams) -- [Function `flashloan`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_flashloan_logic_flashloan) -- [Function `flash_loan_simple`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_flashloan_logic_flash_loan_simple) +- [Struct `FlashLoan`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_flashloan_logic_FlashLoan) +- [Struct `FlashLoanLocalVars`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_flashloan_logic_FlashLoanLocalVars) +- [Struct `SimpleFlashLoansReceipt`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_flashloan_logic_SimpleFlashLoansReceipt) +- [Struct `ComplexFlashLoansReceipt`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_flashloan_logic_ComplexFlashLoansReceipt) +- [Struct `FlashLoanRepaymentParams`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_flashloan_logic_FlashLoanRepaymentParams) +- [Function `flashloan`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_flashloan_logic_flashloan) +- [Function `pay_flash_loan_complex`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_flashloan_logic_pay_flash_loan_complex) +- [Function `flash_loan_simple`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_flashloan_logic_flash_loan_simple) +- [Function `pay_flash_loan_simple`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_flashloan_logic_pay_flash_loan_simple)
use 0x1::event;
 use 0x1::option;
 use 0x1::signer;
 use 0x1::vector;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::borrow_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::validation_logic;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::borrow_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::validation_logic;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `FlashLoan` +@dev Emitted on flashLoan() +@param target The address of the flash loan receiver contract +@param initiator The address initiating the flash loan +@param asset The address of the asset being flash borrowed +@param amount The amount flash borrowed +@param interest_rate_mode The flashloan mode: 0 for regular flashloan, 2 for Variable debt +@param premium The fee flash borrowed +@param referral_code The referral code used
#[event]
-struct FlashLoan has drop, store
+struct FlashLoan has drop, store
 
- + ## Struct `FlashLoanLocalVars` +Helper struct for internal variables used in the executeFlashLoan function -
struct FlashLoanLocalVars has copy, drop
+
struct FlashLoanLocalVars has copy, drop
 
- + ## Struct `SimpleFlashLoansReceipt` -
struct SimpleFlashLoansReceipt
+
struct SimpleFlashLoansReceipt
 
- + ## Struct `ComplexFlashLoansReceipt` -
struct ComplexFlashLoansReceipt
+
struct ComplexFlashLoansReceipt
 
- + ## Struct `FlashLoanRepaymentParams` -
struct FlashLoanRepaymentParams has drop
+
struct FlashLoanRepaymentParams has drop
 
- + ## Function `flashloan` +@notice Allows smartcontracts to access the liquidity of the pool within one transaction, +as long as the amount taken plus a fee is returned. +@dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept +into consideration. For further details please visit https://docs.aave.com/developers/ +@param receiver_address The address of the contract receiving the funds +@param assets The addresses of the assets being flash-borrowed +@param amounts The amounts of the assets being flash-borrowed +@param interest_rate_modes Types of the debt to open if the flash loan is not returned: +0 -> Don't open any debt, just revert if funds can't be transferred from the receiver +2 -> Open debt at variable rate for the value of the amount flash-borrowed to the onBehalfOf address +@param on_behalf_of The address that will receive the debt in the case of using on modes 2 +@param referral_code The code used to register the integrator originating the operation, for potential rewards. +0 if the action is executed directly by the user, without any middle-man + + +
public fun flashloan(account: &signer, receiver_address: address, assets: vector<address>, amounts: vector<u256>, interest_rate_modes: vector<u8>, on_behalf_of: address, referral_code: u16): vector<flashloan_logic::ComplexFlashLoansReceipt>
+
+ + + + +## Function `pay_flash_loan_complex` -
public entry fun flashloan(account: &signer, receiver_address: address, assets: vector<address>, amounts: vector<u256>, interest_rate_modes: vector<u8>, on_behalf_of: address, referral_code: u16)
+
+
+
public fun pay_flash_loan_complex(account: &signer, flashloan_receipts: vector<flashloan_logic::ComplexFlashLoansReceipt>)
 
- + ## Function `flash_loan_simple` +@notice Allows smartcontracts to access the liquidity of the pool within one transaction, +as long as the amount taken plus a fee is returned. +@dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept +into consideration. For further details please visit https://docs.aave.com/developers/ +@param receiver_address The address of the contract receiving the funds +@param asset The address of the asset being flash-borrowed +@param amount The amount of the asset being flash-borrowed +@param referral_code The code used to register the integrator originating the operation, for potential rewards. +0 if the action is executed directly by the user, without any middle-man + + +
public fun flash_loan_simple(account: &signer, receiver_address: address, asset: address, amount: u256, referral_code: u16): flashloan_logic::SimpleFlashLoansReceipt
+
+ + + + + +## Function `pay_flash_loan_simple` + -
public entry fun flash_loan_simple(account: &signer, receiver_address: address, asset: address, amount: u256, referral_code: u16)
+
public fun pay_flash_loan_simple(account: &signer, flashloan_receipt: flashloan_logic::SimpleFlashLoansReceipt)
 
diff --git a/aave-core/doc/generic_logic.md b/aave-core/doc/generic_logic.md index dc46cc1..565f5c3 100644 --- a/aave-core/doc/generic_logic.md +++ b/aave-core/doc/generic_logic.md @@ -1,54 +1,79 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::generic_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::generic_logic` +@title GenericLogic module +@author Aave +@notice Implements protocol-level logic to calculate and validate the state of a user -- [Struct `CalculateUserAccountDataVars`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_generic_logic_CalculateUserAccountDataVars) -- [Function `calculate_user_account_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_generic_logic_calculate_user_account_data) -- [Function `calculate_available_borrows`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_generic_logic_calculate_available_borrows) +- [Struct `CalculateUserAccountDataVars`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_generic_logic_CalculateUserAccountDataVars) +- [Function `calculate_user_account_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_generic_logic_calculate_user_account_data) +- [Function `calculate_available_borrows`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_generic_logic_calculate_available_borrows) -
use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::variable_token_factory;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle;
+
use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::variable_debt_token_factory;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `CalculateUserAccountDataVars` -
struct CalculateUserAccountDataVars has drop
+
struct CalculateUserAccountDataVars has drop
 
- + ## Function `calculate_user_account_data` - - -
public fun calculate_user_account_data(reserves_count: u256, user_config_map: &user::UserConfigurationMap, user: address, user_emode_category: u8, emode_ltv: u256, emode_liq_threshold: u256, emode_asset_price: u256): (u256, u256, u256, u256, u256, bool)
+@notice Calculates the user data across the reserves.
+@dev It includes the total liquidity/collateral/borrow balances in the base currency used by the price feed,
+the average Loan To Value, the average Liquidation Ratio, and the Health factor.
+@param params reserves_count The number of reserves
+@param params user_config_map The user configuration map
+@param params user The address of the user
+@param params user_emode_category The category of the user in the emode
+@param params emode_ltv The ltv of the user in the emode
+@param params emode_liq_threshold The liquidation threshold of the user in the emode
+@param params emode_asset_price The price of the asset in the emode
+@return The total collateral of the user in the base currency used by the price feed
+@return The total debt of the user in the base currency used by the price feed
+@return The average ltv of the user
+@return The average liquidation threshold of the user
+@return The health factor of the user
+@return True if the ltv is zero, false otherwise
+
+
+
public fun calculate_user_account_data(reserves_count: u256, user_config_map: &user::UserConfigurationMap, user: address, user_emode_category: u8, emode_ltv: u256, emode_liq_threshold: u256, emode_asset_price: u256): (u256, u256, u256, u256, u256, bool)
 
- + ## Function `calculate_available_borrows` +@notice Calculates the maximum amount that can be borrowed depending on the available collateral, the total debt +and the average Loan To Value +@param total_collateral_in_base_currency The total collateral in the base currency used by the price feed +@param total_debt_in_base_currency The total borrow balance in the base currency used by the price feed +@param ltv The average loan to value +@return The amount available to borrow in the base currency of the used by the price feed -
public fun calculate_available_borrows(total_collateral_in_base_currency: u256, total_debt_in_base_currency: u256, ltv: u256): u256
+
public fun calculate_available_borrows(total_collateral_in_base_currency: u256, total_debt_in_base_currency: u256, ltv: u256): u256
 
diff --git a/aave-core/doc/isolation_mode_logic.md b/aave-core/doc/isolation_mode_logic.md index 5a84f10..15429fa 100644 --- a/aave-core/doc/isolation_mode_logic.md +++ b/aave-core/doc/isolation_mode_logic.md @@ -1,40 +1,47 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::isolation_mode_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::isolation_mode_logic` -- [Struct `IsolationModeTotalDebtUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_isolation_mode_logic_IsolationModeTotalDebtUpdated) -- [Function `update_isolated_debt_if_isolated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_isolation_mode_logic_update_isolated_debt_if_isolated) +- [Struct `IsolationModeTotalDebtUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_isolation_mode_logic_IsolationModeTotalDebtUpdated) +- [Function `update_isolated_debt_if_isolated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_isolation_mode_logic_update_isolated_debt_if_isolated)
use 0x1::event;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `IsolationModeTotalDebtUpdated` +@dev Emitted on borrow(), repay() and liquidation_call() when using isolated assets +@param asset The address of the underlying asset of the reserve +@param total_debt The total isolation mode debt for the reserve
#[event]
-struct IsolationModeTotalDebtUpdated has drop, store
+struct IsolationModeTotalDebtUpdated has drop, store
 
- + ## Function `update_isolated_debt_if_isolated` +@notice updated the isolated debt whenever a position collateralized by an isolated asset is repaid or liquidated +@param user_config_map The user configuration map +@param reserve_data The reserve data +@param repay_amount The amount being repaid -
public(friend) fun update_isolated_debt_if_isolated(user_config_map: &user::UserConfigurationMap, reserve_data: &pool::ReserveData, repay_amount: u256)
+
public(friend) fun update_isolated_debt_if_isolated(user_config_map: &user::UserConfigurationMap, reserve_data: &pool::ReserveData, repay_amount: u256)
 
diff --git a/aave-core/doc/liquidation_logic.md b/aave-core/doc/liquidation_logic.md index 37b1f4d..994b1f9 100644 --- a/aave-core/doc/liquidation_logic.md +++ b/aave-core/doc/liquidation_logic.md @@ -1,105 +1,123 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::liquidation_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::liquidation_logic` +@title liquidation_logic module +@author Aave +@notice Implements actions involving management of collateral in the protocol, the main one being the liquidations -- [Struct `ReserveUsedAsCollateralEnabled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_liquidation_logic_ReserveUsedAsCollateralEnabled) -- [Struct `ReserveUsedAsCollateralDisabled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_liquidation_logic_ReserveUsedAsCollateralDisabled) -- [Struct `LiquidationCall`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_liquidation_logic_LiquidationCall) -- [Struct `LiquidationCallLocalVars`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_liquidation_logic_LiquidationCallLocalVars) -- [Struct `ExecuteLiquidationCallParams`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_liquidation_logic_ExecuteLiquidationCallParams) -- [Struct `AvailableCollateralToLiquidateLocalVars`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_liquidation_logic_AvailableCollateralToLiquidateLocalVars) +- [Struct `ReserveUsedAsCollateralEnabled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_liquidation_logic_ReserveUsedAsCollateralEnabled) +- [Struct `ReserveUsedAsCollateralDisabled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_liquidation_logic_ReserveUsedAsCollateralDisabled) +- [Struct `LiquidationCall`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_liquidation_logic_LiquidationCall) +- [Struct `LiquidationCallLocalVars`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_liquidation_logic_LiquidationCallLocalVars) +- [Struct `ExecuteLiquidationCallParams`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_liquidation_logic_ExecuteLiquidationCallParams) +- [Struct `AvailableCollateralToLiquidateLocalVars`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_liquidation_logic_AvailableCollateralToLiquidateLocalVars) - [Constants](#@Constants_0) -- [Function `liquidation_call`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_liquidation_logic_liquidation_call) +- [Function `liquidation_call`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_liquidation_logic_liquidation_call)
use 0x1::event;
 use 0x1::signer;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::emode_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::generic_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::isolation_mode_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool_validation;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::validation_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::variable_token_factory;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::emode_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::generic_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::isolation_mode_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool_validation;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::validation_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::variable_debt_token_factory;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `ReserveUsedAsCollateralEnabled` +@dev Emitted on setUserUseReserveAsCollateral() +@param reserve The address of the underlying asset of the reserve +@param user The address of the user enabling the usage as collateral
#[event]
-struct ReserveUsedAsCollateralEnabled has drop, store
+struct ReserveUsedAsCollateralEnabled has drop, store
 
- + ## Struct `ReserveUsedAsCollateralDisabled` +@dev Emitted on setUserUseReserveAsCollateral() +@param reserve The address of the underlying asset of the reserve +@param user The address of the user enabling the usage as collateral
#[event]
-struct ReserveUsedAsCollateralDisabled has drop, store
+struct ReserveUsedAsCollateralDisabled has drop, store
 
- + ## Struct `LiquidationCall` +@dev Emitted when a borrower is liquidated. +@param collateral_asset The address of the underlying asset used as collateral, to receive as result of the liquidation +@param debt_asset The address of the underlying borrowed asset to be repaid with the liquidation +@param user The address of the borrower getting liquidated +@param debt_to_cover The debt amount of borrowed asset the liquidator wants to cover +@param liquidated_collateral_amount The amount of collateral received by the liquidator +@param liquidator The address of the liquidator +@param receive_a_token True if the liquidators wants to receive the collateral aTokens, false if he wants +to receive the underlying collateral asset directly
#[event]
-struct LiquidationCall has drop, store
+struct LiquidationCall has drop, store
 
- + ## Struct `LiquidationCallLocalVars` -
struct LiquidationCallLocalVars has drop
+
struct LiquidationCallLocalVars has drop
 
- + ## Struct `ExecuteLiquidationCallParams` -
struct ExecuteLiquidationCallParams has drop
+
struct ExecuteLiquidationCallParams has drop
 
- + ## Struct `AvailableCollateralToLiquidateLocalVars` -
struct AvailableCollateralToLiquidateLocalVars has drop
+
struct AvailableCollateralToLiquidateLocalVars has drop
 
@@ -109,53 +127,60 @@ ## Constants - + +@dev This constant represents below which health factor value it is possible to liquidate +an amount of debt corresponding to MAX_LIQUIDATION_CLOSE_FACTOR. +A value of 0.95e18 results in 0.95 +0.95 * 10 ** 18 -* @dev This constant represents below which health factor value it is possible to liquidate -* an amount of debt corresponding to MAX_LIQUIDATION_CLOSE_FACTOR. -* A value of 0.95e18 results in 0.95 - - -
const CLOSE_FACTOR_HF_THRESHOLD: u256 = 950000000000000000;
+
const CLOSE_FACTOR_HF_THRESHOLD: u256 = 950000000000000000;
 
- - + -* @dev Default percentage of borrower's debt to be repaid in a liquidation. -* @dev Percentage applied when the users health factor is above CLOSE_FACTOR_HF_THRESHOLD -* Expressed in bps, a value of 0.5e4 results in 50.00% +@dev Default percentage of borrower's debt to be repaid in a liquidation. +@dev Percentage applied when the users health factor is above CLOSE_FACTOR_HF_THRESHOLD +Expressed in bps, a value of 0.5e4 results in 50.00% +5 * 10 ** 3 - -
const DEFAULT_LIQUIDATION_CLOSE_FACTOR: u256 = 5000;
+
const DEFAULT_LIQUIDATION_CLOSE_FACTOR: u256 = 5000;
 
- - - -* @dev Maximum percentage of borrower's debt to be repaid in a liquidation -* @dev Percentage applied when the users health factor is below CLOSE_FACTOR_HF_THRESHOLD -* Expressed in bps, a value of 1e4 results in 100.00% + +@dev Maximum percentage of borrower's debt to be repaid in a liquidation +@dev Percentage applied when the users health factor is below CLOSE_FACTOR_HF_THRESHOLD +Expressed in bps, a value of 1e4 results in 100.00% +1 * 10 ** 4 -
const MAX_LIQUIDATION_CLOSE_FACTOR: u256 = 10000;
+
const MAX_LIQUIDATION_CLOSE_FACTOR: u256 = 10000;
 
- + ## Function `liquidation_call` +@notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 +- The caller (liquidator) covers debt_to_cover amount of debt of the user getting liquidated, and receives +a proportionally amount of the collateral_asset plus a bonus to cover market risk +@dev Emits the LiquidationCall() event +@param collateral_asset The address of the underlying asset used as collateral, to receive as result of the liquidation +@param debt_asset The address of the underlying borrowed asset to be repaid with the liquidation +@param user The address of the borrower getting liquidated +@param debt_to_cover The debt amount of borrowed asset the liquidator wants to cover +@param receive_a_token True if the liquidators wants to receive the collateral aTokens, false if he wants +to receive the underlying collateral asset directly -
public entry fun liquidation_call(account: &signer, collateral_asset: address, debt_asset: address, user: address, debt_to_cover: u256, receive_a_token: bool)
+
public entry fun liquidation_call(account: &signer, collateral_asset: address, debt_asset: address, user: address, debt_to_cover: u256, receive_a_token: bool)
 
diff --git a/aave-core/doc/mock_underlying_token_factory.md b/aave-core/doc/mock_underlying_token_factory.md new file mode 100644 index 0000000..8b0879f --- /dev/null +++ b/aave-core/doc/mock_underlying_token_factory.md @@ -0,0 +1,272 @@ + + + +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory` + + + +- [Resource `ManagedFungibleAsset`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_ManagedFungibleAsset) +- [Resource `CoinList`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_CoinList) +- [Constants](#@Constants_0) +- [Function `create_token`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_create_token) +- [Function `assert_token_exists`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_assert_token_exists) +- [Function `get_metadata_by_symbol`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_get_metadata_by_symbol) +- [Function `get_token_account_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_get_token_account_address) +- [Function `mint`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_mint) +- [Function `transfer_from`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_transfer_from) +- [Function `burn`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_burn) +- [Function `supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_supply) +- [Function `maximum`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_maximum) +- [Function `name`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_name) +- [Function `symbol`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_symbol) +- [Function `decimals`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_decimals) +- [Function `balance_of`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_balance_of) +- [Function `token_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_mock_underlying_token_factory_token_address) + + +
use 0x1::error;
+use 0x1::fungible_asset;
+use 0x1::object;
+use 0x1::option;
+use 0x1::primary_fungible_store;
+use 0x1::signer;
+use 0x1::smart_table;
+use 0x1::string;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::token_base;
+
+ + + + + +## Resource `ManagedFungibleAsset` + +Hold refs to control the minting, transfer and burning of fungible assets. + + +
#[resource_group_member(#[group = 0x1::object::ObjectGroup])]
+struct ManagedFungibleAsset has key
+
+ + + + + +## Resource `CoinList` + +mapping (underlying token address => bool) + + +
struct CoinList has key
+
+ + + + + +## Constants + + + + +Only fungible asset metadata owner can make changes. + + +
const ENOT_OWNER: u64 = 1;
+
+ + + + + + + +
const E_ACCOUNT_NOT_EXISTS: u64 = 3;
+
+ + + + + + + +
const E_TOKEN_ALREADY_EXISTS: u64 = 2;
+
+ + + + + +## Function `create_token` + +@notice Creates a new underlying token. +@param signer The signer of the transaction +@param name The name of the aToken +@param symbol The symbol of the aToken +@param decimals The decimals of the aToken +@param icon_uri The icon URI of the aToken +@param project_uri The project URI of the aToken + + +
public entry fun create_token(signer: &signer, maximum_supply: u128, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String)
+
+ + + + + +## Function `assert_token_exists` + + + +
public fun assert_token_exists(token_metadata_address: address)
+
+ + + + + +## Function `get_metadata_by_symbol` + + + +
#[view]
+public fun get_metadata_by_symbol(symbol: string::String): object::Object<fungible_asset::Metadata>
+
+ + + + + +## Function `get_token_account_address` + + + +
#[view]
+public fun get_token_account_address(): address
+
+ + + + + +## Function `mint` + +Mint as the owner of metadata object. + + +
public entry fun mint(admin: &signer, to: address, amount: u64, metadata_address: address)
+
+ + + + + +## Function `transfer_from` + + + +
public(friend) fun transfer_from(from: address, to: address, amount: u64, metadata_address: address)
+
+ + + + + +## Function `burn` + +Burn fungible assets as the owner of metadata object. + + +
public(friend) fun burn(from: address, amount: u64, metadata_address: address)
+
+ + + + + +## Function `supply` + +Get the current supply from the metadata object. + + +
#[view]
+public fun supply(metadata_address: address): option::Option<u128>
+
+ + + + + +## Function `maximum` + +Get the maximum supply from the metadata object. + + +
#[view]
+public fun maximum(metadata_address: address): option::Option<u128>
+
+ + + + + +## Function `name` + +Get the name of the fungible asset from the metadata object. + + +
#[view]
+public fun name(metadata_address: address): string::String
+
+ + + + + +## Function `symbol` + +Get the symbol of the fungible asset from the metadata object. + + +
#[view]
+public fun symbol(metadata_address: address): string::String
+
+ + + + + +## Function `decimals` + +Get the decimals from the metadata object. + + +
#[view]
+public fun decimals(metadata_address: address): u8
+
+ + + + + +## Function `balance_of` + +Get the balance of a given store. + + +
#[view]
+public fun balance_of(owner: address, metadata_address: address): u64
+
+ + + + + +## Function `token_address` + + + +
#[view]
+public fun token_address(symbol: string::String): address
+
diff --git a/aave-core/doc/package-manager.md b/aave-core/doc/package-manager.md index ff292e1..fcef833 100644 --- a/aave-core/doc/package-manager.md +++ b/aave-core/doc/package-manager.md @@ -1,15 +1,15 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::package_manager` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::package_manager` -- [Resource `PermissionConfig`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_package_manager_PermissionConfig) -- [Function `get_signer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_package_manager_get_signer) -- [Function `add_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_package_manager_add_address) -- [Function `address_exists`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_package_manager_address_exists) -- [Function `get_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_package_manager_get_address) +- [Resource `PermissionConfig`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_package_manager_PermissionConfig) +- [Function `get_signer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_package_manager_get_signer) +- [Function `add_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_package_manager_add_address) +- [Function `address_exists`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_package_manager_address_exists) +- [Function `get_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_package_manager_get_address)
use 0x1::account;
@@ -20,58 +20,58 @@
 
 
 
-
+
 
 ## Resource `PermissionConfig`
 
 Stores permission config such as SignerCapability for controlling the resource account.
 
 
-
struct PermissionConfig has key
+
struct PermissionConfig has key
 
- + ## Function `get_signer` Can be called by friended modules to obtain the resource account signer. -
public(friend) fun get_signer(): signer
+
public(friend) fun get_signer(): signer
 
- + ## Function `add_address` Can be called by friended modules to keep track of a system address. -
public(friend) fun add_address(name: string::String, object: address)
+
public(friend) fun add_address(name: string::String, object: address)
 
- + ## Function `address_exists` -
public(friend) fun address_exists(name: string::String): bool
+
public(friend) fun address_exists(name: string::String): bool
 
- + ## Function `get_address` -
public(friend) fun get_address(name: string::String): address
+
public(friend) fun get_address(name: string::String): address
 
diff --git a/aave-core/doc/pool.md b/aave-core/doc/pool.md index f51504c..4d29b96 100644 --- a/aave-core/doc/pool.md +++ b/aave-core/doc/pool.md @@ -1,70 +1,70 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool` -- [Struct `ReserveInitialized`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_ReserveInitialized) -- [Struct `ReserveDataUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_ReserveDataUpdated) -- [Struct `MintedToTreasury`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_MintedToTreasury) -- [Struct `IsolationModeTotalDebtUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_IsolationModeTotalDebtUpdated) -- [Resource `ReserveExtendConfiguration`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_ReserveExtendConfiguration) -- [Resource `ReserveData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_ReserveData) -- [Resource `ReserveList`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_ReserveList) -- [Resource `ReserveAddressesList`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_ReserveAddressesList) -- [Resource `UsersConfig`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_UsersConfig) +- [Struct `ReserveInitialized`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_ReserveInitialized) +- [Struct `ReserveDataUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_ReserveDataUpdated) +- [Struct `MintedToTreasury`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_MintedToTreasury) +- [Struct `IsolationModeTotalDebtUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_IsolationModeTotalDebtUpdated) +- [Resource `ReserveExtendConfiguration`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_ReserveExtendConfiguration) +- [Resource `ReserveData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_ReserveData) +- [Resource `ReserveList`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_ReserveList) +- [Resource `ReserveAddressesList`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_ReserveAddressesList) +- [Resource `UsersConfig`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_UsersConfig) - [Constants](#@Constants_0) -- [Function `init_pool`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_init_pool) -- [Function `get_revision`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_revision) -- [Function `init_reserve`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_init_reserve) -- [Function `drop_reserve`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_drop_reserve) -- [Function `get_reserve_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_data) -- [Function `get_reserve_data_and_reserves_count`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_data_and_reserves_count) -- [Function `get_reserve_configuration`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_configuration) -- [Function `get_reserves_count`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserves_count) -- [Function `get_reserve_configuration_by_reserve_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_configuration_by_reserve_data) -- [Function `get_reserve_last_update_timestamp`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_last_update_timestamp) -- [Function `get_reserve_id`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_id) -- [Function `get_reserve_a_token_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_a_token_address) -- [Function `set_reserve_accrued_to_treasury`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_set_reserve_accrued_to_treasury) -- [Function `get_reserve_accrued_to_treasury`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_accrued_to_treasury) -- [Function `get_reserve_variable_borrow_index`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_variable_borrow_index) -- [Function `get_reserve_liquidity_index`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_liquidity_index) -- [Function `get_reserve_current_liquidity_rate`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_current_liquidity_rate) -- [Function `get_reserve_current_variable_borrow_rate`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_current_variable_borrow_rate) -- [Function `get_reserve_variable_debt_token_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_variable_debt_token_address) -- [Function `set_reserve_unbacked`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_set_reserve_unbacked) -- [Function `get_reserve_unbacked`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_unbacked) -- [Function `set_reserve_isolation_mode_total_debt`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_set_reserve_isolation_mode_total_debt) -- [Function `get_reserve_isolation_mode_total_debt`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_isolation_mode_total_debt) -- [Function `set_reserve_configuration`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_set_reserve_configuration) -- [Function `get_user_configuration`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_user_configuration) -- [Function `set_user_configuration`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_set_user_configuration) -- [Function `get_reserve_normalized_income`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_normalized_income) -- [Function `get_normalized_income_by_reserve_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_normalized_income_by_reserve_data) -- [Function `update_state`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_update_state) -- [Function `get_reserve_normalized_variable_debt`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_normalized_variable_debt) -- [Function `get_normalized_debt_by_reserve_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_normalized_debt_by_reserve_data) -- [Function `get_reserves_list`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserves_list) -- [Function `get_reserve_address_by_id`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_reserve_address_by_id) -- [Function `mint_to_treasury`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_mint_to_treasury) -- [Function `get_bridge_protocol_fee`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_bridge_protocol_fee) -- [Function `set_bridge_protocol_fee`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_set_bridge_protocol_fee) -- [Function `get_flashloan_premium_total`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_flashloan_premium_total) -- [Function `set_flashloan_premiums`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_set_flashloan_premiums) -- [Function `get_flashloan_premium_to_protocol`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_flashloan_premium_to_protocol) -- [Function `max_number_reserves`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_max_number_reserves) -- [Function `update_interest_rates`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_update_interest_rates) -- [Function `get_isolation_mode_state`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_isolation_mode_state) -- [Function `get_siloed_borrowing_state`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_get_siloed_borrowing_state) -- [Function `cumulate_to_liquidity_index`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_cumulate_to_liquidity_index) -- [Function `reset_isolation_mode_total_debt`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_reset_isolation_mode_total_debt) -- [Function `rescue_tokens`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_rescue_tokens) -- [Function `scale_a_token_total_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_scale_a_token_total_supply) -- [Function `scale_a_token_balance_of`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_scale_a_token_balance_of) -- [Function `scale_variable_token_total_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_scale_variable_token_total_supply) -- [Function `scale_variable_token_balance_of`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_scale_variable_token_balance_of) +- [Function `init_pool`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_init_pool) +- [Function `get_revision`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_revision) +- [Function `init_reserve`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_init_reserve) +- [Function `drop_reserve`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_drop_reserve) +- [Function `get_reserve_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_data) +- [Function `get_reserve_data_and_reserves_count`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_data_and_reserves_count) +- [Function `get_reserve_configuration`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_configuration) +- [Function `get_reserves_count`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserves_count) +- [Function `get_reserve_configuration_by_reserve_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_configuration_by_reserve_data) +- [Function `get_reserve_last_update_timestamp`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_last_update_timestamp) +- [Function `get_reserve_id`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_id) +- [Function `get_reserve_a_token_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_a_token_address) +- [Function `set_reserve_accrued_to_treasury`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_set_reserve_accrued_to_treasury) +- [Function `get_reserve_accrued_to_treasury`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_accrued_to_treasury) +- [Function `get_reserve_variable_borrow_index`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_variable_borrow_index) +- [Function `get_reserve_liquidity_index`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_liquidity_index) +- [Function `get_reserve_current_liquidity_rate`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_current_liquidity_rate) +- [Function `get_reserve_current_variable_borrow_rate`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_current_variable_borrow_rate) +- [Function `get_reserve_variable_debt_token_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_variable_debt_token_address) +- [Function `set_reserve_unbacked`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_set_reserve_unbacked) +- [Function `get_reserve_unbacked`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_unbacked) +- [Function `set_reserve_isolation_mode_total_debt`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_set_reserve_isolation_mode_total_debt) +- [Function `get_reserve_isolation_mode_total_debt`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_isolation_mode_total_debt) +- [Function `set_reserve_configuration`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_set_reserve_configuration) +- [Function `get_user_configuration`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_user_configuration) +- [Function `set_user_configuration`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_set_user_configuration) +- [Function `get_reserve_normalized_income`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_normalized_income) +- [Function `get_normalized_income_by_reserve_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_normalized_income_by_reserve_data) +- [Function `update_state`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_update_state) +- [Function `get_reserve_normalized_variable_debt`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_normalized_variable_debt) +- [Function `get_normalized_debt_by_reserve_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_normalized_debt_by_reserve_data) +- [Function `get_reserves_list`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserves_list) +- [Function `get_reserve_address_by_id`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_reserve_address_by_id) +- [Function `mint_to_treasury`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_mint_to_treasury) +- [Function `get_bridge_protocol_fee`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_bridge_protocol_fee) +- [Function `set_bridge_protocol_fee`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_set_bridge_protocol_fee) +- [Function `get_flashloan_premium_total`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_flashloan_premium_total) +- [Function `update_flashloan_premiums`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_update_flashloan_premiums) +- [Function `get_flashloan_premium_to_protocol`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_flashloan_premium_to_protocol) +- [Function `max_number_reserves`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_max_number_reserves) +- [Function `update_interest_rates`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_update_interest_rates) +- [Function `get_isolation_mode_state`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_isolation_mode_state) +- [Function `get_siloed_borrowing_state`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_get_siloed_borrowing_state) +- [Function `cumulate_to_liquidity_index`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_cumulate_to_liquidity_index) +- [Function `reset_isolation_mode_total_debt`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_reset_isolation_mode_total_debt) +- [Function `rescue_tokens`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_rescue_tokens) +- [Function `scaled_a_token_total_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_scaled_a_token_total_supply) +- [Function `scaled_a_token_balance_of`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_scaled_a_token_balance_of) +- [Function `scaled_variable_token_total_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_scaled_variable_token_total_supply) +- [Function `scaled_variable_token_balance_of`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_scaled_variable_token_balance_of)
use 0x1::event;
@@ -73,119 +73,139 @@
 use 0x1::string;
 use 0x1::timestamp;
 use 0x1::vector;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::default_reserve_interest_rate_strategy;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::variable_token_factory;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::default_reserve_interest_rate_strategy;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::variable_debt_token_factory;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `ReserveInitialized` +@dev Emitted when a reserve is initialized. +@param asset The address of the underlying asset of the reserve +@param a_token The address of the associated aToken contract +@param variable_debt_token The address of the associated variable rate debt token
#[event]
-struct ReserveInitialized has drop, store
+struct ReserveInitialized has drop, store
 
- + ## Struct `ReserveDataUpdated` +@dev Emitted when the state of a reserve is updated. +@param reserve The address of the underlying asset of the reserve +@param liquidity_rate The next liquidity rate +@param variable_borrow_rate The next variable borrow rate +@param liquidity_index The next liquidity index +@param variable_borrow_index The next variable borrow index
#[event]
-struct ReserveDataUpdated has drop, store
+struct ReserveDataUpdated has drop, store
 
- + ## Struct `MintedToTreasury` +@dev Emitted when the protocol treasury receives minted aTokens from the accrued interest. +@param reserve The address of the reserve +@param amount_minted The amount minted to the treasury
#[event]
-struct MintedToTreasury has drop, store
+struct MintedToTreasury has drop, store
 
- + ## Struct `IsolationModeTotalDebtUpdated` +@dev Emitted on borrow(), repay() and liquidation_call() when using isolated assets +@param asset The address of the underlying asset of the reserve +@param totalDebt The total isolation mode debt for the reserve
#[event]
-struct IsolationModeTotalDebtUpdated has drop, store
+struct IsolationModeTotalDebtUpdated has drop, store
 
- + ## Resource `ReserveExtendConfiguration` -
struct ReserveExtendConfiguration has drop, store, key
+
struct ReserveExtendConfiguration has drop, store, key
 
- + ## Resource `ReserveData` -
struct ReserveData has copy, drop, store, key
+
struct ReserveData has copy, drop, store, key
 
- + ## Resource `ReserveList` +Map of reserves and their data (underlying_asset_of_reserve => reserveData) -
struct ReserveList has key
+
struct ReserveList has key
 
- + ## Resource `ReserveAddressesList` +List of reserves as a map (reserveId => reserve). +It is structured as a mapping for gas savings reasons, using the reserve id as index -
struct ReserveAddressesList has key
+
struct ReserveAddressesList has key
 
- + ## Resource `UsersConfig` +Map of users address and their configuration data (user_address => UserConfigurationMap) -
struct UsersConfig has key
+
struct UsersConfig has key
 
@@ -195,577 +215,670 @@ ## Constants - + -
const POOL_REVISION: u256 = 1;
+
const POOL_REVISION: u256 = 1;
 
- + ## Function `init_pool` +@notice init pool -
public(friend) fun init_pool(account: &signer)
+
public(friend) fun init_pool(account: &signer)
 
- + ## Function `get_revision` +@notice Returns the revision number of the contract +@dev Needs to be defined in the inherited class as a constant. +@return The revision number
#[view]
-public fun get_revision(): u256
+public fun get_revision(): u256
 
- + ## Function `init_reserve` +@notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an +interest rate strategy +@dev Only callable by the pool_configurator contract +@param account The address of the caller +@param underlying_asset The address of the underlying asset of the reserve +@param underlying_asset_decimals The decimals of the underlying asset +@param treasury The address of the treasury +@param a_token_name The name of the aToken +@param a_token_symbol The symbol of the aToken +@param variable_debt_token_name The name of the variable debt token +@param variable_debt_token_symbol The symbol of the variable debt token -
public(friend) fun init_reserve(account: &signer, underlying_asset: address, underlying_asset_decimals: u8, treasury: address, a_token_name: string::String, a_token_symbol: string::String, variable_debt_token_name: string::String, variable_debt_token_symbol: string::String)
+
public(friend) fun init_reserve(account: &signer, underlying_asset: address, underlying_asset_decimals: u8, treasury: address, a_token_name: string::String, a_token_symbol: string::String, variable_debt_token_name: string::String, variable_debt_token_symbol: string::String)
 
- + ## Function `drop_reserve` +@notice Drop a reserve +@dev Only callable by the pool_configurator contract +@param asset The address of the underlying asset of the reserve -
public(friend) fun drop_reserve(asset: address)
+
public(friend) fun drop_reserve(asset: address)
 
- + ## Function `get_reserve_data` +@notice Returns the state and configuration of the reserve +@param asset The address of the underlying asset of the reserve +@return The state and configuration data of the reserve
#[view]
-public fun get_reserve_data(asset: address): pool::ReserveData
+public fun get_reserve_data(asset: address): pool::ReserveData
 
- + ## Function `get_reserve_data_and_reserves_count`
#[view]
-public fun get_reserve_data_and_reserves_count(asset: address): (pool::ReserveData, u256)
+public fun get_reserve_data_and_reserves_count(asset: address): (pool::ReserveData, u256)
 
- + ## Function `get_reserve_configuration` +@notice Returns the configuration of the reserve +@param asset The address of the underlying asset of the reserve +@return The configuration of the reserve
#[view]
-public fun get_reserve_configuration(asset: address): reserve::ReserveConfigurationMap
+public fun get_reserve_configuration(asset: address): reserve::ReserveConfigurationMap
 
- + ## Function `get_reserves_count`
#[view]
-public fun get_reserves_count(): u256
+public fun get_reserves_count(): u256
 
- + ## Function `get_reserve_configuration_by_reserve_data` -
public fun get_reserve_configuration_by_reserve_data(reserve_data: &pool::ReserveData): reserve::ReserveConfigurationMap
+
public fun get_reserve_configuration_by_reserve_data(reserve_data: &pool::ReserveData): reserve::ReserveConfigurationMap
 
- + ## Function `get_reserve_last_update_timestamp` -
public fun get_reserve_last_update_timestamp(reserve: &pool::ReserveData): u64
+
public fun get_reserve_last_update_timestamp(reserve: &pool::ReserveData): u64
 
- + ## Function `get_reserve_id` -
public fun get_reserve_id(reserve: &pool::ReserveData): u16
+
public fun get_reserve_id(reserve: &pool::ReserveData): u16
 
- + ## Function `get_reserve_a_token_address` -
public fun get_reserve_a_token_address(reserve: &pool::ReserveData): address
+
public fun get_reserve_a_token_address(reserve: &pool::ReserveData): address
 
- + ## Function `set_reserve_accrued_to_treasury` -
public(friend) fun set_reserve_accrued_to_treasury(asset: address, accrued_to_treasury: u256)
+
public(friend) fun set_reserve_accrued_to_treasury(asset: address, accrued_to_treasury: u256)
 
- + ## Function `get_reserve_accrued_to_treasury` -
public fun get_reserve_accrued_to_treasury(reserve: &pool::ReserveData): u256
+
public fun get_reserve_accrued_to_treasury(reserve: &pool::ReserveData): u256
 
- + ## Function `get_reserve_variable_borrow_index` -
public fun get_reserve_variable_borrow_index(reserve: &pool::ReserveData): u128
+
public fun get_reserve_variable_borrow_index(reserve: &pool::ReserveData): u128
 
- + ## Function `get_reserve_liquidity_index` -
public fun get_reserve_liquidity_index(reserve: &pool::ReserveData): u128
+
public fun get_reserve_liquidity_index(reserve: &pool::ReserveData): u128
 
- + ## Function `get_reserve_current_liquidity_rate` -
public fun get_reserve_current_liquidity_rate(reserve: &pool::ReserveData): u128
+
public fun get_reserve_current_liquidity_rate(reserve: &pool::ReserveData): u128
 
- + ## Function `get_reserve_current_variable_borrow_rate` -
public fun get_reserve_current_variable_borrow_rate(reserve: &pool::ReserveData): u128
+
public fun get_reserve_current_variable_borrow_rate(reserve: &pool::ReserveData): u128
 
- + ## Function `get_reserve_variable_debt_token_address` -
public fun get_reserve_variable_debt_token_address(reserve: &pool::ReserveData): address
+
public fun get_reserve_variable_debt_token_address(reserve: &pool::ReserveData): address
 
- + ## Function `set_reserve_unbacked` -
public(friend) fun set_reserve_unbacked(asset: address, unbacked: u128)
+
public(friend) fun set_reserve_unbacked(asset: address, reserve_data_mut: &mut pool::ReserveData, unbacked: u128)
 
- + ## Function `get_reserve_unbacked` -
public fun get_reserve_unbacked(reserve: &pool::ReserveData): u128
+
public fun get_reserve_unbacked(reserve: &pool::ReserveData): u128
 
- + ## Function `set_reserve_isolation_mode_total_debt` -
public(friend) fun set_reserve_isolation_mode_total_debt(asset: address, isolation_mode_total_debt: u128)
+
public(friend) fun set_reserve_isolation_mode_total_debt(asset: address, isolation_mode_total_debt: u128)
 
- + ## Function `get_reserve_isolation_mode_total_debt` -
public fun get_reserve_isolation_mode_total_debt(reserve: &pool::ReserveData): u128
+
public fun get_reserve_isolation_mode_total_debt(reserve: &pool::ReserveData): u128
 
- + ## Function `set_reserve_configuration` +@notice Sets the configuration bitmap of the reserve as a whole +@dev Only callable by the pool_configurator and pool contract +@param asset The address of the underlying asset of the reserve +@param reserve_config_map The new configuration bitmap -
public(friend) fun set_reserve_configuration(asset: address, reserve_config_map: reserve::ReserveConfigurationMap)
+
public(friend) fun set_reserve_configuration(asset: address, reserve_config_map: reserve::ReserveConfigurationMap)
 
- + ## Function `get_user_configuration`
#[view]
-public fun get_user_configuration(user: address): user::UserConfigurationMap
+public fun get_user_configuration(user: address): user::UserConfigurationMap
 
- + ## Function `set_user_configuration` -
public(friend) fun set_user_configuration(user: address, user_config_map: user::UserConfigurationMap)
+
public(friend) fun set_user_configuration(user: address, user_config_map: user::UserConfigurationMap)
 
- + ## Function `get_reserve_normalized_income` +@notice Returns the normalized income of the reserve +@param asset The address of the underlying asset of the reserve +@return The reserve's normalized income
#[view]
-public fun get_reserve_normalized_income(asset: address): u256
+public fun get_reserve_normalized_income(asset: address): u256
 
- + ## Function `get_normalized_income_by_reserve_data` +@notice Returns the ongoing normalized income for the reserve. +@dev A value of 1e27 means there is no income. As time passes, the income is accrued +@dev A value of 2*1e27 means for each unit of asset one unit of income has been accrued +@param reserve_data The reserve object +@return The normalized income, expressed in ray -
public fun get_normalized_income_by_reserve_data(reserve_data: &pool::ReserveData): u256
+
public fun get_normalized_income_by_reserve_data(reserve_data: &pool::ReserveData): u256
 
- + ## Function `update_state` +@notice Updates the liquidity cumulative index and the variable borrow index. +@param asset The address of the underlying asset of the reserve +@param reserve_data The reserve data -
public(friend) fun update_state(asset: address, reserve_data: &mut pool::ReserveData)
+
public(friend) fun update_state(asset: address, reserve_data: &mut pool::ReserveData)
 
- + ## Function `get_reserve_normalized_variable_debt` +@notice Returns the normalized variable debt per unit of asset +@dev WARNING: This function is intended to be used primarily by the protocol itself to get a +"dynamic" variable index based on time, current stored index and virtual rate at the current +moment (approx. a borrower would get if opening a position). This means that is always used in +combination with variable debt supply/balances. +If using this function externally, consider that is possible to have an increasing normalized +variable debt that is not equivalent to how the variable debt index would be updated in storage +(e.g. only updates with non-zero variable debt supply) +@param asset The address of the underlying asset of the reserve +@return The reserve normalized variable debt
#[view]
-public fun get_reserve_normalized_variable_debt(asset: address): u256
+public fun get_reserve_normalized_variable_debt(asset: address): u256
 
- + ## Function `get_normalized_debt_by_reserve_data` +@notice Returns the ongoing normalized variable debt for the reserve. +@dev A value of 1e27 means there is no debt. As time passes, the debt is accrued +@dev A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated +@param reserve_data The reserve object +@return The normalized variable debt, expressed in ray -
public fun get_normalized_debt_by_reserve_data(reserve_data: &pool::ReserveData): u256
+
public fun get_normalized_debt_by_reserve_data(reserve_data: &pool::ReserveData): u256
 
- + ## Function `get_reserves_list` +@notice Returns the list of the underlying assets of all the initialized reserves +@dev It does not include dropped reserves +@return The addresses of the underlying assets of the initialized reserves
#[view]
-public fun get_reserves_list(): vector<address>
+public fun get_reserves_list(): vector<address>
 
- + ## Function `get_reserve_address_by_id` +@notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the ReserveData struct +@param id The id of the reserve as stored in the ReserveData struct +@return The address of the reserve associated with id
#[view]
-public fun get_reserve_address_by_id(id: u256): address
+public fun get_reserve_address_by_id(id: u256): address
 
- + ## Function `mint_to_treasury` +@notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens +@param assets The list of reserves for which the minting needs to be executed -
public entry fun mint_to_treasury(assets: vector<address>)
+
public entry fun mint_to_treasury(assets: vector<address>)
 
- + ## Function `get_bridge_protocol_fee`
#[view]
-public fun get_bridge_protocol_fee(): u256
+public fun get_bridge_protocol_fee(): u256
 
- + ## Function `set_bridge_protocol_fee` -
public(friend) fun set_bridge_protocol_fee(protocol_fee: u256)
+
public(friend) fun set_bridge_protocol_fee(protocol_fee: u256)
 
- + ## Function `get_flashloan_premium_total`
#[view]
-public fun get_flashloan_premium_total(): u128
+public fun get_flashloan_premium_total(): u128
 
- + -## Function `set_flashloan_premiums` +## Function `update_flashloan_premiums` +@notice Updates flash loan premiums. Flash loan premium consists of two parts: +- A part is sent to aToken holders as extra, one time accumulated interest +- A part is collected by the protocol treasury +@dev The total premium is calculated on the total borrowed amount +@dev The premium to protocol is calculated on the total premium, being a percentage of flashLoanPremiumTotal +@dev Only callable by the pool_configurator contract +@param flash_loan_premium_total The total premium, expressed in bps +@param flash_loan_premium_to_protocol The part of the premium sent to the protocol treasury, expressed in bps -
public(friend) fun set_flashloan_premiums(flash_loan_premium_total: u128, flash_loan_premium_to_protocol: u128)
+
public(friend) fun update_flashloan_premiums(flash_loan_premium_total: u128, flash_loan_premium_to_protocol: u128)
 
- + ## Function `get_flashloan_premium_to_protocol`
#[view]
-public fun get_flashloan_premium_to_protocol(): u128
+public fun get_flashloan_premium_to_protocol(): u128
 
- + ## Function `max_number_reserves` +@notice Returns the maximum number of reserves supported to be listed in this Pool +@return The maximum number of reserves supported
#[view]
-public fun max_number_reserves(): u16
+public fun max_number_reserves(): u16
 
- + ## Function `update_interest_rates` +@notice Updates the reserve the current variable borrow rate and the current liquidity rate. +@param reserve_data The reserve data reserve to be updated +@param reserve_address The address of the reserve to be updated +@param liquidity_added The amount of liquidity added to the protocol (supply or repay) in the previous action +@param liquidity_taken The amount of liquidity taken from the protocol (redeem or borrow) -
public(friend) fun update_interest_rates(reserve_data: &mut pool::ReserveData, reserve_address: address, liquidity_added: u256, liquidity_taken: u256)
+
public(friend) fun update_interest_rates(reserve_data: &mut pool::ReserveData, reserve_address: address, liquidity_added: u256, liquidity_taken: u256)
 
- + ## Function `get_isolation_mode_state` +@notice Returns the Isolation Mode state of the user +@param user_config_map The configuration of the user +@return True if the user is in isolation mode, false otherwise +@return The address of the only asset used as collateral +@return The debt ceiling of the reserve -
public fun get_isolation_mode_state(user_config_map: &user::UserConfigurationMap): (bool, address, u256)
+
public fun get_isolation_mode_state(user_config_map: &user::UserConfigurationMap): (bool, address, u256)
 
- + ## Function `get_siloed_borrowing_state` +@notice Returns the siloed borrowing state for the user +@param account The address of the user +@return True if the user has borrowed a siloed asset, false otherwise +@return The address of the only borrowed asset -
public fun get_siloed_borrowing_state(account: address): (bool, address)
+
public fun get_siloed_borrowing_state(account: address): (bool, address)
 
- + ## Function `cumulate_to_liquidity_index` -
public(friend) fun cumulate_to_liquidity_index(asset: address, reserve_data: &mut pool::ReserveData, total_liquidity: u256, amount: u256): u256
+
public(friend) fun cumulate_to_liquidity_index(asset: address, reserve_data: &mut pool::ReserveData, total_liquidity: u256, amount: u256): u256
 
- + ## Function `reset_isolation_mode_total_debt` +@notice Resets the isolation mode total debt of the given asset to zero +@dev It requires the given asset has zero debt ceiling +@param asset The address of the underlying asset to reset the isolation_mode_total_debt -
public(friend) fun reset_isolation_mode_total_debt(asset: address)
+
public(friend) fun reset_isolation_mode_total_debt(asset: address)
 
- + ## Function `rescue_tokens` +@notice Rescue and transfer tokens locked in this contract +@param token The address of the token +@param to The address of the recipient +@param amount The amount of token to transfer -
public entry fun rescue_tokens(account: &signer, token: address, to: address, amount: u256)
+
public entry fun rescue_tokens(account: &signer, token: address, to: address, amount: u256)
 
- + -## Function `scale_a_token_total_supply` +## Function `scaled_a_token_total_supply`
#[view]
-public fun scale_a_token_total_supply(a_token_address: address): u256
+public fun scaled_a_token_total_supply(a_token_address: address): u256
 
- + -## Function `scale_a_token_balance_of` +## Function `scaled_a_token_balance_of`
#[view]
-public fun scale_a_token_balance_of(owner: address, a_token_address: address): u256
+public fun scaled_a_token_balance_of(owner: address, a_token_address: address): u256
 
- + -## Function `scale_variable_token_total_supply` +## Function `scaled_variable_token_total_supply`
#[view]
-public fun scale_variable_token_total_supply(variable_debt_token_address: address): u256
+public fun scaled_variable_token_total_supply(variable_debt_token_address: address): u256
 
- + -## Function `scale_variable_token_balance_of` +## Function `scaled_variable_token_balance_of`
#[view]
-public fun scale_variable_token_balance_of(owner: address, variable_debt_token_address: address): u256
+public fun scaled_variable_token_balance_of(owner: address, variable_debt_token_address: address): u256
 
diff --git a/aave-core/doc/pool_addresses_provider.md b/aave-core/doc/pool_addresses_provider.md index f5e7068..6b8cf71 100644 --- a/aave-core/doc/pool_addresses_provider.md +++ b/aave-core/doc/pool_addresses_provider.md @@ -1,39 +1,39 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool_addresses_provider` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool_addresses_provider` -- [Struct `MarketIdSet`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_MarketIdSet) -- [Struct `PoolUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_PoolUpdated) -- [Struct `PoolConfiguratorUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_PoolConfiguratorUpdated) -- [Struct `PriceOracleUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_PriceOracleUpdated) -- [Struct `ACLManagerUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_ACLManagerUpdated) -- [Struct `ACLAdminUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_ACLAdminUpdated) -- [Struct `PriceOracleSentinelUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_PriceOracleSentinelUpdated) -- [Struct `PoolDataProviderUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_PoolDataProviderUpdated) -- [Resource `Provider`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_Provider) +- [Struct `MarketIdSet`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_MarketIdSet) +- [Struct `PoolUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_PoolUpdated) +- [Struct `PoolConfiguratorUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_PoolConfiguratorUpdated) +- [Struct `PriceOracleUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_PriceOracleUpdated) +- [Struct `ACLManagerUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_ACLManagerUpdated) +- [Struct `ACLAdminUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_ACLAdminUpdated) +- [Struct `PriceOracleSentinelUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_PriceOracleSentinelUpdated) +- [Struct `PoolDataProviderUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_PoolDataProviderUpdated) +- [Resource `Provider`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_Provider) - [Constants](#@Constants_0) -- [Function `has_id_mapped_account`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_has_id_mapped_account) -- [Function `get_market_id`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_get_market_id) -- [Function `set_market_id`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_set_market_id) -- [Function `get_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_get_address) -- [Function `set_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_set_address) -- [Function `get_pool`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_get_pool) -- [Function `set_pool_impl`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_set_pool_impl) -- [Function `get_pool_configurator`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_get_pool_configurator) -- [Function `set_pool_configurator`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_set_pool_configurator) -- [Function `get_price_oracle`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_get_price_oracle) -- [Function `set_price_oracle`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_set_price_oracle) -- [Function `get_acl_manager`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_get_acl_manager) -- [Function `set_acl_manager`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_set_acl_manager) -- [Function `get_acl_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_get_acl_admin) -- [Function `set_acl_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_set_acl_admin) -- [Function `get_price_oracle_sentinel`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_get_price_oracle_sentinel) -- [Function `set_price_oracle_sentinel`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_set_price_oracle_sentinel) -- [Function `get_pool_data_provider`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_get_pool_data_provider) -- [Function `set_pool_data_provider`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_addresses_provider_set_pool_data_provider) +- [Function `has_id_mapped_account`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_has_id_mapped_account) +- [Function `get_market_id`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_get_market_id) +- [Function `set_market_id`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_set_market_id) +- [Function `get_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_get_address) +- [Function `set_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_set_address) +- [Function `get_pool`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_get_pool) +- [Function `set_pool_impl`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_set_pool_impl) +- [Function `get_pool_configurator`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_get_pool_configurator) +- [Function `set_pool_configurator`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_set_pool_configurator) +- [Function `get_price_oracle`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_get_price_oracle) +- [Function `set_price_oracle`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_set_price_oracle) +- [Function `get_acl_manager`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_get_acl_manager) +- [Function `set_acl_manager`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_set_acl_manager) +- [Function `get_acl_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_get_acl_admin) +- [Function `set_acl_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_set_acl_admin) +- [Function `get_price_oracle_sentinel`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_get_price_oracle_sentinel) +- [Function `set_price_oracle_sentinel`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_set_price_oracle_sentinel) +- [Function `get_pool_data_provider`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_get_pool_data_provider) +- [Function `set_pool_data_provider`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_addresses_provider_set_pool_data_provider)
use 0x1::event;
@@ -45,109 +45,109 @@
 
 
 
-
+
 
 ## Struct `MarketIdSet`
 
 
 
 
#[event]
-struct MarketIdSet has drop, store
+struct MarketIdSet has drop, store
 
- + ## Struct `PoolUpdated`
#[event]
-struct PoolUpdated has drop, store
+struct PoolUpdated has drop, store
 
- + ## Struct `PoolConfiguratorUpdated`
#[event]
-struct PoolConfiguratorUpdated has drop, store
+struct PoolConfiguratorUpdated has drop, store
 
- + ## Struct `PriceOracleUpdated`
#[event]
-struct PriceOracleUpdated has drop, store
+struct PriceOracleUpdated has drop, store
 
- + ## Struct `ACLManagerUpdated`
#[event]
-struct ACLManagerUpdated has drop, store
+struct ACLManagerUpdated has drop, store
 
- + ## Struct `ACLAdminUpdated`
#[event]
-struct ACLAdminUpdated has drop, store
+struct ACLAdminUpdated has drop, store
 
- + ## Struct `PriceOracleSentinelUpdated`
#[event]
-struct PriceOracleSentinelUpdated has drop, store
+struct PriceOracleSentinelUpdated has drop, store
 
- + ## Struct `PoolDataProviderUpdated`
#[event]
-struct PoolDataProviderUpdated has drop, store
+struct PoolDataProviderUpdated has drop, store
 
- + ## Resource `Provider` -
struct Provider has store, key
+
struct Provider has store, key
 
@@ -157,309 +157,309 @@ ## Constants - + -
const ENOT_MANAGEMENT: u64 = 1;
+
const ENOT_MANAGEMENT: u64 = 1;
 
- + -
const ACL_ADMIN: vector<u8> = [65, 67, 76, 95, 65, 68, 77, 73, 78];
+
const ACL_ADMIN: vector<u8> = [65, 67, 76, 95, 65, 68, 77, 73, 78];
 
- + -
const ACL_MANAGER: vector<u8> = [65, 67, 76, 95, 77, 65, 78, 65, 71, 69, 82];
+
const ACL_MANAGER: vector<u8> = [65, 67, 76, 95, 77, 65, 78, 65, 71, 69, 82];
 
- + -
const DATA_PROVIDER: vector<u8> = [68, 65, 84, 65, 95, 80, 82, 79, 86, 73, 68, 69, 82];
+
const DATA_PROVIDER: vector<u8> = [68, 65, 84, 65, 95, 80, 82, 79, 86, 73, 68, 69, 82];
 
- + -
const EID_ALREADY_EXISTS: u64 = 2;
+
const EID_ALREADY_EXISTS: u64 = 2;
 
- + -
const EID_NOT_EXISTS: u64 = 3;
+
const EID_NOT_EXISTS: u64 = 3;
 
- + -
const POOL: vector<u8> = [80, 79, 79, 76];
+
const POOL: vector<u8> = [80, 79, 79, 76];
 
- + -
const POOL_CONFIGURATOR: vector<u8> = [80, 79, 79, 76, 95, 67, 79, 78, 70, 73, 71, 85, 82, 65, 84, 79, 82];
+
const POOL_CONFIGURATOR: vector<u8> = [80, 79, 79, 76, 95, 67, 79, 78, 70, 73, 71, 85, 82, 65, 84, 79, 82];
 
- + -
const PRICE_ORACLE: vector<u8> = [80, 82, 73, 67, 69, 95, 79, 82, 65, 67, 76, 69];
+
const PRICE_ORACLE: vector<u8> = [80, 82, 73, 67, 69, 95, 79, 82, 65, 67, 76, 69];
 
- + -
const PRICE_ORACLE_SENTINEL: vector<u8> = [80, 82, 73, 67, 69, 95, 79, 82, 65, 67, 76, 69, 95, 83, 69, 78, 84, 73, 78, 69, 76];
+
const PRICE_ORACLE_SENTINEL: vector<u8> = [80, 82, 73, 67, 69, 95, 79, 82, 65, 67, 76, 69, 95, 83, 69, 78, 84, 73, 78, 69, 76];
 
- + ## Function `has_id_mapped_account`
#[view]
-public fun has_id_mapped_account(id: string::String): bool
+public fun has_id_mapped_account(id: string::String): bool
 
- + ## Function `get_market_id`
#[view]
-public fun get_market_id(): option::Option<string::String>
+public fun get_market_id(): option::Option<string::String>
 
- + ## Function `set_market_id` -
public entry fun set_market_id(account: &signer, new_market_id: string::String)
+
public entry fun set_market_id(account: &signer, new_market_id: string::String)
 
- + ## Function `get_address`
#[view]
-public fun get_address(id: string::String): option::Option<address>
+public fun get_address(id: string::String): option::Option<address>
 
- + ## Function `set_address` -
public entry fun set_address(account: &signer, id: string::String, addr: address)
+
public entry fun set_address(account: &signer, id: string::String, addr: address)
 
- + ## Function `get_pool`
#[view]
-public fun get_pool(): option::Option<address>
+public fun get_pool(): option::Option<address>
 
- + ## Function `set_pool_impl` -
public entry fun set_pool_impl(account: &signer, new_pool_impl: address)
+
public entry fun set_pool_impl(account: &signer, new_pool_impl: address)
 
- + ## Function `get_pool_configurator`
#[view]
-public fun get_pool_configurator(): option::Option<address>
+public fun get_pool_configurator(): option::Option<address>
 
- + ## Function `set_pool_configurator` -
public entry fun set_pool_configurator(account: &signer, new_pool_configurator_impl: address)
+
public entry fun set_pool_configurator(account: &signer, new_pool_configurator_impl: address)
 
- + ## Function `get_price_oracle`
#[view]
-public fun get_price_oracle(): option::Option<address>
+public fun get_price_oracle(): option::Option<address>
 
- + ## Function `set_price_oracle` -
public entry fun set_price_oracle(account: &signer, new_price_oracle_impl: address)
+
public entry fun set_price_oracle(account: &signer, new_price_oracle_impl: address)
 
- + ## Function `get_acl_manager`
#[view]
-public fun get_acl_manager(): option::Option<address>
+public fun get_acl_manager(): option::Option<address>
 
- + ## Function `set_acl_manager` -
public entry fun set_acl_manager(account: &signer, new_acl_manager_impl: address)
+
public entry fun set_acl_manager(account: &signer, new_acl_manager_impl: address)
 
- + ## Function `get_acl_admin`
#[view]
-public fun get_acl_admin(): option::Option<address>
+public fun get_acl_admin(): option::Option<address>
 
- + ## Function `set_acl_admin` -
public entry fun set_acl_admin(account: &signer, new_acl_admin_impl: address)
+
public entry fun set_acl_admin(account: &signer, new_acl_admin_impl: address)
 
- + ## Function `get_price_oracle_sentinel`
#[view]
-public fun get_price_oracle_sentinel(): option::Option<address>
+public fun get_price_oracle_sentinel(): option::Option<address>
 
- + ## Function `set_price_oracle_sentinel` -
public entry fun set_price_oracle_sentinel(account: &signer, new_price_oracle_sentinel_impl: address)
+
public entry fun set_price_oracle_sentinel(account: &signer, new_price_oracle_sentinel_impl: address)
 
- + ## Function `get_pool_data_provider`
#[view]
-public fun get_pool_data_provider(): option::Option<address>
+public fun get_pool_data_provider(): option::Option<address>
 
- + ## Function `set_pool_data_provider` -
public entry fun set_pool_data_provider(account: &signer, new_pool_data_provider_impl: address)
+
public entry fun set_pool_data_provider(account: &signer, new_pool_data_provider_impl: address)
 
diff --git a/aave-core/doc/pool_configurator.md b/aave-core/doc/pool_configurator.md index c3da51c..8703d4d 100644 --- a/aave-core/doc/pool_configurator.md +++ b/aave-core/doc/pool_configurator.md @@ -1,320 +1,380 @@ - - -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool_configurator` - - - -- [Struct `ReserveBorrowing`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_ReserveBorrowing) -- [Struct `ReserveFlashLoaning`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_ReserveFlashLoaning) -- [Struct `CollateralConfigurationChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_CollateralConfigurationChanged) -- [Struct `ReserveActive`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_ReserveActive) -- [Struct `ReserveFrozen`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_ReserveFrozen) -- [Struct `ReservePaused`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_ReservePaused) -- [Struct `ReserveDropped`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_ReserveDropped) -- [Struct `ReserveFactorChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_ReserveFactorChanged) -- [Struct `BorrowCapChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_BorrowCapChanged) -- [Struct `SupplyCapChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_SupplyCapChanged) -- [Struct `LiquidationProtocolFeeChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_LiquidationProtocolFeeChanged) -- [Struct `UnbackedMintCapChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_UnbackedMintCapChanged) -- [Struct `EModeAssetCategoryChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_EModeAssetCategoryChanged) -- [Struct `EModeCategoryAdded`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_EModeCategoryAdded) -- [Struct `ReserveInterestRateStrategyChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_ReserveInterestRateStrategyChanged) -- [Struct `DebtCeilingChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_DebtCeilingChanged) -- [Struct `SiloedBorrowingChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_SiloedBorrowingChanged) -- [Struct `BridgeProtocolFeeUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_BridgeProtocolFeeUpdated) -- [Struct `FlashloanPremiumTotalUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_FlashloanPremiumTotalUpdated) -- [Struct `FlashloanPremiumToProtocolUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_FlashloanPremiumToProtocolUpdated) -- [Struct `BorrowableInIsolationChanged`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_BorrowableInIsolationChanged) + + +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool_configurator` + + + +- [Struct `ReserveBorrowing`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_ReserveBorrowing) +- [Struct `ReserveFlashLoaning`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_ReserveFlashLoaning) +- [Struct `CollateralConfigurationChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_CollateralConfigurationChanged) +- [Struct `ReserveActive`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_ReserveActive) +- [Struct `ReserveFrozen`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_ReserveFrozen) +- [Struct `ReservePaused`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_ReservePaused) +- [Struct `ReserveDropped`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_ReserveDropped) +- [Struct `ReserveFactorChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_ReserveFactorChanged) +- [Struct `BorrowCapChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_BorrowCapChanged) +- [Struct `SupplyCapChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_SupplyCapChanged) +- [Struct `LiquidationProtocolFeeChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_LiquidationProtocolFeeChanged) +- [Struct `UnbackedMintCapChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_UnbackedMintCapChanged) +- [Struct `EModeAssetCategoryChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_EModeAssetCategoryChanged) +- [Struct `EModeCategoryAdded`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_EModeCategoryAdded) +- [Struct `DebtCeilingChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_DebtCeilingChanged) +- [Struct `SiloedBorrowingChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_SiloedBorrowingChanged) +- [Struct `BridgeProtocolFeeUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_BridgeProtocolFeeUpdated) +- [Struct `FlashloanPremiumTotalUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_FlashloanPremiumTotalUpdated) +- [Struct `FlashloanPremiumToProtocolUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_FlashloanPremiumToProtocolUpdated) +- [Struct `BorrowableInIsolationChanged`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_BorrowableInIsolationChanged) - [Constants](#@Constants_0) -- [Function `get_revision`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_get_revision) -- [Function `init_reserves`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_init_reserves) -- [Function `drop_reserve`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_drop_reserve) -- [Function `set_reserve_borrowing`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_reserve_borrowing) -- [Function `configure_reserve_as_collateral`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_configure_reserve_as_collateral) -- [Function `set_reserve_flash_loaning`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_reserve_flash_loaning) -- [Function `set_reserve_active`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_reserve_active) -- [Function `set_reserve_freeze`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_reserve_freeze) -- [Function `set_borrowable_in_isolation`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_borrowable_in_isolation) -- [Function `set_reserve_pause`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_reserve_pause) -- [Function `set_reserve_factor`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_reserve_factor) -- [Function `set_debt_ceiling`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_debt_ceiling) -- [Function `set_siloed_borrowing`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_siloed_borrowing) -- [Function `set_borrow_cap`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_borrow_cap) -- [Function `set_supply_cap`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_supply_cap) -- [Function `set_liquidation_protocol_fee`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_liquidation_protocol_fee) -- [Function `set_emode_category`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_emode_category) -- [Function `set_asset_emode_category`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_asset_emode_category) -- [Function `set_unbacked_mint_cap`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_unbacked_mint_cap) -- [Function `set_pool_pause`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_set_pool_pause) -- [Function `update_bridge_protocol_fee`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_update_bridge_protocol_fee) -- [Function `update_flashloan_premium_total`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_update_flashloan_premium_total) -- [Function `update_flashloan_premium_to_protocol`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_update_flashloan_premium_to_protocol) -- [Function `configure_reserves`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_configurator_configure_reserves) +- [Function `get_revision`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_get_revision) +- [Function `init_reserves`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_init_reserves) +- [Function `drop_reserve`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_drop_reserve) +- [Function `set_reserve_borrowing`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_reserve_borrowing) +- [Function `configure_reserve_as_collateral`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_configure_reserve_as_collateral) +- [Function `set_reserve_flash_loaning`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_reserve_flash_loaning) +- [Function `set_reserve_active`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_reserve_active) +- [Function `set_reserve_freeze`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_reserve_freeze) +- [Function `set_borrowable_in_isolation`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_borrowable_in_isolation) +- [Function `set_reserve_pause`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_reserve_pause) +- [Function `set_reserve_factor`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_reserve_factor) +- [Function `set_debt_ceiling`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_debt_ceiling) +- [Function `set_siloed_borrowing`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_siloed_borrowing) +- [Function `set_borrow_cap`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_borrow_cap) +- [Function `set_supply_cap`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_supply_cap) +- [Function `set_liquidation_protocol_fee`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_liquidation_protocol_fee) +- [Function `set_emode_category`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_emode_category) +- [Function `set_asset_emode_category`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_asset_emode_category) +- [Function `set_unbacked_mint_cap`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_unbacked_mint_cap) +- [Function `set_pool_pause`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_set_pool_pause) +- [Function `update_bridge_protocol_fee`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_update_bridge_protocol_fee) +- [Function `update_flashloan_premium_total`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_update_flashloan_premium_total) +- [Function `update_flashloan_premium_to_protocol`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_update_flashloan_premium_to_protocol) +- [Function `configure_reserves`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_configurator_configure_reserves)
use 0x1::event;
 use 0x1::signer;
 use 0x1::string;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::default_reserve_interest_rate_strategy;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::emode_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::default_reserve_interest_rate_strategy;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::emode_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
 
- + ## Struct `ReserveBorrowing` +@dev Emitted when borrowing is enabled or disabled on a reserve. +@param asset The address of the underlying asset of the reserve +@param enabled True if borrowing is enabled, false otherwise
#[event]
-struct ReserveBorrowing has drop, store
+struct ReserveBorrowing has drop, store
 
- + ## Struct `ReserveFlashLoaning` +@dev Emitted when flashloans are enabled or disabled on a reserve. +@param asset The address of the underlying asset of the reserve +@param enabled True if flashloans are enabled, false otherwise
#[event]
-struct ReserveFlashLoaning has drop, store
+struct ReserveFlashLoaning has drop, store
 
- + ## Struct `CollateralConfigurationChanged` +@dev Emitted when the collateralization risk parameters for the specified asset are updated. +@param asset The address of the underlying asset of the reserve +@param ltv The loan to value of the asset when used as collateral +@param liquidation_threshold The threshold at which loans using this asset as collateral will be considered undercollateralized +@param liquidation_bonus The bonus liquidators receive to liquidate this asset
#[event]
-struct CollateralConfigurationChanged has drop, store
+struct CollateralConfigurationChanged has drop, store
 
- + ## Struct `ReserveActive` +@dev Emitted when a reserve is activated or deactivated +@param asset The address of the underlying asset of the reserve +@param active True if reserve is active, false otherwise
#[event]
-struct ReserveActive has drop, store
+struct ReserveActive has drop, store
 
- + ## Struct `ReserveFrozen` +@dev Emitted when a reserve is frozen or unfrozen +@param asset The address of the underlying asset of the reserve +@param frozen True if reserve is frozen, false otherwise
#[event]
-struct ReserveFrozen has drop, store
+struct ReserveFrozen has drop, store
 
- + ## Struct `ReservePaused` +@dev Emitted when a reserve is paused or unpaused +@param asset The address of the underlying asset of the reserve +@param paused True if reserve is paused, false otherwise
#[event]
-struct ReservePaused has drop, store
+struct ReservePaused has drop, store
 
- + ## Struct `ReserveDropped` +@dev Emitted when a reserve is dropped. +@param asset The address of the underlying asset of the reserve
#[event]
-struct ReserveDropped has drop, store
+struct ReserveDropped has drop, store
 
- + ## Struct `ReserveFactorChanged` +@dev Emitted when a reserve factor is updated. +@param asset The address of the underlying asset of the reserve +@param old_reserve_factor The old reserve factor, expressed in bps +@param new_reserve_factor The new reserve factor, expressed in bps
#[event]
-struct ReserveFactorChanged has drop, store
+struct ReserveFactorChanged has drop, store
 
- + ## Struct `BorrowCapChanged` +@dev Emitted when the borrow cap of a reserve is updated. +@param asset The address of the underlying asset of the reserve +@param old_borrow_cap The old borrow cap +@param new_borrow_cap The new borrow cap
#[event]
-struct BorrowCapChanged has drop, store
+struct BorrowCapChanged has drop, store
 
- + ## Struct `SupplyCapChanged` +@dev Emitted when the supply cap of a reserve is updated. +@param asset The address of the underlying asset of the reserve +@param old_supply_cap The old supply cap +@param new_supply_cap The new supply cap
#[event]
-struct SupplyCapChanged has drop, store
+struct SupplyCapChanged has drop, store
 
- + ## Struct `LiquidationProtocolFeeChanged` +@dev Emitted when the liquidation protocol fee of a reserve is updated. +@param asset The address of the underlying asset of the reserve +@param old_fee The old liquidation protocol fee, expressed in bps +@param new_fee The new liquidation protocol fee, expressed in bps
#[event]
-struct LiquidationProtocolFeeChanged has drop, store
+struct LiquidationProtocolFeeChanged has drop, store
 
- + ## Struct `UnbackedMintCapChanged` +@dev Emitted when the unbacked mint cap of a reserve is updated. +@param asset The address of the underlying asset of the reserve +@param old_unbacked_mint_cap The old unbacked mint cap +@param new_unbacked_mint_cap The new unbacked mint cap
#[event]
-struct UnbackedMintCapChanged has drop, store
+struct UnbackedMintCapChanged has drop, store
 
- + ## Struct `EModeAssetCategoryChanged` +@dev Emitted when the category of an asset in eMode is changed. +@param asset The address of the underlying asset of the reserve +@param old_category_id The old eMode asset category +@param new_category_id The new eMode asset category
#[event]
-struct EModeAssetCategoryChanged has drop, store
+struct EModeAssetCategoryChanged has drop, store
 
- + ## Struct `EModeCategoryAdded` +@dev Emitted when a new eMode category is added. +@param category_id The new eMode category id +@param ltv The ltv for the asset category in eMode +@param liquidation_threshold The liquidationThreshold for the asset category in eMode +@param liquidation_bonus The liquidationBonus for the asset category in eMode +@param oracle The optional address of the price oracle specific for this category +@param label A human readable identifier for the category
#[event]
-struct EModeCategoryAdded has drop, store
+struct EModeCategoryAdded has drop, store
 
- - -## Struct `ReserveInterestRateStrategyChanged` - - - -
#[event]
-struct ReserveInterestRateStrategyChanged has drop, store
-
- - - - + ## Struct `DebtCeilingChanged` +@dev Emitted when the debt ceiling of an asset is set. +@param asset The address of the underlying asset of the reserve +@param old_debt_ceiling The old debt ceiling +@param new_debt_ceiling The new debt ceiling
#[event]
-struct DebtCeilingChanged has drop, store
+struct DebtCeilingChanged has drop, store
 
- + ## Struct `SiloedBorrowingChanged` +@dev Emitted when the the siloed borrowing state for an asset is changed. +@param asset The address of the underlying asset of the reserve +@param old_state The old siloed borrowing state +@param new_state The new siloed borrowing state
#[event]
-struct SiloedBorrowingChanged has drop, store
+struct SiloedBorrowingChanged has drop, store
 
- + ## Struct `BridgeProtocolFeeUpdated` +@dev Emitted when the bridge protocol fee is updated. +@param old_bridge_protocol_fee The old protocol fee, expressed in bps +@param new_bridge_protocol_fee The new protocol fee, expressed in bps
#[event]
-struct BridgeProtocolFeeUpdated has drop, store
+struct BridgeProtocolFeeUpdated has drop, store
 
- + ## Struct `FlashloanPremiumTotalUpdated` +@dev Emitted when the total premium on flashloans is updated. +@param old_flashloan_premium_total The old premium, expressed in bps +@param new_flashloan_premium_total The new premium, expressed in bps
#[event]
-struct FlashloanPremiumTotalUpdated has drop, store
+struct FlashloanPremiumTotalUpdated has drop, store
 
- + ## Struct `FlashloanPremiumToProtocolUpdated` +@dev Emitted when the part of the premium that goes to protocol is updated. +@param old_flashloan_premium_to_protocol The old premium, expressed in bps +@param new_flashloan_premium_to_protocol The new premium, expressed in bps
#[event]
-struct FlashloanPremiumToProtocolUpdated has drop, store
+struct FlashloanPremiumToProtocolUpdated has drop, store
 
- + ## Struct `BorrowableInIsolationChanged` +@dev Emitted when the reserve is set as borrowable/non borrowable in isolation mode. +@param asset The address of the underlying asset of the reserve +@param borrowable True if the reserve is borrowable in isolation, false otherwise
#[event]
-struct BorrowableInIsolationChanged has drop, store
+struct BorrowableInIsolationChanged has drop, store
 
@@ -324,274 +384,369 @@ ## Constants - + -
const CONFIGURATOR_REVISION: u256 = 1;
+
const CONFIGURATOR_REVISION: u256 = 1;
 
- + ## Function `get_revision` +@notice Returns the revision of the configurator
#[view]
-public fun get_revision(): u256
+public fun get_revision(): u256
 
- + ## Function `init_reserves` +@notice Initializes multiple reserves. +@param account The address of the caller +@param underlying_asset The list of the underlying assets of the reserves +@param underlying_asset_decimals The list of the decimals of the underlying assets +@param treasury The list of the treasury addresses of the reserves +@param a_token_name The list of the aToken names of the reserves +@param a_token_symbol The list of the aToken symbols of the reserves +@param variable_debt_token_name The list of the variable debt token names of the reserves +@param variable_debt_token_symbol The list of the variable debt token symbols of the reserves +@dev The caller needs to be an asset listing or pool admin -
public entry fun init_reserves(account: &signer, underlying_asset: vector<address>, underlying_asset_decimals: vector<u8>, treasury: vector<address>, a_token_name: vector<string::String>, a_token_symbol: vector<string::String>, variable_debt_token_name: vector<string::String>, variable_debt_token_symbol: vector<string::String>)
+
public entry fun init_reserves(account: &signer, underlying_asset: vector<address>, underlying_asset_decimals: vector<u8>, treasury: vector<address>, a_token_name: vector<string::String>, a_token_symbol: vector<string::String>, variable_debt_token_name: vector<string::String>, variable_debt_token_symbol: vector<string::String>)
 
- + ## Function `drop_reserve` +@notice Drops a reserve entirely. +@param account The address of the caller +@param asset The address of the reserve to drop -
public entry fun drop_reserve(account: &signer, asset: address)
+
public entry fun drop_reserve(account: &signer, asset: address)
 
- + ## Function `set_reserve_borrowing` +@notice Configures borrowing on a reserve. +@dev Can only be disabled (set to false) +@param asset The address of the underlying asset of the reserve +@param enabled True if borrowing needs to be enabled, false otherwise -
public entry fun set_reserve_borrowing(account: &signer, asset: address, enabled: bool)
+
public entry fun set_reserve_borrowing(account: &signer, asset: address, enabled: bool)
 
- + ## Function `configure_reserve_as_collateral` +@notice Configures the reserve collateralization parameters. +@dev All the values are expressed in bps. A value of 10000, results in 100.00% +@dev The liquidation_bonus is always above 100%. A value of 105% means the liquidator will receive a 5% bonus +@param asset The address of the underlying asset of the reserve +@param ltv The loan to value of the asset when used as collateral +@param liquidation_threshold The threshold at which loans using this asset as collateral will be considered undercollateralized +@param liquidation_bonus The bonus liquidators receive to liquidate this asset -
public entry fun configure_reserve_as_collateral(account: &signer, asset: address, ltv: u256, liquidation_threshold: u256, liquidation_bonus: u256)
+
public entry fun configure_reserve_as_collateral(account: &signer, asset: address, ltv: u256, liquidation_threshold: u256, liquidation_bonus: u256)
 
- + ## Function `set_reserve_flash_loaning` +@notice Enable or disable flashloans on a reserve +@param asset The address of the underlying asset of the reserve +@param enabled True if flashloans need to be enabled, false otherwise -
public entry fun set_reserve_flash_loaning(account: &signer, asset: address, enabled: bool)
+
public entry fun set_reserve_flash_loaning(account: &signer, asset: address, enabled: bool)
 
- + ## Function `set_reserve_active` +@notice Activate or deactivate a reserve +@param asset The address of the underlying asset of the reserve +@param active True if the reserve needs to be active, false otherwise -
public entry fun set_reserve_active(account: &signer, asset: address, active: bool)
+
public entry fun set_reserve_active(account: &signer, asset: address, active: bool)
 
- + ## Function `set_reserve_freeze` +@notice Freeze or unfreeze a reserve. A frozen reserve doesn't allow any new supply, borrow +or rate swap but allows repayments, liquidations, rate rebalances and withdrawals. +@param asset The address of the underlying asset of the reserve +@param freeze True if the reserve needs to be frozen, false otherwise -
public entry fun set_reserve_freeze(account: &signer, asset: address, freeze: bool)
+
public entry fun set_reserve_freeze(account: &signer, asset: address, freeze: bool)
 
- + ## Function `set_borrowable_in_isolation` +@notice Sets the borrowable in isolation flag for the reserve. +@dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the +borrowed amount will be accumulated in the isolated collateral's total debt exposure +@dev Only assets of the same family (e.g. USD stablecoins) should be borrowable in isolation mode to keep +consistency in the debt ceiling calculations +@param asset The address of the underlying asset of the reserve +@param borrowable True if the asset should be borrowable in isolation, false otherwise -
public entry fun set_borrowable_in_isolation(account: &signer, asset: address, borrowable: bool)
+
public entry fun set_borrowable_in_isolation(account: &signer, asset: address, borrowable: bool)
 
- + ## Function `set_reserve_pause` +@notice Pauses a reserve. A paused reserve does not allow any interaction (supply, borrow, repay, +swap interest rate, liquidate, atoken transfers). +@param asset The address of the underlying asset of the reserve +@param paused True if pausing the reserve, false if unpausing -
public entry fun set_reserve_pause(account: &signer, asset: address, paused: bool)
+
public entry fun set_reserve_pause(account: &signer, asset: address, paused: bool)
 
- + ## Function `set_reserve_factor` +@notice Updates the reserve factor of a reserve. +@param asset The address of the underlying asset of the reserve +@param new_reserve_factor The new reserve factor of the reserve -
public entry fun set_reserve_factor(account: &signer, asset: address, new_reserve_factor: u256)
+
public entry fun set_reserve_factor(account: &signer, asset: address, new_reserve_factor: u256)
 
- + ## Function `set_debt_ceiling` +@notice Sets the debt ceiling for an asset. +@param new_debt_ceiling The new debt ceiling -
public entry fun set_debt_ceiling(account: &signer, asset: address, new_debt_ceiling: u256)
+
public entry fun set_debt_ceiling(account: &signer, asset: address, new_debt_ceiling: u256)
 
- + ## Function `set_siloed_borrowing` +@notice Sets siloed borrowing for an asset +@param new_siloed The new siloed borrowing state -
public entry fun set_siloed_borrowing(account: &signer, asset: address, new_siloed: bool)
+
public entry fun set_siloed_borrowing(account: &signer, asset: address, new_siloed: bool)
 
- + ## Function `set_borrow_cap` +@notice Updates the borrow cap of a reserve. +@param asset The address of the underlying asset of the reserve +@param new_borrow_cap The new borrow cap of the reserve -
public entry fun set_borrow_cap(account: &signer, asset: address, new_borrow_cap: u256)
+
public entry fun set_borrow_cap(account: &signer, asset: address, new_borrow_cap: u256)
 
- + ## Function `set_supply_cap` +@notice Updates the supply cap of a reserve. +@param asset The address of the underlying asset of the reserve +@param new_supply_cap The new supply cap of the reserve -
public entry fun set_supply_cap(account: &signer, asset: address, new_supply_cap: u256)
+
public entry fun set_supply_cap(account: &signer, asset: address, new_supply_cap: u256)
 
- + ## Function `set_liquidation_protocol_fee` +@notice Updates the liquidation protocol fee of reserve. +@param asset The address of the underlying asset of the reserve +@param new_fee The new liquidation protocol fee of the reserve, expressed in bps -
public entry fun set_liquidation_protocol_fee(account: &signer, asset: address, new_fee: u256)
+
public entry fun set_liquidation_protocol_fee(account: &signer, asset: address, new_fee: u256)
 
- + ## Function `set_emode_category` +@notice Adds a new efficiency mode (eMode) category. +@dev If zero is provided as oracle address, the default asset oracles will be used to compute the overall debt and +overcollateralization of the users using this category. +@dev The new ltv and liquidation threshold must be greater than the base +ltvs and liquidation thresholds of all assets within the eMode category +@param category_id The id of the category to be configured +@param ltv The ltv associated with the category +@param liquidation_threshold The liquidation threshold associated with the category +@param liquidation_bonus The liquidation bonus associated with the category +@param oracle The oracle associated with the category +@param label A label identifying the category -
public entry fun set_emode_category(account: &signer, category_id: u8, ltv: u16, liquidation_threshold: u16, liquidation_bonus: u16, oracle: address, label: string::String)
+
public entry fun set_emode_category(account: &signer, category_id: u8, ltv: u16, liquidation_threshold: u16, liquidation_bonus: u16, oracle: address, label: string::String)
 
- + ## Function `set_asset_emode_category` +@notice Assign an efficiency mode (eMode) category to asset. +@param asset The address of the underlying asset of the reserve +@param new_category_id The new category id of the asset -
public entry fun set_asset_emode_category(account: &signer, asset: address, new_category_id: u8)
+
public entry fun set_asset_emode_category(account: &signer, asset: address, new_category_id: u8)
 
- + ## Function `set_unbacked_mint_cap` +@notice Updates the unbacked mint cap of reserve. +@param asset The address of the underlying asset of the reserve +@param new_unbacked_mint_cap The new unbacked mint cap of the reserve -
public entry fun set_unbacked_mint_cap(account: &signer, asset: address, new_unbacked_mint_cap: u256)
+
public entry fun set_unbacked_mint_cap(account: &signer, asset: address, new_unbacked_mint_cap: u256)
 
- + ## Function `set_pool_pause` +@notice Pauses or unpauses all the protocol reserves. In the paused state all the protocol interactions +are suspended. +@param paused True if protocol needs to be paused, false otherwise -
public entry fun set_pool_pause(account: &signer, paused: bool)
+
public entry fun set_pool_pause(account: &signer, paused: bool)
 
- + ## Function `update_bridge_protocol_fee` +@notice Updates the protocol fee on the bridging +@param new_bridge_protocol_fee The part of the premium sent to the protocol treasury -
public entry fun update_bridge_protocol_fee(account: &signer, new_bridge_protocol_fee: u256)
+
public entry fun update_bridge_protocol_fee(account: &signer, new_bridge_protocol_fee: u256)
 
- + ## Function `update_flashloan_premium_total` +@notice Updates the total flash loan premium. +Total flash loan premium consists of two parts: +- A part is sent to aToken holders as extra balance +- A part is collected by the protocol reserves +@dev Expressed in bps +@dev The premium is calculated on the total amount borrowed +@param new_flashloan_premium_total The total flashloan premium -
public entry fun update_flashloan_premium_total(account: &signer, new_flashloan_premium_total: u128)
+
public entry fun update_flashloan_premium_total(account: &signer, new_flashloan_premium_total: u128)
 
- + ## Function `update_flashloan_premium_to_protocol` +@notice Updates the flash loan premium collected by protocol reserves +@dev Expressed in bps +@dev The premium to protocol is calculated on the total flashloan premium +@param new_flashloan_premium_to_protocol The part of the flashloan premium sent to the protocol treasury -
public entry fun update_flashloan_premium_to_protocol(account: &signer, new_flashloan_premium_to_protocol: u128)
+
public entry fun update_flashloan_premium_to_protocol(account: &signer, new_flashloan_premium_to_protocol: u128)
 
- + ## Function `configure_reserves` -
public entry fun configure_reserves(account: &signer, asset: vector<address>, base_ltv: vector<u256>, liquidation_threshold: vector<u256>, liquidation_bonus: vector<u256>, reserve_factor: vector<u256>, borrow_cap: vector<u256>, supply_cap: vector<u256>, borrowing_enabled: vector<bool>, flash_loan_enabled: vector<bool>)
+
public entry fun configure_reserves(account: &signer, asset: vector<address>, base_ltv: vector<u256>, liquidation_threshold: vector<u256>, liquidation_bonus: vector<u256>, reserve_factor: vector<u256>, borrow_cap: vector<u256>, supply_cap: vector<u256>, borrowing_enabled: vector<bool>, flash_loan_enabled: vector<bool>)
 
diff --git a/aave-core/doc/pool_data_provider.md b/aave-core/doc/pool_data_provider.md index b38fd1f..8a4f7e0 100644 --- a/aave-core/doc/pool_data_provider.md +++ b/aave-core/doc/pool_data_provider.md @@ -1,263 +1,263 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool_data_provider` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool_data_provider` -- [Struct `TokenData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_TokenData) -- [Function `get_all_reserves_tokens`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_all_reserves_tokens) -- [Function `get_all_a_tokens`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_all_a_tokens) -- [Function `get_all_var_tokens`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_all_var_tokens) -- [Function `get_reserve_configuration_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_reserve_configuration_data) -- [Function `get_reserve_emode_category`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_reserve_emode_category) -- [Function `get_reserve_caps`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_reserve_caps) -- [Function `get_paused`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_paused) -- [Function `get_siloed_borrowing`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_siloed_borrowing) -- [Function `get_liquidation_protocol_fee`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_liquidation_protocol_fee) -- [Function `get_unbacked_mint_cap`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_unbacked_mint_cap) -- [Function `get_debt_ceiling`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_debt_ceiling) -- [Function `get_debt_ceiling_decimals`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_debt_ceiling_decimals) -- [Function `get_reserve_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_reserve_data) -- [Function `get_a_token_total_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_a_token_total_supply) -- [Function `get_total_debt`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_total_debt) -- [Function `get_user_reserve_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_user_reserve_data) -- [Function `get_reserve_tokens_addresses`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_reserve_tokens_addresses) -- [Function `get_flash_loan_enabled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_data_provider_get_flash_loan_enabled) +- [Struct `TokenData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_TokenData) +- [Function `get_all_reserves_tokens`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_all_reserves_tokens) +- [Function `get_all_a_tokens`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_all_a_tokens) +- [Function `get_all_var_tokens`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_all_var_tokens) +- [Function `get_reserve_configuration_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_reserve_configuration_data) +- [Function `get_reserve_emode_category`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_reserve_emode_category) +- [Function `get_reserve_caps`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_reserve_caps) +- [Function `get_paused`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_paused) +- [Function `get_siloed_borrowing`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_siloed_borrowing) +- [Function `get_liquidation_protocol_fee`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_liquidation_protocol_fee) +- [Function `get_unbacked_mint_cap`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_unbacked_mint_cap) +- [Function `get_debt_ceiling`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_debt_ceiling) +- [Function `get_debt_ceiling_decimals`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_debt_ceiling_decimals) +- [Function `get_reserve_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_reserve_data) +- [Function `get_a_token_total_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_a_token_total_supply) +- [Function `get_total_debt`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_total_debt) +- [Function `get_user_reserve_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_user_reserve_data) +- [Function `get_reserve_tokens_addresses`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_reserve_tokens_addresses) +- [Function `get_flash_loan_enabled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_data_provider_get_flash_loan_enabled)
use 0x1::string;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::variable_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::variable_debt_token_factory;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `TokenData` -
struct TokenData
+
struct TokenData has drop
 
- + ## Function `get_all_reserves_tokens`
#[view]
-public fun get_all_reserves_tokens(): vector<pool_data_provider::TokenData>
+public fun get_all_reserves_tokens(): vector<pool_data_provider::TokenData>
 
- + ## Function `get_all_a_tokens`
#[view]
-public fun get_all_a_tokens(): vector<pool_data_provider::TokenData>
+public fun get_all_a_tokens(): vector<pool_data_provider::TokenData>
 
- + ## Function `get_all_var_tokens`
#[view]
-public fun get_all_var_tokens(): vector<pool_data_provider::TokenData>
+public fun get_all_var_tokens(): vector<pool_data_provider::TokenData>
 
- + ## Function `get_reserve_configuration_data`
#[view]
-public fun get_reserve_configuration_data(asset: address): (u256, u256, u256, u256, u256, bool, bool, bool, bool)
+public fun get_reserve_configuration_data(asset: address): (u256, u256, u256, u256, u256, bool, bool, bool, bool)
 
- + ## Function `get_reserve_emode_category`
#[view]
-public fun get_reserve_emode_category(asset: address): u256
+public fun get_reserve_emode_category(asset: address): u256
 
- + ## Function `get_reserve_caps`
#[view]
-public fun get_reserve_caps(asset: address): (u256, u256)
+public fun get_reserve_caps(asset: address): (u256, u256)
 
- + ## Function `get_paused`
#[view]
-public fun get_paused(asset: address): bool
+public fun get_paused(asset: address): bool
 
- + ## Function `get_siloed_borrowing`
#[view]
-public fun get_siloed_borrowing(asset: address): bool
+public fun get_siloed_borrowing(asset: address): bool
 
- + ## Function `get_liquidation_protocol_fee`
#[view]
-public fun get_liquidation_protocol_fee(asset: address): u256
+public fun get_liquidation_protocol_fee(asset: address): u256
 
- + ## Function `get_unbacked_mint_cap`
#[view]
-public fun get_unbacked_mint_cap(asset: address): u256
+public fun get_unbacked_mint_cap(asset: address): u256
 
- + ## Function `get_debt_ceiling`
#[view]
-public fun get_debt_ceiling(asset: address): u256
+public fun get_debt_ceiling(asset: address): u256
 
- + ## Function `get_debt_ceiling_decimals`
#[view]
-public fun get_debt_ceiling_decimals(): u256
+public fun get_debt_ceiling_decimals(): u256
 
- + ## Function `get_reserve_data`
#[view]
-public fun get_reserve_data(asset: address): (u256, u256, u256, u256, u256, u256, u256, u256, u64)
+public fun get_reserve_data(asset: address): (u256, u256, u256, u256, u256, u256, u256, u256, u64)
 
- + ## Function `get_a_token_total_supply`
#[view]
-public fun get_a_token_total_supply(asset: address): u256
+public fun get_a_token_total_supply(asset: address): u256
 
- + ## Function `get_total_debt`
#[view]
-public fun get_total_debt(asset: address): u256
+public fun get_total_debt(asset: address): u256
 
- + ## Function `get_user_reserve_data`
#[view]
-public fun get_user_reserve_data(asset: address, user: address): (u256, u256, u256, u256, bool)
+public fun get_user_reserve_data(asset: address, user: address): (u256, u256, u256, u256, bool)
 
- + ## Function `get_reserve_tokens_addresses`
#[view]
-public fun get_reserve_tokens_addresses(asset: address): (address, address)
+public fun get_reserve_tokens_addresses(asset: address): (address, address)
 
- + ## Function `get_flash_loan_enabled`
#[view]
-public fun get_flash_loan_enabled(asset: address): bool
+public fun get_flash_loan_enabled(asset: address): bool
 
diff --git a/aave-core/doc/rewards_controller.md b/aave-core/doc/rewards_controller.md index 9110d57..a33cadd 100644 --- a/aave-core/doc/rewards_controller.md +++ b/aave-core/doc/rewards_controller.md @@ -1,53 +1,53 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::rewards_controller` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::rewards_controller` -- [Resource `RewardsControllerData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_RewardsControllerData) -- [Resource `AssetData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_AssetData) -- [Resource `RewardData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_RewardData) -- [Resource `UserData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_UserData) -- [Struct `UserAssetBalance`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_UserAssetBalance) -- [Struct `ClaimerSet`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_ClaimerSet) -- [Struct `Accrued`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_Accrued) -- [Struct `AssetConfigUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_AssetConfigUpdated) -- [Struct `RewardsClaimed`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_RewardsClaimed) -- [Struct `RewardOracleUpdated`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_RewardOracleUpdated) -- [Struct `PullRewardsTransferStrategyInstalled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_PullRewardsTransferStrategyInstalled) -- [Struct `StakedTokenTransferStrategyInstalled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_StakedTokenTransferStrategyInstalled) +- [Resource `RewardsControllerData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_RewardsControllerData) +- [Resource `AssetData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_AssetData) +- [Resource `RewardData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_RewardData) +- [Resource `UserData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_UserData) +- [Struct `UserAssetBalance`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_UserAssetBalance) +- [Struct `ClaimerSet`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_ClaimerSet) +- [Struct `Accrued`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_Accrued) +- [Struct `AssetConfigUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_AssetConfigUpdated) +- [Struct `RewardsClaimed`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_RewardsClaimed) +- [Struct `RewardOracleUpdated`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_RewardOracleUpdated) +- [Struct `PullRewardsTransferStrategyInstalled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_PullRewardsTransferStrategyInstalled) +- [Struct `StakedTokenTransferStrategyInstalled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_StakedTokenTransferStrategyInstalled) - [Constants](#@Constants_0) -- [Function `initialize`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_initialize) -- [Function `create_asset_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_create_asset_data) -- [Function `rewards_controller_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_rewards_controller_address) -- [Function `rewards_controller_object`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_rewards_controller_object) -- [Function `get_claimer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_claimer) -- [Function `get_revision`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_revision) -- [Function `get_reward_oracle`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_reward_oracle) -- [Function `get_pull_rewards_transfer_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_pull_rewards_transfer_strategy) -- [Function `get_staked_token_transfer_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_staked_token_transfer_strategy) -- [Function `configure_assets`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_configure_assets) -- [Function `set_pull_rewards_transfer_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_set_pull_rewards_transfer_strategy) -- [Function `set_staked_token_transfer_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_set_staked_token_transfer_strategy) -- [Function `set_reward_oracle`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_set_reward_oracle) -- [Function `claim_rewards`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_claim_rewards) -- [Function `claim_all_rewards`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_claim_all_rewards) -- [Function `set_claimer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_set_claimer) -- [Function `set_reward_oracle_internal`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_set_reward_oracle_internal) -- [Function `get_rewards_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_rewards_data) -- [Function `get_asset_index`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_asset_index) -- [Function `get_distribution_end`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_distribution_end) -- [Function `get_rewards_by_asset`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_rewards_by_asset) -- [Function `get_rewards_list`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_rewards_list) -- [Function `get_user_asset_index`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_user_asset_index) -- [Function `get_user_accrued_rewards`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_user_accrued_rewards) -- [Function `get_user_rewards`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_user_rewards) -- [Function `get_all_user_rewards`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_all_user_rewards) -- [Function `set_distribution_end`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_set_distribution_end) -- [Function `set_emission_per_second`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_set_emission_per_second) -- [Function `get_asset_decimals`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_asset_decimals) -- [Function `get_emission_manager`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_rewards_controller_get_emission_manager) +- [Function `initialize`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_initialize) +- [Function `create_asset_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_create_asset_data) +- [Function `rewards_controller_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_rewards_controller_address) +- [Function `rewards_controller_object`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_rewards_controller_object) +- [Function `get_claimer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_claimer) +- [Function `get_revision`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_revision) +- [Function `get_reward_oracle`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_reward_oracle) +- [Function `get_pull_rewards_transfer_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_pull_rewards_transfer_strategy) +- [Function `get_staked_token_transfer_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_staked_token_transfer_strategy) +- [Function `configure_assets`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_configure_assets) +- [Function `set_pull_rewards_transfer_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_set_pull_rewards_transfer_strategy) +- [Function `set_staked_token_transfer_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_set_staked_token_transfer_strategy) +- [Function `set_reward_oracle`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_set_reward_oracle) +- [Function `claim_rewards`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_claim_rewards) +- [Function `claim_all_rewards`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_claim_all_rewards) +- [Function `set_claimer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_set_claimer) +- [Function `set_reward_oracle_internal`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_set_reward_oracle_internal) +- [Function `get_rewards_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_rewards_data) +- [Function `get_asset_index`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_asset_index) +- [Function `get_distribution_end`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_distribution_end) +- [Function `get_rewards_by_asset`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_rewards_by_asset) +- [Function `get_rewards_list`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_rewards_list) +- [Function `get_user_asset_index`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_user_asset_index) +- [Function `get_user_accrued_rewards`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_user_accrued_rewards) +- [Function `get_user_rewards`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_user_rewards) +- [Function `get_all_user_rewards`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_all_user_rewards) +- [Function `set_distribution_end`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_set_distribution_end) +- [Function `set_emission_per_second`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_set_emission_per_second) +- [Function `get_asset_decimals`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_asset_decimals) +- [Function `get_emission_manager`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_rewards_controller_get_emission_manager)
use 0x1::event;
@@ -57,151 +57,151 @@
 use 0x1::smart_table;
 use 0x1::timestamp;
 use 0x1::vector;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::transfer_strategy;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::transfer_strategy;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle;
 
- + ## Resource `RewardsControllerData`
#[resource_group_member(#[group = 0x1::object::ObjectGroup])]
-struct RewardsControllerData has key
+struct RewardsControllerData has key
 
- + ## Resource `AssetData` -
struct AssetData has drop, store, key
+
struct AssetData has drop, store, key
 
- + ## Resource `RewardData` -
struct RewardData has drop, store, key
+
struct RewardData has drop, store, key
 
- + ## Resource `UserData` -
struct UserData has copy, drop, store, key
+
struct UserData has copy, drop, store, key
 
- + ## Struct `UserAssetBalance` -
struct UserAssetBalance has copy, drop, store
+
struct UserAssetBalance has copy, drop, store
 
- + ## Struct `ClaimerSet`
#[event]
-struct ClaimerSet has drop, store
+struct ClaimerSet has drop, store
 
- + ## Struct `Accrued`
#[event]
-struct Accrued has drop, store
+struct Accrued has drop, store
 
- + ## Struct `AssetConfigUpdated`
#[event]
-struct AssetConfigUpdated has drop, store
+struct AssetConfigUpdated has drop, store
 
- + ## Struct `RewardsClaimed`
#[event]
-struct RewardsClaimed has drop, store
+struct RewardsClaimed has drop, store
 
- + ## Struct `RewardOracleUpdated`
#[event]
-struct RewardOracleUpdated has drop, store
+struct RewardOracleUpdated has drop, store
 
- + ## Struct `PullRewardsTransferStrategyInstalled`
#[event]
-struct PullRewardsTransferStrategyInstalled has drop, store
+struct PullRewardsTransferStrategyInstalled has drop, store
 
- + ## Struct `StakedTokenTransferStrategyInstalled`
#[event]
-struct StakedTokenTransferStrategyInstalled has drop, store
+struct StakedTokenTransferStrategyInstalled has drop, store
 
@@ -211,436 +211,436 @@ ## Constants - + -
const REVISION: u64 = 1;
+
const REVISION: u64 = 1;
 
- + -
const CLAIMER_UNAUTHORIZED: u64 = 1;
+
const CLAIMER_UNAUTHORIZED: u64 = 1;
 
- + -
const DISTRIBUTION_DOES_NOT_EXIST: u64 = 1;
+
const DISTRIBUTION_DOES_NOT_EXIST: u64 = 5;
 
- + -
const INDEX_OVERFLOW: u64 = 1;
+
const INDEX_OVERFLOW: u64 = 2;
 
- + -
const INVALID_INPUT: u64 = 1;
+
const INVALID_INPUT: u64 = 4;
 
- + -
const NOT_REWARDS_CONTROLLER_ADMIN: u64 = 1;
+
const NOT_REWARDS_CONTROLLER_ADMIN: u64 = 8;
 
- + -
const ONLY_EMISSION_MANAGER: u64 = 1;
+
const ONLY_EMISSION_MANAGER: u64 = 3;
 
- + -
const ORACLE_MUST_RETURN_PRICE: u64 = 1;
+
const ORACLE_MUST_RETURN_PRICE: u64 = 6;
 
- + -
const REWARDS_CONTROLLER_NAME: vector<u8> = [82, 69, 87, 65, 82, 68, 83, 95, 67, 79, 78, 84, 82, 79, 76, 76, 69, 82, 95, 78, 65, 77, 69];
+
const REWARDS_CONTROLLER_NAME: vector<u8> = [82, 69, 87, 65, 82, 68, 83, 95, 67, 79, 78, 84, 82, 79, 76, 76, 69, 82, 95, 78, 65, 77, 69];
 
- + -
const TRANSFER_ERROR: u64 = 1;
+
const TRANSFER_ERROR: u64 = 7;
 
- + ## Function `initialize` -
public fun initialize(sender: &signer, emission_manager: address)
+
public fun initialize(sender: &signer, emission_manager: address)
 
- + ## Function `create_asset_data` -
public fun create_asset_data(rewards: simple_map::SimpleMap<address, rewards_controller::RewardData>, available_rewards: simple_map::SimpleMap<u128, address>, available_rewards_count: u128, decimals: u8): rewards_controller::AssetData
+
public fun create_asset_data(rewards: simple_map::SimpleMap<address, rewards_controller::RewardData>, available_rewards: simple_map::SimpleMap<u128, address>, available_rewards_count: u128, decimals: u8): rewards_controller::AssetData
 
- + ## Function `rewards_controller_address`
#[view]
-public fun rewards_controller_address(): address
+public fun rewards_controller_address(): address
 
- + ## Function `rewards_controller_object`
#[view]
-public fun rewards_controller_object(): object::Object<rewards_controller::RewardsControllerData>
+public fun rewards_controller_object(): object::Object<rewards_controller::RewardsControllerData>
 
- + ## Function `get_claimer`
#[view]
-public fun get_claimer(user: address, rewards_controller_address: address): address
+public fun get_claimer(user: address, rewards_controller_address: address): address
 
- + ## Function `get_revision`
#[view]
-public fun get_revision(): u64
+public fun get_revision(): u64
 
- + ## Function `get_reward_oracle`
#[view]
-public fun get_reward_oracle(reward: address, rewards_controller_address: address): oracle::RewardOracle
+public fun get_reward_oracle(reward: address, rewards_controller_address: address): oracle::RewardOracle
 
- + ## Function `get_pull_rewards_transfer_strategy` -
public fun get_pull_rewards_transfer_strategy(reward: address, rewards_controller_address: address): transfer_strategy::PullRewardsTransferStrategy
+
public fun get_pull_rewards_transfer_strategy(reward: address, rewards_controller_address: address): transfer_strategy::PullRewardsTransferStrategy
 
- + ## Function `get_staked_token_transfer_strategy` -
public fun get_staked_token_transfer_strategy(reward: address, rewards_controller_address: address): transfer_strategy::StakedTokenTransferStrategy
+
public fun get_staked_token_transfer_strategy(reward: address, rewards_controller_address: address): transfer_strategy::StakedTokenTransferStrategy
 
- + ## Function `configure_assets` -
public fun configure_assets(caller: &signer, config: vector<transfer_strategy::RewardsConfigInput>, rewards_controller_address: address)
+
public fun configure_assets(caller: &signer, config: vector<transfer_strategy::RewardsConfigInput>, rewards_controller_address: address)
 
- + ## Function `set_pull_rewards_transfer_strategy` -
public fun set_pull_rewards_transfer_strategy(caller: &signer, reward: address, pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy, rewards_controller_address: address)
+
public fun set_pull_rewards_transfer_strategy(caller: &signer, reward: address, pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy, rewards_controller_address: address)
 
- + ## Function `set_staked_token_transfer_strategy` -
public fun set_staked_token_transfer_strategy(caller: &signer, reward: address, staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy, rewards_controller_address: address)
+
public fun set_staked_token_transfer_strategy(caller: &signer, reward: address, staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy, rewards_controller_address: address)
 
- + ## Function `set_reward_oracle` -
public fun set_reward_oracle(caller: &signer, reward: address, reward_oracle: oracle::RewardOracle, rewards_controller_address: address)
+
public fun set_reward_oracle(caller: &signer, reward: address, reward_oracle: oracle::RewardOracle, rewards_controller_address: address)
 
- + ## Function `claim_rewards` -
public fun claim_rewards(caller: &signer, assets: vector<address>, amount: u256, to: address, reward: address, rewards_controller_address: address): u256
+
public fun claim_rewards(caller: &signer, assets: vector<address>, amount: u256, to: address, reward: address, rewards_controller_address: address): u256
 
- + ## Function `claim_all_rewards` -
public fun claim_all_rewards(caller: &signer, assets: vector<address>, to: address, rewards_controller_address: address): (vector<address>, vector<u256>)
+
public fun claim_all_rewards(caller: &signer, assets: vector<address>, to: address, rewards_controller_address: address): (vector<address>, vector<u256>)
 
- + ## Function `set_claimer` -
public fun set_claimer(user: address, claimer: address, rewards_controller_address: address)
+
public fun set_claimer(user: address, claimer: address, rewards_controller_address: address)
 
- + ## Function `set_reward_oracle_internal` -
public fun set_reward_oracle_internal(reward: address, reward_oracle: oracle::RewardOracle)
+
public fun set_reward_oracle_internal(reward: address, reward_oracle: oracle::RewardOracle)
 
- + ## Function `get_rewards_data`
#[view]
-public fun get_rewards_data(asset: address, reward: address, rewards_controller_address: address): (u256, u256, u256, u256)
+public fun get_rewards_data(asset: address, reward: address, rewards_controller_address: address): (u256, u256, u256, u256)
 
- + ## Function `get_asset_index`
#[view]
-public fun get_asset_index(asset: address, reward: address, rewards_controller_address: address): (u256, u256)
+public fun get_asset_index(asset: address, reward: address, rewards_controller_address: address): (u256, u256)
 
- + ## Function `get_distribution_end`
#[view]
-public fun get_distribution_end(asset: address, reward: address, rewards_controller_address: address): u256
+public fun get_distribution_end(asset: address, reward: address, rewards_controller_address: address): u256
 
- + ## Function `get_rewards_by_asset`
#[view]
-public fun get_rewards_by_asset(asset: address, rewards_controller_address: address): vector<address>
+public fun get_rewards_by_asset(asset: address, rewards_controller_address: address): vector<address>
 
- + ## Function `get_rewards_list`
#[view]
-public fun get_rewards_list(rewards_controller_address: address): vector<address>
+public fun get_rewards_list(rewards_controller_address: address): vector<address>
 
- + ## Function `get_user_asset_index`
#[view]
-public fun get_user_asset_index(user: address, asset: address, reward: address, rewards_controller_address: address): u256
+public fun get_user_asset_index(user: address, asset: address, reward: address, rewards_controller_address: address): u256
 
- + ## Function `get_user_accrued_rewards`
#[view]
-public fun get_user_accrued_rewards(user: address, reward: address, rewards_controller_address: address): u256
+public fun get_user_accrued_rewards(user: address, reward: address, rewards_controller_address: address): u256
 
- + ## Function `get_user_rewards`
#[view]
-public fun get_user_rewards(assets: vector<address>, user: address, reward: address, rewards_controller_address: address): u256
+public fun get_user_rewards(assets: vector<address>, user: address, reward: address, rewards_controller_address: address): u256
 
- + ## Function `get_all_user_rewards`
#[view]
-public fun get_all_user_rewards(assets: vector<address>, user: address, rewards_controller_address: address): (vector<address>, vector<u256>)
+public fun get_all_user_rewards(assets: vector<address>, user: address, rewards_controller_address: address): (vector<address>, vector<u256>)
 
- + ## Function `set_distribution_end` -
public fun set_distribution_end(caller: &signer, asset: address, reward: address, new_distribution_end: u32, rewards_controller_address: address)
+
public fun set_distribution_end(caller: &signer, asset: address, reward: address, new_distribution_end: u32, rewards_controller_address: address)
 
- + ## Function `set_emission_per_second` -
public fun set_emission_per_second(caller: &signer, asset: address, rewards: vector<address>, new_emissions_per_second: vector<u128>, rewards_controller_address: address)
+
public fun set_emission_per_second(caller: &signer, asset: address, rewards: vector<address>, new_emissions_per_second: vector<u128>, rewards_controller_address: address)
 
- + ## Function `get_asset_decimals`
#[view]
-public fun get_asset_decimals(asset: address, rewards_controller_address: address): u8
+public fun get_asset_decimals(asset: address, rewards_controller_address: address): u8
 
- + ## Function `get_emission_manager`
#[view]
-public fun get_emission_manager(rewards_controller_address: address): address
+public fun get_emission_manager(rewards_controller_address: address): address
 
diff --git a/aave-core/doc/staked_token.md b/aave-core/doc/staked_token.md index f02c82c..be03d6d 100644 --- a/aave-core/doc/staked_token.md +++ b/aave-core/doc/staked_token.md @@ -1,58 +1,58 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::staked_token` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::staked_token` -- [Resource `MockStakedToken`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_staked_token_MockStakedToken) -- [Function `staked_token`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_staked_token_staked_token) -- [Function `stake`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_staked_token_stake) -- [Function `create_mock_staked_token`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_staked_token_create_mock_staked_token) +- [Resource `MockStakedToken`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_staked_token_MockStakedToken) +- [Function `staked_token`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_staked_token_staked_token) +- [Function `stake`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_staked_token_stake) +- [Function `create_mock_staked_token`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_staked_token_create_mock_staked_token)
- + ## Resource `MockStakedToken` -
struct MockStakedToken has copy, drop, store, key
+
struct MockStakedToken has copy, drop, store, key
 
- + ## Function `staked_token` -
public fun staked_token(mock_staked_token: &staked_token::MockStakedToken): address
+
public fun staked_token(mock_staked_token: &staked_token::MockStakedToken): address
 
- + ## Function `stake` -
public fun stake(_mock_staked_token: &staked_token::MockStakedToken, _to: address, _amount: u256)
+
public fun stake(_mock_staked_token: &staked_token::MockStakedToken, _to: address, _amount: u256)
 
- + ## Function `create_mock_staked_token` -
public fun create_mock_staked_token(addr: address): staked_token::MockStakedToken
+
public fun create_mock_staked_token(addr: address): staked_token::MockStakedToken
 
diff --git a/aave-core/doc/standard_token.md b/aave-core/doc/standard_token.md index 14e4773..bd4f6f8 100644 --- a/aave-core/doc/standard_token.md +++ b/aave-core/doc/standard_token.md @@ -1,27 +1,27 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::standard_token` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::standard_token` -- [Resource `ManagingRefs`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_ManagingRefs) -- [Struct `AaveTokenInitialized`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_AaveTokenInitialized) +- [Resource `ManagingRefs`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_ManagingRefs) +- [Struct `AaveTokenInitialized`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_AaveTokenInitialized) - [Constants](#@Constants_0) -- [Function `initialize`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_initialize) -- [Function `get_revision`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_get_revision) -- [Function `mint_to_primary_stores`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_mint_to_primary_stores) -- [Function `mint`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_mint) -- [Function `transfer_between_primary_stores`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_transfer_between_primary_stores) -- [Function `transfer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_transfer) -- [Function `burn_from_primary_stores`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_burn_from_primary_stores) -- [Function `burn`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_burn) -- [Function `set_primary_stores_frozen_status`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_set_primary_stores_frozen_status) -- [Function `set_frozen_status`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_set_frozen_status) -- [Function `withdraw_from_primary_stores`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_withdraw_from_primary_stores) -- [Function `withdraw`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_withdraw) -- [Function `deposit_to_primary_stores`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_deposit_to_primary_stores) -- [Function `deposit`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_standard_token_deposit) +- [Function `initialize`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_initialize) +- [Function `get_revision`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_get_revision) +- [Function `mint_to_primary_stores`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_mint_to_primary_stores) +- [Function `mint`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_mint) +- [Function `transfer_between_primary_stores`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_transfer_between_primary_stores) +- [Function `transfer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_transfer) +- [Function `burn_from_primary_stores`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_burn_from_primary_stores) +- [Function `burn`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_burn) +- [Function `set_primary_stores_frozen_status`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_set_primary_stores_frozen_status) +- [Function `set_frozen_status`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_set_frozen_status) +- [Function `withdraw_from_primary_stores`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_withdraw_from_primary_stores) +- [Function `withdraw`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_withdraw) +- [Function `deposit_to_primary_stores`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_deposit_to_primary_stores) +- [Function `deposit`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_standard_token_deposit)
use 0x1::error;
@@ -37,7 +37,7 @@
 
 
 
-
+
 
 ## Resource `ManagingRefs`
 
@@ -45,19 +45,19 @@ Hold refs to control the minting, transfer and burning of fungible assets.
 
 
 
#[resource_group_member(#[group = 0x1::object::ObjectGroup])]
-struct ManagingRefs has key
+struct ManagingRefs has key
 
- + ## Struct `AaveTokenInitialized`
#[event]
-struct AaveTokenInitialized has drop, store
+struct AaveTokenInitialized has drop, store
 
@@ -67,97 +67,97 @@ Hold refs to control the minting, transfer and burning of fungible assets. ## Constants - + -
const E_NOT_A_TOKEN_ADMIN: u64 = 1;
+
const E_NOT_A_TOKEN_ADMIN: u64 = 1;
 
- + -
const REVISION: u64 = 1;
+
const REVISION: u64 = 1;
 
- + Only fungible asset metadata owner can make changes. -
const ERR_NOT_OWNER: u64 = 1;
+
const ERR_NOT_OWNER: u64 = 1;
 
- + BurnRef error. -
const ERR_BURN_REF: u64 = 6;
+
const ERR_BURN_REF: u64 = 6;
 
- + The length of ref_flags is not 3. -
const ERR_INVALID_REF_FLAGS_LENGTH: u64 = 2;
+
const ERR_INVALID_REF_FLAGS_LENGTH: u64 = 2;
 
- + MintRef error. -
const ERR_MINT_REF: u64 = 4;
+
const ERR_MINT_REF: u64 = 4;
 
- + TransferRef error. -
const ERR_TRANSFER_REF: u64 = 5;
+
const ERR_TRANSFER_REF: u64 = 5;
 
- + The lengths of two vector do not equal. -
const ERR_VECTORS_LENGTH_MISMATCH: u64 = 3;
+
const ERR_VECTORS_LENGTH_MISMATCH: u64 = 3;
 
- + ## Function `initialize` Initialize metadata object and store the refs specified by ref_flags. -
public fun initialize(creator: &signer, maximum_supply: u128, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String, ref_flags: vector<bool>, underlying_asset_address: address, is_coin_underlying: bool)
+
public fun initialize(creator: &signer, maximum_supply: u128, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String, ref_flags: vector<bool>, underlying_asset_address: address, is_coin_underlying: bool)
 
- + ## Function `get_revision` @@ -165,36 +165,36 @@ Return the revision of the aave token implementation
#[view]
-public fun get_revision(): u64
+public fun get_revision(): u64
 
- + ## Function `mint_to_primary_stores` Mint as the owner of metadata object to the primary fungible stores of the accounts with amounts of FAs. -
public entry fun mint_to_primary_stores(admin: &signer, asset: object::Object<fungible_asset::Metadata>, to: vector<address>, amounts: vector<u64>)
+
public entry fun mint_to_primary_stores(admin: &signer, asset: object::Object<fungible_asset::Metadata>, to: vector<address>, amounts: vector<u64>)
 
- + ## Function `mint` Mint as the owner of metadata object to multiple fungible stores with amounts of FAs. -
public entry fun mint(admin: &signer, asset: object::Object<fungible_asset::Metadata>, stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>)
+
public entry fun mint(admin: &signer, asset: object::Object<fungible_asset::Metadata>, stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>)
 
- + ## Function `transfer_between_primary_stores` @@ -202,84 +202,84 @@ Transfer as the owner of metadata object ignoring frozen field from accounts. -
public entry fun transfer_between_primary_stores(admin: &signer, asset: object::Object<fungible_asset::Metadata>, from: vector<address>, to: vector<address>, amounts: vector<u64>)
+
public entry fun transfer_between_primary_stores(admin: &signer, asset: object::Object<fungible_asset::Metadata>, from: vector<address>, to: vector<address>, amounts: vector<u64>)
 
- + ## Function `transfer` Transfer as the owner of metadata object ignoring frozen field between fungible stores. -
public entry fun transfer(admin: &signer, asset: object::Object<fungible_asset::Metadata>, sender_stores: vector<object::Object<fungible_asset::FungibleStore>>, receiver_stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>)
+
public entry fun transfer(admin: &signer, asset: object::Object<fungible_asset::Metadata>, sender_stores: vector<object::Object<fungible_asset::FungibleStore>>, receiver_stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>)
 
- + ## Function `burn_from_primary_stores` Burn fungible assets as the owner of metadata object from the primary stores of accounts. -
public entry fun burn_from_primary_stores(admin: &signer, asset: object::Object<fungible_asset::Metadata>, from: vector<address>, amounts: vector<u64>)
+
public entry fun burn_from_primary_stores(admin: &signer, asset: object::Object<fungible_asset::Metadata>, from: vector<address>, amounts: vector<u64>)
 
- + ## Function `burn` Burn fungible assets as the owner of metadata object from fungible stores. -
public entry fun burn(admin: &signer, asset: object::Object<fungible_asset::Metadata>, stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>)
+
public entry fun burn(admin: &signer, asset: object::Object<fungible_asset::Metadata>, stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>)
 
- + ## Function `set_primary_stores_frozen_status` Freeze/unfreeze the primary stores of accounts so they cannot transfer or receive fungible assets. -
public entry fun set_primary_stores_frozen_status(admin: &signer, asset: object::Object<fungible_asset::Metadata>, accounts: vector<address>, frozen: bool)
+
public entry fun set_primary_stores_frozen_status(admin: &signer, asset: object::Object<fungible_asset::Metadata>, accounts: vector<address>, frozen: bool)
 
- + ## Function `set_frozen_status` Freeze/unfreeze the fungible stores so they cannot transfer or receive fungible assets. -
public entry fun set_frozen_status(admin: &signer, asset: object::Object<fungible_asset::Metadata>, stores: vector<object::Object<fungible_asset::FungibleStore>>, frozen: bool)
+
public entry fun set_frozen_status(admin: &signer, asset: object::Object<fungible_asset::Metadata>, stores: vector<object::Object<fungible_asset::FungibleStore>>, frozen: bool)
 
- + ## Function `withdraw_from_primary_stores` Withdraw as the owner of metadata object ignoring frozen field from primary fungible stores of accounts. -
public fun withdraw_from_primary_stores(admin: &signer, asset: object::Object<fungible_asset::Metadata>, from: vector<address>, amounts: vector<u64>): fungible_asset::FungibleAsset
+
public fun withdraw_from_primary_stores(admin: &signer, asset: object::Object<fungible_asset::Metadata>, from: vector<address>, amounts: vector<u64>): fungible_asset::FungibleAsset
 
- + ## Function `withdraw` @@ -287,12 +287,12 @@ Withdraw as the owner of metadata object ignoring frozen field from return a fungible asset fa where fa.amount = sum(amounts). -
public fun withdraw(admin: &signer, asset: object::Object<fungible_asset::Metadata>, stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>): fungible_asset::FungibleAsset
+
public fun withdraw(admin: &signer, asset: object::Object<fungible_asset::Metadata>, stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>): fungible_asset::FungibleAsset
 
- + ## Function `deposit_to_primary_stores` @@ -300,12 +300,12 @@ Deposit as the owner of metadata object ignoring frozen field to pr single source of fungible asset. -
public fun deposit_to_primary_stores(admin: &signer, fa: &mut fungible_asset::FungibleAsset, from: vector<address>, amounts: vector<u64>)
+
public fun deposit_to_primary_stores(admin: &signer, fa: &mut fungible_asset::FungibleAsset, from: vector<address>, amounts: vector<u64>)
 
- + ## Function `deposit` @@ -313,5 +313,5 @@ Deposit as the owner of metadata object ignoring frozen field from is fa.amount - sum(amounts). -
public fun deposit(admin: &signer, fa: &mut fungible_asset::FungibleAsset, stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>)
+
public fun deposit(admin: &signer, fa: &mut fungible_asset::FungibleAsset, stores: vector<object::Object<fungible_asset::FungibleStore>>, amounts: vector<u64>)
 
diff --git a/aave-core/doc/stream.md b/aave-core/doc/stream.md index 9cc6d69..0cdc3c3 100644 --- a/aave-core/doc/stream.md +++ b/aave-core/doc/stream.md @@ -1,30 +1,30 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::stream` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::stream` -- [Resource `Stream`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_stream_Stream) +- [Resource `Stream`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_stream_Stream) - [Constants](#@Constants_0) -- [Function `recipient`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_stream_recipient) -- [Function `is_entity`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_stream_is_entity) -- [Function `get_stream`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_stream_get_stream) -- [Function `set_remaining_balance`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_stream_set_remaining_balance) -- [Function `create_stream`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_stream_create_stream) +- [Function `recipient`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_stream_recipient) +- [Function `is_entity`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_stream_is_entity) +- [Function `get_stream`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_stream_get_stream) +- [Function `set_remaining_balance`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_stream_set_remaining_balance) +- [Function `create_stream`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_stream_create_stream)
- + ## Resource `Stream` -
struct Stream has drop, store, key
+
struct Stream has drop, store, key
 
@@ -34,73 +34,73 @@ ## Constants - + -
const TEST_FAILED: u64 = 2;
+
const TEST_FAILED: u64 = 2;
 
- + -
const TEST_SUCCESS: u64 = 1;
+
const TEST_SUCCESS: u64 = 1;
 
- + ## Function `recipient` -
public fun recipient(stream: &stream::Stream): address
+
public fun recipient(stream: &stream::Stream): address
 
- + ## Function `is_entity` -
public fun is_entity(stream: &stream::Stream): bool
+
public fun is_entity(stream: &stream::Stream): bool
 
- + ## Function `get_stream` -
public fun get_stream(stream: &stream::Stream): (address, address, u256, address, u256, u256, u256, u256)
+
public fun get_stream(stream: &stream::Stream): (address, address, u256, address, u256, u256, u256, u256)
 
- + ## Function `set_remaining_balance` -
public fun set_remaining_balance(stream: &mut stream::Stream, remaining_balance: u256)
+
public fun set_remaining_balance(stream: &mut stream::Stream, remaining_balance: u256)
 
- + ## Function `create_stream` -
public fun create_stream(deposit: u256, rate_per_second: u256, remaining_balance: u256, start_time: u256, stop_time: u256, recipient: address, sender: address, token_address: address, is_entity: bool): stream::Stream
+
public fun create_stream(deposit: u256, rate_per_second: u256, remaining_balance: u256, start_time: u256, stop_time: u256, recipient: address, sender: address, token_address: address, is_entity: bool): stream::Stream
 
diff --git a/aave-core/doc/supply_logic.md b/aave-core/doc/supply_logic.md index df72da9..1655040 100644 --- a/aave-core/doc/supply_logic.md +++ b/aave-core/doc/supply_logic.md @@ -1,135 +1,169 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::supply_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::supply_logic` -- [Struct `Supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_supply_logic_Supply) -- [Struct `Withdraw`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_supply_logic_Withdraw) -- [Struct `ReserveUsedAsCollateralEnabled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_supply_logic_ReserveUsedAsCollateralEnabled) -- [Struct `ReserveUsedAsCollateralDisabled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_supply_logic_ReserveUsedAsCollateralDisabled) -- [Function `supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_supply_logic_supply) -- [Function `withdraw`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_supply_logic_withdraw) -- [Function `finalize_transfer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_supply_logic_finalize_transfer) -- [Function `set_user_use_reserve_as_collateral`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_supply_logic_set_user_use_reserve_as_collateral) -- [Function `deposit`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_supply_logic_deposit) +- [Struct `Supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_supply_logic_Supply) +- [Struct `Withdraw`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_supply_logic_Withdraw) +- [Struct `ReserveUsedAsCollateralEnabled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_supply_logic_ReserveUsedAsCollateralEnabled) +- [Struct `ReserveUsedAsCollateralDisabled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_supply_logic_ReserveUsedAsCollateralDisabled) +- [Function `supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_supply_logic_supply) +- [Function `withdraw`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_supply_logic_withdraw) +- [Function `finalize_transfer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_supply_logic_finalize_transfer) +- [Function `set_user_use_reserve_as_collateral`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_supply_logic_set_user_use_reserve_as_collateral)
use 0x1::event;
 use 0x1::signer;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::emode_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool_validation;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::validation_logic;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::emode_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool_validation;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::validation_logic;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `Supply` +@dev Emitted on supply() +@param reserve The address of the underlying asset of the reserve +@param user The address initiating the supply +@param on_behalf_of The beneficiary of the supply, receiving the aTokens +@param amount The amount supplied +@param referral_code The referral code used
#[event]
-struct Supply has copy, drop, store
+struct Supply has copy, drop, store
 
- + ## Struct `Withdraw` +@dev Emitted on withdraw() +@param reserve The address of the underlying asset being withdrawn +@param user The address initiating the withdrawal, owner of aTokens +@param to The address that will receive the underlying +@param amount The amount to be withdrawn
#[event]
-struct Withdraw has drop, store
+struct Withdraw has drop, store
 
- + ## Struct `ReserveUsedAsCollateralEnabled` +@dev Emitted on setUserUseReserveAsCollateral() +@param reserve The address of the underlying asset of the reserve +@param user The address of the user enabling the usage as collateral
#[event]
-struct ReserveUsedAsCollateralEnabled has drop, store
+struct ReserveUsedAsCollateralEnabled has drop, store
 
- + ## Struct `ReserveUsedAsCollateralDisabled` +@dev Emitted on setUserUseReserveAsCollateral() +@param reserve The address of the underlying asset of the reserve +@param user The address of the user enabling the usage as collateral
#[event]
-struct ReserveUsedAsCollateralDisabled has drop, store
+struct ReserveUsedAsCollateralDisabled has drop, store
 
- + ## Function `supply` +@notice Supplies an amount of underlying asset into the reserve, receiving in return overlying aTokens. +- E.g. User supplies 100 USDC and gets in return 100 aUSDC +@param account The account that will supply the asset +@param asset The address of the underlying asset to supply +@param amount The amount to be supplied +@param on_behalf_of The address that will receive the aTokens, same as msg.sender if the user +wants to receive them on his own wallet, or a different address if the beneficiary of aTokens +is a different wallet +@param referral_code Code used to register the integrator originating the operation, for potential rewards. +0 if the action is executed directly by the user, without any middle-man -
public entry fun supply(account: &signer, asset: address, amount: u256, on_behalf_of: address, referral_code: u16)
+
public entry fun supply(account: &signer, asset: address, amount: u256, on_behalf_of: address, referral_code: u16)
 
- + ## Function `withdraw` +@notice Withdraws an amount of underlying asset from the reserve, burning the equivalent aTokens owned +E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC +@param asset The address of the underlying asset to withdraw +@param amount The underlying amount to be withdrawn +- Send the value type(uint256).max in order to withdraw the whole aToken balance +@param to The address that will receive the underlying, same as msg.sender if the user +wants to receive it on his own wallet, or a different address if the beneficiary is a +different wallet -
public entry fun withdraw(account: &signer, asset: address, amount: u256, to: address)
+
public entry fun withdraw(account: &signer, asset: address, amount: u256, to: address)
 
- + ## Function `finalize_transfer` +@notice Validates and finalizes an aToken transfer +@dev Only callable by the overlying aToken of the asset +@param asset The address of the underlying asset of the aToken +@param from The user from which the aTokens are transferred +@param to The user receiving the aTokens +@param amount The amount being transferred/withdrawn +@param balance_from_before The aToken balance of the from user before the transfer +@param balance_to_before The aToken balance of the to user before the transfer -
public entry fun finalize_transfer(account: &signer, asset: address, from: address, to: address, amount: u256, balance_from_before: u256, balance_to_before: u256)
+
public entry fun finalize_transfer(account: &signer, asset: address, from: address, to: address, amount: u256, balance_from_before: u256, balance_to_before: u256)
 
- + ## Function `set_user_use_reserve_as_collateral` +@notice Allows suppliers to enable/disable a specific supplied asset as collateral +@param asset The address of the underlying asset supplied +@param use_as_collateral True if the user wants to use the supply as collateral, false otherwise -
public entry fun set_user_use_reserve_as_collateral(account: &signer, asset: address, use_as_collateral: bool)
-
- - - - - -## Function `deposit` - - - -
public entry fun deposit(account: &signer, asset: address, amount: u256, on_behalf_of: address, referral_code: u16)
+
public entry fun set_user_use_reserve_as_collateral(account: &signer, asset: address, use_as_collateral: bool)
 
diff --git a/aave-core/doc/token_base.md b/aave-core/doc/token_base.md index ce26af7..bc55180 100644 --- a/aave-core/doc/token_base.md +++ b/aave-core/doc/token_base.md @@ -1,43 +1,40 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::token_base` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::token_base` -- [Struct `Transfer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_Transfer) -- [Struct `Mint`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_Mint) -- [Struct `Burn`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_Burn) -- [Struct `UserState`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_UserState) -- [Resource `UserStateMap`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_UserStateMap) -- [Struct `TokenData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_TokenData) -- [Resource `TokenMap`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_TokenMap) -- [Resource `ManagedFungibleAsset`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_ManagedFungibleAsset) +- [Struct `Transfer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_Transfer) +- [Struct `Mint`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_Mint) +- [Struct `Burn`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_Burn) +- [Struct `UserState`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_UserState) +- [Resource `UserStateMap`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_UserStateMap) +- [Struct `TokenData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_TokenData) +- [Resource `TokenMap`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_TokenMap) +- [Resource `ManagedFungibleAsset`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_ManagedFungibleAsset) - [Constants](#@Constants_0) -- [Function `get_user_state`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_get_user_state) -- [Function `get_token_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_get_token_data) -- [Function `get_underlying_asset`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_get_underlying_asset) -- [Function `get_treasury_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_get_treasury_address) -- [Function `get_resource_account`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_get_resource_account) -- [Function `get_previous_index`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_get_previous_index) -- [Function `get_scale_total_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_get_scale_total_supply) -- [Function `create_a_token`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_create_a_token) -- [Function `create_variable_token`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_create_variable_token) -- [Function `mint_scaled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_mint_scaled) -- [Function `burn_scaled`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_burn_scaled) -- [Function `transfer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_transfer) -- [Function `transfer_internal`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_transfer_internal) -- [Function `scale_balance_of`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_scale_balance_of) -- [Function `balance_of`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_balance_of) -- [Function `scale_total_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_scale_total_supply) -- [Function `supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_supply) -- [Function `get_scaled_user_balance_and_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_get_scaled_user_balance_and_supply) -- [Function `maximum`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_maximum) -- [Function `name`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_name) -- [Function `symbol`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_symbol) -- [Function `decimals`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_decimals) -- [Function `only_pool_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_only_pool_admin) -- [Function `only_token_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_token_base_only_token_admin) +- [Function `get_user_state`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_get_user_state) +- [Function `get_token_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_get_token_data) +- [Function `get_underlying_asset`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_get_underlying_asset) +- [Function `get_treasury_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_get_treasury_address) +- [Function `get_resource_account`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_get_resource_account) +- [Function `get_previous_index`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_get_previous_index) +- [Function `get_scaled_total_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_get_scaled_total_supply) +- [Function `create_a_token`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_create_a_token) +- [Function `create_variable_token`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_create_variable_token) +- [Function `mint_scaled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_mint_scaled) +- [Function `burn_scaled`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_burn_scaled) +- [Function `transfer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_transfer) +- [Function `transfer_internal`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_transfer_internal) +- [Function `scaled_balance_of`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_scaled_balance_of) +- [Function `scaled_total_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_scaled_total_supply) +- [Function `get_scaled_user_balance_and_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_get_scaled_user_balance_and_supply) +- [Function `name`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_name) +- [Function `symbol`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_symbol) +- [Function `decimals`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_decimals) +- [Function `only_pool_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_only_pool_admin) +- [Function `only_token_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_token_base_only_token_admin)
use 0x1::event;
@@ -49,94 +46,111 @@
 use 0x1::smart_table;
 use 0x1::string;
 use 0x1::string_utils;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
 
- + ## Struct `Transfer` +@dev Emitted when value tokens are moved from one account (from) to +another (to). + +Note that value may be zero.
#[event]
-struct Transfer has drop, store
+struct Transfer has drop, store
 
- + ## Struct `Mint` +@dev Emitted after the mint action +@param caller The address performing the mint +@param on_behalf_of The address of the user that will receive the minted tokens +@param value The scaled-up amount being minted (based on user entered amount and balance increase from interest) +@param balance_increase The increase in scaled-up balance since the last action of 'onBehalfOf' +@param index The next liquidity index of the reserve
#[event]
-struct Mint has drop, store
+struct Mint has drop, store
 
- + ## Struct `Burn` +@dev Emitted after the burn action +@dev If the burn function does not involve a transfer of the underlying asset, the target defaults to zero address +@param from The address from which the tokens will be burned +@param target The address that will receive the underlying, if any +@param value The scaled-up amount being burned (user entered amount - balance increase from interest) +@param balance_increase The increase in scaled-up balance since the last action of 'from' +@param index The next liquidity index of the reserve
#[event]
-struct Burn has drop, store
+struct Burn has drop, store
 
- + ## Struct `UserState` -
struct UserState has copy, drop, store
+
struct UserState has copy, drop, store
 
- + ## Resource `UserStateMap` -
struct UserStateMap has key
+
struct UserStateMap has key
 
- + ## Struct `TokenData` -
struct TokenData has copy, drop, store
+
struct TokenData has copy, drop, store
 
- + ## Resource `TokenMap` -
struct TokenMap has key
+
struct TokenMap has key
 
- + ## Resource `ManagedFungibleAsset` @@ -144,7 +158,7 @@ Hold refs to control the minting, transfer and burning of fungible assets.
#[resource_group_member(#[group = 0x1::object::ObjectGroup])]
-struct ManagedFungibleAsset has key
+struct ManagedFungibleAsset has key
 
@@ -154,301 +168,268 @@ Hold refs to control the minting, transfer and burning of fungible assets. ## Constants - + Only fungible asset metadata owner can make changes. -
const ENOT_OWNER: u64 = 1;
+
const ENOT_OWNER: u64 = 1;
 
- + -
const E_ACCOUNT_NOT_EXISTS: u64 = 3;
+
const E_ACCOUNT_NOT_EXISTS: u64 = 3;
 
- + -
const E_TOKEN_ALREADY_EXISTS: u64 = 2;
+
const E_TOKEN_ALREADY_EXISTS: u64 = 2;
 
- + -
const E_TOKEN_NOT_EXISTS: u64 = 4;
+
const E_TOKEN_NOT_EXISTS: u64 = 4;
 
- + ## Function `get_user_state` -
public fun get_user_state(user: address, token_metadata_address: address): token_base::UserState
+
public fun get_user_state(user: address, token_metadata_address: address): token_base::UserState
 
- + ## Function `get_token_data` -
public fun get_token_data(token_metadata_address: address): token_base::TokenData
+
public fun get_token_data(token_metadata_address: address): token_base::TokenData
 
- + ## Function `get_underlying_asset` -
public fun get_underlying_asset(token_data: &token_base::TokenData): address
+
public fun get_underlying_asset(token_data: &token_base::TokenData): address
 
- + ## Function `get_treasury_address` -
public fun get_treasury_address(token_data: &token_base::TokenData): address
+
public fun get_treasury_address(token_data: &token_base::TokenData): address
 
- + ## Function `get_resource_account` -
public fun get_resource_account(token_data: &token_base::TokenData): address
+
public fun get_resource_account(token_data: &token_base::TokenData): address
 
- + ## Function `get_previous_index` -
public fun get_previous_index(user: address, metadata_address: address): u256
+
public fun get_previous_index(user: address, metadata_address: address): u256
 
- + -## Function `get_scale_total_supply` +## Function `get_scaled_total_supply` -
public fun get_scale_total_supply(token_data: &token_base::TokenData): u256
+
public fun get_scaled_total_supply(token_data: &token_base::TokenData): u256
 
- + ## Function `create_a_token` -
public(friend) fun create_a_token(signer: &signer, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String, underlying_asset: address, treasury: address, resource_account: address)
+
public(friend) fun create_a_token(signer: &signer, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String, underlying_asset: address, treasury: address, resource_account: address)
 
- + ## Function `create_variable_token` -
public(friend) fun create_variable_token(signer: &signer, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String, underlying_asset: address)
+
public(friend) fun create_variable_token(signer: &signer, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String, underlying_asset: address)
 
- + ## Function `mint_scaled` -
public(friend) fun mint_scaled(caller: address, on_behalf_of: address, amount: u256, index: u256, metadata_address: address)
+
public(friend) fun mint_scaled(caller: address, on_behalf_of: address, amount: u256, index: u256, metadata_address: address)
 
- + ## Function `burn_scaled` -
public(friend) fun burn_scaled(user: address, target: address, amount: u256, index: u256, metadata_address: address)
+
public(friend) fun burn_scaled(user: address, target: address, amount: u256, index: u256, metadata_address: address)
 
- + ## Function `transfer` -
public(friend) fun transfer(sender: address, recipient: address, amount: u256, index: u256, metadata_address: address)
+
public(friend) fun transfer(sender: address, recipient: address, amount: u256, index: u256, metadata_address: address)
 
- + ## Function `transfer_internal` -
public fun transfer_internal(from: address, to: address, amount: u64, metadata_address: address)
+
public(friend) fun transfer_internal(from: address, to: address, amount: u64, metadata_address: address)
 
- + -## Function `scale_balance_of` +## Function `scaled_balance_of` -
public fun scale_balance_of(owner: address, metadata_address: address): u256
+
public fun scaled_balance_of(owner: address, metadata_address: address): u256
 
- + -## Function `balance_of` +## Function `scaled_total_supply` -
public fun balance_of(owner: address, metadata_address: address): u256
+
public fun scaled_total_supply(metadata_address: address): u256
 
- - -## Function `scale_total_supply` - - - -
public fun scale_total_supply(metadata_address: address): u256
-
- - - - - -## Function `supply` - - - -
public fun supply(metadata_address: address): option::Option<u128>
-
- - - - + ## Function `get_scaled_user_balance_and_supply` -
public fun get_scaled_user_balance_and_supply(owner: address, metadata_address: address): (u256, u256)
-
- - - - - -## Function `maximum` - - - -
public fun maximum(metadata_address: address): option::Option<u128>
+
public fun get_scaled_user_balance_and_supply(owner: address, metadata_address: address): (u256, u256)
 
- + ## Function `name` -
public fun name(metadata_address: address): string::String
+
public fun name(metadata_address: address): string::String
 
- + ## Function `symbol` -
public fun symbol(metadata_address: address): string::String
+
public fun symbol(metadata_address: address): string::String
 
- + ## Function `decimals` -
public fun decimals(metadata_address: address): u8
+
public fun decimals(metadata_address: address): u8
 
- + ## Function `only_pool_admin` -
public fun only_pool_admin(account: &signer)
+
public fun only_pool_admin(account: &signer)
 
- + ## Function `only_token_admin` -
public fun only_token_admin(account: &signer)
+
public fun only_token_admin(account: &signer)
 
diff --git a/aave-core/doc/transfer_strategy.md b/aave-core/doc/transfer_strategy.md index e95fbdf..5a4d656 100644 --- a/aave-core/doc/transfer_strategy.md +++ b/aave-core/doc/transfer_strategy.md @@ -1,93 +1,93 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::transfer_strategy` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::transfer_strategy` -- [Resource `PullRewardsTransferStrategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_PullRewardsTransferStrategy) -- [Resource `StakedTokenTransferStrategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_StakedTokenTransferStrategy) -- [Struct `RewardsConfigInput`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_RewardsConfigInput) -- [Struct `EmergencyWithdrawal`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_EmergencyWithdrawal) +- [Resource `PullRewardsTransferStrategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_PullRewardsTransferStrategy) +- [Resource `StakedTokenTransferStrategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_StakedTokenTransferStrategy) +- [Struct `RewardsConfigInput`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_RewardsConfigInput) +- [Struct `EmergencyWithdrawal`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_EmergencyWithdrawal) - [Constants](#@Constants_0) -- [Function `check_is_emission_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_check_is_emission_admin) -- [Function `create_pull_rewards_transfer_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_create_pull_rewards_transfer_strategy) -- [Function `pull_rewards_transfer_strategy_perform_transfer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_pull_rewards_transfer_strategy_perform_transfer) -- [Function `pull_rewards_transfer_strategy_get_rewards_vault`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_pull_rewards_transfer_strategy_get_rewards_vault) -- [Function `pull_rewards_transfer_strategy_get_incentives_controller`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_pull_rewards_transfer_strategy_get_incentives_controller) -- [Function `pull_rewards_transfer_strategy_get_rewards_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_pull_rewards_transfer_strategy_get_rewards_admin) -- [Function `create_staked_token_transfer_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_create_staked_token_transfer_strategy) -- [Function `staked_token_transfer_strategy_perform_transfer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_staked_token_transfer_strategy_perform_transfer) -- [Function `staked_token_transfer_strategy_get_stake_contract`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_staked_token_transfer_strategy_get_stake_contract) -- [Function `staked_token_transfer_strategy_get_underlying_token`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_staked_token_transfer_strategy_get_underlying_token) -- [Function `staked_token_transfer_strategy_get_incentives_controller`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_staked_token_transfer_strategy_get_incentives_controller) -- [Function `staked_token_transfer_strategy_get_rewards_admin`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_staked_token_transfer_strategy_get_rewards_admin) -- [Function `get_reward`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_get_reward) -- [Function `get_reward_oracle`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_get_reward_oracle) -- [Function `get_asset`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_get_asset) -- [Function `get_total_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_get_total_supply) -- [Function `get_emission_per_second`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_get_emission_per_second) -- [Function `get_distribution_end`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_get_distribution_end) -- [Function `set_total_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_set_total_supply) -- [Function `pull_rewards_transfer_strategy_get_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_pull_rewards_transfer_strategy_get_strategy) -- [Function `staked_token_transfer_strategy_get_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_staked_token_transfer_strategy_get_strategy) -- [Function `validate_rewards_config_input`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_validate_rewards_config_input) -- [Function `has_pull_rewards_transfer_strategy`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_has_pull_rewards_transfer_strategy) -- [Function `emit_emergency_withdrawal_event`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_transfer_strategy_emit_emergency_withdrawal_event) +- [Function `check_is_emission_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_check_is_emission_admin) +- [Function `create_pull_rewards_transfer_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_create_pull_rewards_transfer_strategy) +- [Function `pull_rewards_transfer_strategy_perform_transfer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_pull_rewards_transfer_strategy_perform_transfer) +- [Function `pull_rewards_transfer_strategy_get_rewards_vault`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_pull_rewards_transfer_strategy_get_rewards_vault) +- [Function `pull_rewards_transfer_strategy_get_incentives_controller`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_pull_rewards_transfer_strategy_get_incentives_controller) +- [Function `pull_rewards_transfer_strategy_get_rewards_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_pull_rewards_transfer_strategy_get_rewards_admin) +- [Function `create_staked_token_transfer_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_create_staked_token_transfer_strategy) +- [Function `staked_token_transfer_strategy_perform_transfer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_staked_token_transfer_strategy_perform_transfer) +- [Function `staked_token_transfer_strategy_get_stake_contract`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_staked_token_transfer_strategy_get_stake_contract) +- [Function `staked_token_transfer_strategy_get_underlying_token`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_staked_token_transfer_strategy_get_underlying_token) +- [Function `staked_token_transfer_strategy_get_incentives_controller`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_staked_token_transfer_strategy_get_incentives_controller) +- [Function `staked_token_transfer_strategy_get_rewards_admin`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_staked_token_transfer_strategy_get_rewards_admin) +- [Function `get_reward`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_get_reward) +- [Function `get_reward_oracle`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_get_reward_oracle) +- [Function `get_asset`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_get_asset) +- [Function `get_total_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_get_total_supply) +- [Function `get_emission_per_second`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_get_emission_per_second) +- [Function `get_distribution_end`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_get_distribution_end) +- [Function `set_total_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_set_total_supply) +- [Function `pull_rewards_transfer_strategy_get_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_pull_rewards_transfer_strategy_get_strategy) +- [Function `staked_token_transfer_strategy_get_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_staked_token_transfer_strategy_get_strategy) +- [Function `validate_rewards_config_input`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_validate_rewards_config_input) +- [Function `has_pull_rewards_transfer_strategy`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_has_pull_rewards_transfer_strategy) +- [Function `emit_emergency_withdrawal_event`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_transfer_strategy_emit_emergency_withdrawal_event)
use 0x1::event;
 use 0x1::option;
 use 0x1::signer;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::staked_token;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::underlying_token_factory;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::staked_token;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle;
 
- + ## Resource `PullRewardsTransferStrategy` -
struct PullRewardsTransferStrategy has copy, drop, store, key
+
struct PullRewardsTransferStrategy has copy, drop, store, key
 
- + ## Resource `StakedTokenTransferStrategy` -
struct StakedTokenTransferStrategy has copy, drop, store, key
+
struct StakedTokenTransferStrategy has copy, drop, store, key
 
- + ## Struct `RewardsConfigInput` -
struct RewardsConfigInput has drop, store
+
struct RewardsConfigInput has drop, store
 
- + ## Struct `EmergencyWithdrawal`
#[event]
-struct EmergencyWithdrawal has drop, store
+struct EmergencyWithdrawal has drop, store
 
@@ -97,318 +97,318 @@ ## Constants - + -
const CALLER_NOT_INCENTIVES_CONTROLLER: u64 = 1;
+
const CALLER_NOT_INCENTIVES_CONTROLLER: u64 = 1;
 
- + -
const EMISSION_MANAGER_NAME: vector<u8> = [69, 77, 73, 83, 83, 73, 79, 78, 95, 77, 65, 78, 65, 71, 69, 82];
+
const EMISSION_MANAGER_NAME: vector<u8> = [69, 77, 73, 83, 83, 73, 79, 78, 95, 77, 65, 78, 65, 71, 69, 82];
 
- + -
const NOT_EMISSION_ADMIN: u64 = 1;
+
const NOT_EMISSION_ADMIN: u64 = 1;
 
- + -
const ONLY_REWARDS_ADMIN: u64 = 1;
+
const ONLY_REWARDS_ADMIN: u64 = 1;
 
- + -
const REWARD_TOKEN_NOT_STAKE_CONTRACT: u64 = 1;
+
const REWARD_TOKEN_NOT_STAKE_CONTRACT: u64 = 1;
 
- + -
const TOO_MANY_STRATEGIES: u64 = 1;
+
const TOO_MANY_STRATEGIES: u64 = 1;
 
- + ## Function `check_is_emission_admin` -
public fun check_is_emission_admin(account: address)
+
public fun check_is_emission_admin(account: address)
 
- + ## Function `create_pull_rewards_transfer_strategy` -
public fun create_pull_rewards_transfer_strategy(rewards_admin: address, incentives_controller: address, rewards_vault: address): transfer_strategy::PullRewardsTransferStrategy
+
public fun create_pull_rewards_transfer_strategy(rewards_admin: address, incentives_controller: address, rewards_vault: address): transfer_strategy::PullRewardsTransferStrategy
 
- + ## Function `pull_rewards_transfer_strategy_perform_transfer` -
public fun pull_rewards_transfer_strategy_perform_transfer(caller: &signer, to: address, reward: address, amount: u256, pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy): bool
+
public fun pull_rewards_transfer_strategy_perform_transfer(caller: &signer, to: address, reward: address, amount: u256, pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy): bool
 
- + ## Function `pull_rewards_transfer_strategy_get_rewards_vault` -
public fun pull_rewards_transfer_strategy_get_rewards_vault(pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy): address
+
public fun pull_rewards_transfer_strategy_get_rewards_vault(pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy): address
 
- + ## Function `pull_rewards_transfer_strategy_get_incentives_controller` -
public fun pull_rewards_transfer_strategy_get_incentives_controller(pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy): address
+
public fun pull_rewards_transfer_strategy_get_incentives_controller(pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy): address
 
- + ## Function `pull_rewards_transfer_strategy_get_rewards_admin` -
public fun pull_rewards_transfer_strategy_get_rewards_admin(pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy): address
+
public fun pull_rewards_transfer_strategy_get_rewards_admin(pull_rewards_transfer_strategy: transfer_strategy::PullRewardsTransferStrategy): address
 
- + ## Function `create_staked_token_transfer_strategy` -
public fun create_staked_token_transfer_strategy(rewards_admin: address, incentives_controller: address, stake_contract: staked_token::MockStakedToken, underlying_token: address): transfer_strategy::StakedTokenTransferStrategy
+
public fun create_staked_token_transfer_strategy(rewards_admin: address, incentives_controller: address, stake_contract: staked_token::MockStakedToken, underlying_token: address): transfer_strategy::StakedTokenTransferStrategy
 
- + ## Function `staked_token_transfer_strategy_perform_transfer` -
public fun staked_token_transfer_strategy_perform_transfer(caller: &signer, to: address, reward: address, amount: u256, staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): bool
+
public fun staked_token_transfer_strategy_perform_transfer(caller: &signer, to: address, reward: address, amount: u256, staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): bool
 
- + ## Function `staked_token_transfer_strategy_get_stake_contract` -
public fun staked_token_transfer_strategy_get_stake_contract(staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): address
+
public fun staked_token_transfer_strategy_get_stake_contract(staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): address
 
- + ## Function `staked_token_transfer_strategy_get_underlying_token` -
public fun staked_token_transfer_strategy_get_underlying_token(staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): address
+
public fun staked_token_transfer_strategy_get_underlying_token(staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): address
 
- + ## Function `staked_token_transfer_strategy_get_incentives_controller` -
public fun staked_token_transfer_strategy_get_incentives_controller(staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): address
+
public fun staked_token_transfer_strategy_get_incentives_controller(staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): address
 
- + ## Function `staked_token_transfer_strategy_get_rewards_admin` -
public fun staked_token_transfer_strategy_get_rewards_admin(staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): address
+
public fun staked_token_transfer_strategy_get_rewards_admin(staked_token_transfer_strategy: transfer_strategy::StakedTokenTransferStrategy): address
 
- + ## Function `get_reward` -
public fun get_reward(rewards_config_input: &transfer_strategy::RewardsConfigInput): address
+
public fun get_reward(rewards_config_input: &transfer_strategy::RewardsConfigInput): address
 
- + ## Function `get_reward_oracle` -
public fun get_reward_oracle(rewards_config_input: &transfer_strategy::RewardsConfigInput): oracle::RewardOracle
+
public fun get_reward_oracle(rewards_config_input: &transfer_strategy::RewardsConfigInput): oracle::RewardOracle
 
- + ## Function `get_asset` -
public fun get_asset(rewards_config_input: &transfer_strategy::RewardsConfigInput): address
+
public fun get_asset(rewards_config_input: &transfer_strategy::RewardsConfigInput): address
 
- + ## Function `get_total_supply` -
public fun get_total_supply(rewards_config_input: &transfer_strategy::RewardsConfigInput): u256
+
public fun get_total_supply(rewards_config_input: &transfer_strategy::RewardsConfigInput): u256
 
- + ## Function `get_emission_per_second` -
public fun get_emission_per_second(rewards_config_input: &transfer_strategy::RewardsConfigInput): u128
+
public fun get_emission_per_second(rewards_config_input: &transfer_strategy::RewardsConfigInput): u128
 
- + ## Function `get_distribution_end` -
public fun get_distribution_end(rewards_config_input: &transfer_strategy::RewardsConfigInput): u32
+
public fun get_distribution_end(rewards_config_input: &transfer_strategy::RewardsConfigInput): u32
 
- + ## Function `set_total_supply` -
public fun set_total_supply(rewards_config_input: &mut transfer_strategy::RewardsConfigInput, total_supply: u256)
+
public fun set_total_supply(rewards_config_input: &mut transfer_strategy::RewardsConfigInput, total_supply: u256)
 
- + ## Function `pull_rewards_transfer_strategy_get_strategy` -
public fun pull_rewards_transfer_strategy_get_strategy(rewards_config_input: &transfer_strategy::RewardsConfigInput): transfer_strategy::PullRewardsTransferStrategy
+
public fun pull_rewards_transfer_strategy_get_strategy(rewards_config_input: &transfer_strategy::RewardsConfigInput): transfer_strategy::PullRewardsTransferStrategy
 
- + ## Function `staked_token_transfer_strategy_get_strategy` -
public fun staked_token_transfer_strategy_get_strategy(rewards_config_input: &transfer_strategy::RewardsConfigInput): transfer_strategy::StakedTokenTransferStrategy
+
public fun staked_token_transfer_strategy_get_strategy(rewards_config_input: &transfer_strategy::RewardsConfigInput): transfer_strategy::StakedTokenTransferStrategy
 
- + ## Function `validate_rewards_config_input` -
public fun validate_rewards_config_input(rewards_config_input: &transfer_strategy::RewardsConfigInput)
+
public fun validate_rewards_config_input(rewards_config_input: &transfer_strategy::RewardsConfigInput)
 
- + ## Function `has_pull_rewards_transfer_strategy` -
public fun has_pull_rewards_transfer_strategy(rewards_config_input: &transfer_strategy::RewardsConfigInput): bool
+
public fun has_pull_rewards_transfer_strategy(rewards_config_input: &transfer_strategy::RewardsConfigInput): bool
 
- + ## Function `emit_emergency_withdrawal_event` -
public fun emit_emergency_withdrawal_event(caller: &signer, token: address, to: address, amount: u256)
+
public fun emit_emergency_withdrawal_event(caller: &signer, token: address, to: address, amount: u256)
 
diff --git a/aave-core/doc/ui_incentive_data_provider_v3.md b/aave-core/doc/ui_incentive_data_provider_v3.md new file mode 100644 index 0000000..612ea5e --- /dev/null +++ b/aave-core/doc/ui_incentive_data_provider_v3.md @@ -0,0 +1,189 @@ + + + +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::ui_incentive_data_provider_v3` + + + +- [Resource `UiIncentiveDataProviderV3Data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_UiIncentiveDataProviderV3Data) +- [Struct `AggregatedReserveIncentiveData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_AggregatedReserveIncentiveData) +- [Struct `IncentiveData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_IncentiveData) +- [Struct `RewardInfo`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_RewardInfo) +- [Struct `UserReserveIncentiveData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_UserReserveIncentiveData) +- [Struct `UserIncentiveData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_UserIncentiveData) +- [Struct `UserRewardInfo`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_UserRewardInfo) +- [Constants](#@Constants_0) +- [Function `ui_incentive_data_provider_v3_data_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_ui_incentive_data_provider_v3_data_address) +- [Function `ui_incentive_data_provider_v3_data_object`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_ui_incentive_data_provider_v3_data_object) +- [Function `get_full_reserves_incentive_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_get_full_reserves_incentive_data) +- [Function `get_reserves_incentives_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_get_reserves_incentives_data) +- [Function `get_user_reserves_incentives_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_incentive_data_provider_v3_get_user_reserves_incentives_data) + + +
use 0x1::object;
+use 0x1::string;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::eac_aggregator_proxy;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::rewards_controller;
+
+ + + + + +## Resource `UiIncentiveDataProviderV3Data` + + + +
struct UiIncentiveDataProviderV3Data has key
+
+ + + + + +## Struct `AggregatedReserveIncentiveData` + + + +
struct AggregatedReserveIncentiveData has drop, store
+
+ + + + + +## Struct `IncentiveData` + + + +
struct IncentiveData has drop, store
+
+ + + + + +## Struct `RewardInfo` + + + +
struct RewardInfo has drop, store
+
+ + + + + +## Struct `UserReserveIncentiveData` + + + +
struct UserReserveIncentiveData has drop, store
+
+ + + + + +## Struct `UserIncentiveData` + + + +
struct UserIncentiveData has drop, store
+
+ + + + + +## Struct `UserRewardInfo` + + + +
struct UserRewardInfo has drop, store
+
+ + + + + +## Constants + + + + + + +
const EMPTY_ADDRESS: address = 0x0;
+
+ + + + + + + +
const UI_INCENTIVE_DATA_PROVIDER_V3_NAME: vector<u8> = [65, 65, 86, 69, 95, 85, 73, 95, 73, 78, 67, 69, 78, 84, 73, 86, 69, 95, 68, 65, 84, 65, 95, 80, 82, 79, 86, 73, 68, 69, 82, 95, 86, 51];
+
+ + + + + +## Function `ui_incentive_data_provider_v3_data_address` + + + +
#[view]
+public fun ui_incentive_data_provider_v3_data_address(): address
+
+ + + + + +## Function `ui_incentive_data_provider_v3_data_object` + + + +
#[view]
+public fun ui_incentive_data_provider_v3_data_object(): object::Object<ui_incentive_data_provider_v3::UiIncentiveDataProviderV3Data>
+
+ + + + + +## Function `get_full_reserves_incentive_data` + + + +
#[view]
+public fun get_full_reserves_incentive_data(user: address): (vector<ui_incentive_data_provider_v3::AggregatedReserveIncentiveData>, vector<ui_incentive_data_provider_v3::UserReserveIncentiveData>)
+
+ + + + + +## Function `get_reserves_incentives_data` + + + +
#[view]
+public fun get_reserves_incentives_data(): vector<ui_incentive_data_provider_v3::AggregatedReserveIncentiveData>
+
+ + + + + +## Function `get_user_reserves_incentives_data` + + + +
#[view]
+public fun get_user_reserves_incentives_data(user: address): vector<ui_incentive_data_provider_v3::UserReserveIncentiveData>
+
diff --git a/aave-core/doc/ui_pool_data_provider_v3.md b/aave-core/doc/ui_pool_data_provider_v3.md index 2215818..4f327da 100644 --- a/aave-core/doc/ui_pool_data_provider_v3.md +++ b/aave-core/doc/ui_pool_data_provider_v3.md @@ -1,80 +1,80 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::ui_pool_data_provider_v3` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::ui_pool_data_provider_v3` -- [Resource `UiPoolDataProviderV3Data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ui_pool_data_provider_v3_UiPoolDataProviderV3Data) -- [Resource `AggregatedReserveData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ui_pool_data_provider_v3_AggregatedReserveData) -- [Resource `UserReserveData`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ui_pool_data_provider_v3_UserReserveData) -- [Resource `BaseCurrencyInfo`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ui_pool_data_provider_v3_BaseCurrencyInfo) +- [Resource `UiPoolDataProviderV3Data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_pool_data_provider_v3_UiPoolDataProviderV3Data) +- [Resource `AggregatedReserveData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_pool_data_provider_v3_AggregatedReserveData) +- [Resource `UserReserveData`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_pool_data_provider_v3_UserReserveData) +- [Resource `BaseCurrencyInfo`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_pool_data_provider_v3_BaseCurrencyInfo) - [Constants](#@Constants_0) -- [Function `ui_pool_data_provider_v32_data_address`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ui_pool_data_provider_v3_ui_pool_data_provider_v32_data_address) -- [Function `ui_pool_data_provider_v3_data_object`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ui_pool_data_provider_v3_ui_pool_data_provider_v3_data_object) -- [Function `get_reserves_list`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ui_pool_data_provider_v3_get_reserves_list) -- [Function `get_reserves_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ui_pool_data_provider_v3_get_reserves_data) -- [Function `get_user_reserves_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_ui_pool_data_provider_v3_get_user_reserves_data) +- [Function `ui_pool_data_provider_v3_data_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_pool_data_provider_v3_ui_pool_data_provider_v3_data_address) +- [Function `ui_pool_data_provider_v3_data_object`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_pool_data_provider_v3_ui_pool_data_provider_v3_data_object) +- [Function `get_reserves_list`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_pool_data_provider_v3_get_reserves_list) +- [Function `get_reserves_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_pool_data_provider_v3_get_reserves_data) +- [Function `get_user_reserves_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_ui_pool_data_provider_v3_get_user_reserves_data)
use 0x1::object;
 use 0x1::option;
 use 0x1::string;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::default_reserve_interest_rate_strategy;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::eac_aggregator_proxy;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::emode_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool_addresses_provider;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::token_base;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::variable_token_factory;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::default_reserve_interest_rate_strategy;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::eac_aggregator_proxy;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::emode_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::mock_underlying_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::token_base;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::variable_debt_token_factory;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Resource `UiPoolDataProviderV3Data` -
struct UiPoolDataProviderV3Data has key
+
struct UiPoolDataProviderV3Data has key
 
- + ## Resource `AggregatedReserveData` -
struct AggregatedReserveData has drop, store, key
+
struct AggregatedReserveData has drop, store, key
 
- + ## Resource `UserReserveData` -
struct UserReserveData has drop, store, key
+
struct UserReserveData has drop, store, key
 
- + ## Resource `BaseCurrencyInfo` -
struct BaseCurrencyInfo has drop, store, key
+
struct BaseCurrencyInfo has drop, store, key
 
@@ -84,195 +84,195 @@ ## Constants - + -
const EROLE_NOT_EXISTS: u64 = 1;
+
const EROLE_NOT_EXISTS: u64 = 1;
 
- + -
const NOT_FUNDS_ADMIN: u64 = 1;
+
const NOT_FUNDS_ADMIN: u64 = 3;
 
- + -
const EAMOUNT_EXCEEDS_THE_AVAILABLE_BALANCE: u64 = 1;
+
const EAMOUNT_EXCEEDS_THE_AVAILABLE_BALANCE: u64 = 12;
 
- + -
const EAMOUNT_IS_ZERO: u64 = 1;
+
const EAMOUNT_IS_ZERO: u64 = 11;
 
- + -
const EDEPOSIT_IS_ZERO: u64 = 1;
+
const EDEPOSIT_IS_ZERO: u64 = 6;
 
- + -
const EDEPOSIT_NOT_MULTIPLE_OF_TIME_DELTA: u64 = 1;
+
const EDEPOSIT_NOT_MULTIPLE_OF_TIME_DELTA: u64 = 10;
 
- + -
const EDEPOSIT_SMALLER_THAN_TIME_DELTA: u64 = 1;
+
const EDEPOSIT_SMALLER_THAN_TIME_DELTA: u64 = 9;
 
- + -
const ESTART_TIME_BEFORE_BLOCK_TIMESTAMP: u64 = 1;
+
const ESTART_TIME_BEFORE_BLOCK_TIMESTAMP: u64 = 7;
 
- + -
const ESTOP_TIME_BEFORE_THE_START_TIME: u64 = 1;
+
const ESTOP_TIME_BEFORE_THE_START_TIME: u64 = 8;
 
- + -
const ESTREAM_NOT_EXISTS: u64 = 1;
+
const ESTREAM_NOT_EXISTS: u64 = 2;
 
- + -
const ESTREAM_TO_THE_CALLER: u64 = 1;
+
const ESTREAM_TO_THE_CALLER: u64 = 5;
 
- + -
const ESTREAM_TO_THE_CONTRACT_ITSELF: u64 = 1;
+
const ESTREAM_TO_THE_CONTRACT_ITSELF: u64 = 4;
 
- + -
const EMPTY_ADDRESS: address = 0x0;
+
const EMPTY_ADDRESS: address = 0x0;
 
- + -
const ETH_CURRENCY_UNIT: u256 = 1;
+
const ETH_CURRENCY_UNIT: u256 = 1;
 
- + -
const UI_POOL_DATA_PROVIDER_V3_NAME: vector<u8> = [65, 65, 86, 69, 95, 85, 73, 95, 80, 79, 79, 76, 95, 68, 65, 84, 65, 95, 80, 82, 79, 86, 73, 68, 69, 82, 95, 86, 51];
+
const UI_POOL_DATA_PROVIDER_V3_NAME: vector<u8> = [65, 65, 86, 69, 95, 85, 73, 95, 80, 79, 79, 76, 95, 68, 65, 84, 65, 95, 80, 82, 79, 86, 73, 68, 69, 82, 95, 86, 51];
 
- + -## Function `ui_pool_data_provider_v32_data_address` +## Function `ui_pool_data_provider_v3_data_address`
#[view]
-public fun ui_pool_data_provider_v32_data_address(): address
+public fun ui_pool_data_provider_v3_data_address(): address
 
- + ## Function `ui_pool_data_provider_v3_data_object`
#[view]
-public fun ui_pool_data_provider_v3_data_object(): object::Object<ui_pool_data_provider_v3::UiPoolDataProviderV3Data>
+public fun ui_pool_data_provider_v3_data_object(): object::Object<ui_pool_data_provider_v3::UiPoolDataProviderV3Data>
 
- + ## Function `get_reserves_list`
#[view]
-public fun get_reserves_list(): vector<address>
+public fun get_reserves_list(): vector<address>
 
- + ## Function `get_reserves_data`
#[view]
-public fun get_reserves_data(): (vector<ui_pool_data_provider_v3::AggregatedReserveData>, ui_pool_data_provider_v3::BaseCurrencyInfo)
+public fun get_reserves_data(): (vector<ui_pool_data_provider_v3::AggregatedReserveData>, ui_pool_data_provider_v3::BaseCurrencyInfo)
 
- + ## Function `get_user_reserves_data`
#[view]
-public fun get_user_reserves_data(user: address): (vector<ui_pool_data_provider_v3::UserReserveData>, u8)
+public fun get_user_reserves_data(user: address): (vector<ui_pool_data_provider_v3::UserReserveData>, u8)
 
diff --git a/aave-core/doc/user_logic.md b/aave-core/doc/user_logic.md index 87721db..28125f6 100644 --- a/aave-core/doc/user_logic.md +++ b/aave-core/doc/user_logic.md @@ -1,27 +1,35 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::user_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::user_logic` -- [Function `get_user_account_data`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_user_logic_get_user_account_data) +- [Function `get_user_account_data`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_user_logic_get_user_account_data) -
use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::emode_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::generic_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
+
use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::emode_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::generic_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Function `get_user_account_data` +@notice Returns the user account data across all the reserves +@param user The address of the user +@return total_collateral_base The total collateral of the user in the base currency used by the price feed +@return total_debt_base The total debt of the user in the base currency used by the price feed +@return available_borrows_base The borrowing power left of the user in the base currency used by the price feed +@return current_liquidation_threshold The liquidation threshold of the user +@return ltv The loan to value of The user +@return health_factor The current health factor of the user
#[view]
-public fun get_user_account_data(user: address): (u256, u256, u256, u256, u256, u256)
+public fun get_user_account_data(user: address): (u256, u256, u256, u256, u256, u256)
 
diff --git a/aave-core/doc/validation_logic.md b/aave-core/doc/validation_logic.md index 3f90333..d3de629 100644 --- a/aave-core/doc/validation_logic.md +++ b/aave-core/doc/validation_logic.md @@ -1,119 +1,152 @@ - + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool_validation` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool_validation` -- [Function `validate_hf_and_ltv`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_validation_validate_hf_and_ltv) -- [Function `validate_automatic_use_as_collateral`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_validation_validate_automatic_use_as_collateral) -- [Function `validate_use_as_collateral`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_validation_validate_use_as_collateral) -- [Function `validate_health_factor`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_validation_validate_health_factor) -- [Function `validate_set_user_emode`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_pool_validation_validate_set_user_emode) +- [Function `validate_hf_and_ltv`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_validation_validate_hf_and_ltv) +- [Function `validate_automatic_use_as_collateral`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_validation_validate_automatic_use_as_collateral) +- [Function `validate_use_as_collateral`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_validation_validate_use_as_collateral) +- [Function `validate_health_factor`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_validation_validate_health_factor) +- [Function `validate_set_user_emode`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_pool_validation_validate_set_user_emode)
use 0x1::string;
-use 0x1c0b45bb18cf14bcb0b4caaa8e875dfb5eff6d9d8f5b181de3d3e0107f099753::acl_manage;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::generic_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::generic_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Function `validate_hf_and_ltv` +@notice Validates the health factor of a user and the ltv of the asset being withdrawn. +@param reserves_data The reserve data of reserve +@param reserves_count The number of available reserves +@param user_config_map the user configuration map +@param from The user from which the aTokens are being transferred +@param user_emode_category The users active efficiency mode category +@param emode_ltv The ltv of the efficiency mode category +@param emode_liq_threshold The liquidation threshold of the efficiency mode category +@param emode_asset_price The price of the efficiency mode category -
public fun validate_hf_and_ltv(reserve_data: &mut pool::ReserveData, reserves_count: u256, user_config_map: &user::UserConfigurationMap, from: address, user_emode_category: u8, emode_ltv: u256, emode_liq_threshold: u256, emode_asset_price: u256)
+
public fun validate_hf_and_ltv(reserve_data: &mut pool::ReserveData, reserves_count: u256, user_config_map: &user::UserConfigurationMap, from: address, user_emode_category: u8, emode_ltv: u256, emode_liq_threshold: u256, emode_asset_price: u256)
 
- + ## Function `validate_automatic_use_as_collateral` +@notice Validates if an asset should be automatically activated as collateral in the following actions: supply, +transfer, mint unbacked, and liquidate +@dev This is used to ensure that isolated assets are not enabled as collateral automatically +@param user_config_map the user configuration map +@param reserve_config_map The reserve configuration map +@return True if the asset can be activated as collateral, false otherwise -
public fun validate_automatic_use_as_collateral(account: address, user_config_map: &user::UserConfigurationMap, reserve_config_map: &reserve::ReserveConfigurationMap): bool
+
public fun validate_automatic_use_as_collateral(account: address, user_config_map: &user::UserConfigurationMap, reserve_config_map: &reserve::ReserveConfigurationMap): bool
 
- + ## Function `validate_use_as_collateral` +@notice Validates the action of activating the asset as collateral. +@dev Only possible if the asset has non-zero LTV and the user is not in isolation mode +@param user_config_map the user configuration map +@param reserve_config_map The reserve configuration map +@return True if the asset can be activated as collateral, false otherwise -
public fun validate_use_as_collateral(user_config_map: &user::UserConfigurationMap, reserve_config_map: &reserve::ReserveConfigurationMap): bool
+
public fun validate_use_as_collateral(user_config_map: &user::UserConfigurationMap, reserve_config_map: &reserve::ReserveConfigurationMap): bool
 
- + ## Function `validate_health_factor` +notice Validates the health factor of a user. +@param reserves_count The number of available reserves +@param user_config_map the user configuration map +@param user The user to validate health factor of +@param user_emode_category The users active efficiency mode category +@param emode_ltv The ltv of the efficiency mode category +@param emode_liq_threshold The liquidation threshold of the efficiency mode category +@param emode_asset_price The price of the efficiency mode category -
public fun validate_health_factor(reserves_count: u256, user_config_map: &user::UserConfigurationMap, user: address, user_emode_category: u8, emode_ltv: u256, emode_liq_threshold: u256, emode_asset_price: u256): (u256, bool)
+
public fun validate_health_factor(reserves_count: u256, user_config_map: &user::UserConfigurationMap, user: address, user_emode_category: u8, emode_ltv: u256, emode_liq_threshold: u256, emode_asset_price: u256): (u256, bool)
 
- + ## Function `validate_set_user_emode` +@notice Validates the action of setting efficiency mode. +@param user_config_map the user configuration map +@param reserves_count The total number of valid reserves +@param category_id The id of the category +@param liquidation_threshold The liquidation threshold -
public fun validate_set_user_emode(user_config_map: &user::UserConfigurationMap, reserves_count: u256, category_id: u8, liquidation_threshold: u16)
+
public fun validate_set_user_emode(user_config_map: &user::UserConfigurationMap, reserves_count: u256, category_id: u8, liquidation_threshold: u16)
 
- + -# Module `0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::validation_logic` +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::validation_logic` -- [Struct `ValidateBorrowLocalVars`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_ValidateBorrowLocalVars) -- [Function `validate_flashloan_complex`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_validate_flashloan_complex) -- [Function `validate_flashloan_simple`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_validate_flashloan_simple) -- [Function `validate_supply`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_validate_supply) -- [Function `validate_withdraw`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_validate_withdraw) -- [Function `validate_transfer`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_validate_transfer) -- [Function `validate_set_use_reserve_as_collateral`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_validate_set_use_reserve_as_collateral) -- [Function `validate_borrow`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_validate_borrow) -- [Function `validate_repay`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_validate_repay) -- [Function `validate_liquidation_call`](#0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529_validation_logic_validate_liquidation_call) +- [Struct `ValidateBorrowLocalVars`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_ValidateBorrowLocalVars) +- [Function `validate_flashloan_complex`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_validate_flashloan_complex) +- [Function `validate_flashloan_simple`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_validate_flashloan_simple) +- [Function `validate_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_validate_supply) +- [Function `validate_withdraw`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_validate_withdraw) +- [Function `validate_transfer`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_validate_transfer) +- [Function `validate_set_use_reserve_as_collateral`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_validate_set_use_reserve_as_collateral) +- [Function `validate_borrow`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_validate_borrow) +- [Function `validate_repay`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_validate_repay) +- [Function `validate_liquidation_call`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_validation_logic_validate_liquidation_call)
use 0x1::signer;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::error;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::reserve;
-use 0x2b375fc8da759f1f7c198ffa5a0bf4466a5eb25564272115a1fa2c30b22657a2::user;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::a_token_factory;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::emode_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::generic_logic;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::pool;
-use 0x671a571aefb734eac5263967388f8611f2b11f603b0f9c90bc77851d18928529::variable_token_factory;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::math_utils;
-use 0x6b73dc9e557f4e984e7777685602c2e15559a5f4ec06293a5855206490ac9b77::wad_ray_math;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle;
-use 0x70fe84cb8ecce35131a3c36c2592864bf9da740ffd6d2ceb8bd8f773978fa2ae::oracle_sentinel;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::math_utils;
+use 0x9efefdec8fe22b7447931b81745048182594ef72653dfbf8e05b815ecc355f7c::wad_ray_math;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::a_token_factory;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::emode_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::generic_logic;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::pool;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::variable_debt_token_factory;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle;
+use 0xe02c89369099ad99993cbe3d4c3c80b299df006885854178a8acdb6ab6afb6e::oracle_sentinel;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::reserve;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::user;
 
- + ## Struct `ValidateBorrowLocalVars` @@ -124,104 +157,147 @@ -
struct ValidateBorrowLocalVars has drop
+
struct ValidateBorrowLocalVars has drop
 
- + ## Function `validate_flashloan_complex` +@notice Validates a flashloan action. +@param reserves_data The data of all the reserves +@param assets The assets being flash-borrowed +@param amounts The amounts for each asset being borrowed -
public fun validate_flashloan_complex(reserve_data: &vector<pool::ReserveData>, assets: &vector<address>, amounts: &vector<u256>)
+
public fun validate_flashloan_complex(reserves_data: &vector<pool::ReserveData>, assets: &vector<address>, amounts: &vector<u256>)
 
- + ## Function `validate_flashloan_simple` +@notice Validates a flashloan action. +@param reserve_data The reserve data the reserve -
public fun validate_flashloan_simple(reserve_data: &pool::ReserveData)
+
public fun validate_flashloan_simple(reserve_data: &pool::ReserveData)
 
- + ## Function `validate_supply` +@notice Validates a supply action. +@param reserve_data The reserve data the reserve +@param amount The amount to be supplied -
public fun validate_supply(reserve_data: &pool::ReserveData, amount: u256)
+
public fun validate_supply(reserve_data: &pool::ReserveData, amount: u256)
 
- + ## Function `validate_withdraw` +@notice Validates a withdraw action. +@param reserve_data The reserve data the reserve +@param amount The amount to be withdrawn +@param user_balance The balance of the user -
public fun validate_withdraw(reserve_data: &pool::ReserveData, amount: u256, user_balance: u256)
+
public fun validate_withdraw(reserve_data: &pool::ReserveData, amount: u256, user_balance: u256)
 
- + ## Function `validate_transfer` +@notice Validates a transfer action. +@param reserve_data The reserve data the reserve -
public fun validate_transfer(reserve_data: &pool::ReserveData)
+
public fun validate_transfer(reserve_data: &pool::ReserveData)
 
- + ## Function `validate_set_use_reserve_as_collateral` +@notice Validates the action of setting an asset as collateral. +@param reserve_data The reserve data the reserve +@param user_balance The balance of the user -
public fun validate_set_use_reserve_as_collateral(reserve_data: &pool::ReserveData, user_balance: u256)
+
public fun validate_set_use_reserve_as_collateral(reserve_data: &pool::ReserveData, user_balance: u256)
 
- + ## Function `validate_borrow` - - -
public fun validate_borrow(reserve_data: &pool::ReserveData, user_config_map: &user::UserConfigurationMap, asset: address, user_address: address, amount: u256, interest_rate_mode: u8, reserves_count: u256, user_emode_category: u8, isolation_mode_active: bool, isolation_mode_collateral_address: address, isolation_mode_debt_ceiling: u256)
+@notice Validates a borrow action.
+@param reserve_data The reserve data the reserve
+@param user_config_map The UserConfigurationMap object
+@param asset The address of the asset to be borrowed
+@param user_address The address of the user
+@param amount The amount to be borrowed
+@param interest_rate_mode The interest rate mode
+@param reserves_count The number of reserves
+@param user_emode_category The user's eMode category
+@param isolation_mode_active The isolation mode state
+@param isolation_mode_collateral_address The address of the collateral reserve in isolation mode
+@param isolation_mode_debt_ceiling The debt ceiling in isolation mode
+
+
+
public fun validate_borrow(reserve_data: &pool::ReserveData, user_config_map: &user::UserConfigurationMap, asset: address, user_address: address, amount: u256, interest_rate_mode: u8, reserves_count: u256, user_emode_category: u8, isolation_mode_active: bool, isolation_mode_collateral_address: address, isolation_mode_debt_ceiling: u256)
 
- + ## Function `validate_repay` +@notice Validates a repay action. +@param account The address of the user +@param reserve_data The reserve data the reserve +@param amount_sent The amount sent for the repayment. Can be an actual value or uint(-1) +@param interest_rate_mode The interest rate mode of the debt being repaid +@param on_behalf_of The address of the user msg.sender is repaying for +@param variable_debt The borrow balance of the user -
public fun validate_repay(account: &signer, reserve_data: &pool::ReserveData, amount_sent: u256, interest_rate_mode: u8, on_behalf_of: address, variable_debt: u256)
+
public fun validate_repay(account: &signer, reserve_data: &pool::ReserveData, amount_sent: u256, interest_rate_mode: u8, on_behalf_of: address, variable_debt: u256)
 
- + ## Function `validate_liquidation_call` +@notice Validates the liquidation action. +@param user_config_map The user configuration mapping +@param collateral_reserve The reserve data of the collateral +@param debt_reserve The reserve data of the debt +@param total_debt The total debt of the user +@param health_factor The health factor of the user -
public fun validate_liquidation_call(user_config_map: &user::UserConfigurationMap, collateral_reserve: &pool::ReserveData, debt_reserve: &pool::ReserveData, total_debt: u256, health_factor: u256)
+
public fun validate_liquidation_call(user_config_map: &user::UserConfigurationMap, collateral_reserve: &pool::ReserveData, debt_reserve: &pool::ReserveData, total_debt: u256, health_factor: u256)
 
diff --git a/aave-core/doc/variable_debt_token_factory.md b/aave-core/doc/variable_debt_token_factory.md new file mode 100644 index 0000000..f3bbdec --- /dev/null +++ b/aave-core/doc/variable_debt_token_factory.md @@ -0,0 +1,285 @@ + + + +# Module `0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::variable_debt_token_factory` + + + +- [Struct `Initialized`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_Initialized) +- [Constants](#@Constants_0) +- [Function `create_token`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_create_token) +- [Function `mint`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_mint) +- [Function `burn`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_burn) +- [Function `get_revision`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_get_revision) +- [Function `get_underlying_asset_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_get_underlying_asset_address) +- [Function `get_metadata_by_symbol`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_get_metadata_by_symbol) +- [Function `token_address`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_token_address) +- [Function `asset_metadata`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_asset_metadata) +- [Function `get_previous_index`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_get_previous_index) +- [Function `scaled_balance_of`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_scaled_balance_of) +- [Function `scaled_total_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_scaled_total_supply) +- [Function `get_scaled_user_balance_and_supply`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_get_scaled_user_balance_and_supply) +- [Function `name`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_name) +- [Function `symbol`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_symbol) +- [Function `decimals`](#0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370_variable_debt_token_factory_decimals) + + +
use 0x1::event;
+use 0x1::fungible_asset;
+use 0x1::object;
+use 0x1::signer;
+use 0x1::string;
+use 0xaaeecbeff5c135e527602a0fd44e242efbed5ebec8f911e1e3f4933f62ed2370::token_base;
+use 0xd329b8b371bf56fdbfbb66f441a8463f3605ecb27ee0c484f85a4cf88883d2f9::acl_manage;
+use 0xe984b3b024d14e7aac51fb0aec8d0fbfbc23a230fe3bd8a87f575d243bc0cedd::error;
+
+ + + + + +## Struct `Initialized` + + + +
#[event]
+struct Initialized has drop, store
+
+ + + + + +## Constants + + + + + + +
const DEBT_TOKEN_REVISION: u256 = 1;
+
+ + + + + + + +
const E_NOT_V_TOKEN_ADMIN: u64 = 1;
+
+ + + + + +## Function `create_token` + + + +
public(friend) fun create_token(signer: &signer, name: string::String, symbol: string::String, decimals: u8, icon_uri: string::String, project_uri: string::String, underlying_asset: address)
+
+ + + + + +## Function `mint` + +@notice Mints debt token to the on_behalf_of address +@param caller The address receiving the borrowed underlying, being the delegatee in case +of credit delegate, or same as on_behalf_of otherwise +@param on_behalf_of The address receiving the debt tokens +@param amount The amount of debt being minted +@param index The variable debt index of the reserve +@param metadata_address The address of the metadata object + + +
public(friend) fun mint(caller: address, on_behalf_of: address, amount: u256, index: u256, metadata_address: address)
+
+ + + + + +## Function `burn` + +@notice Burns user variable debt +@dev In some instances, a burn transaction will emit a mint event +if the amount to burn is less than the interest that the user accrued +@param from The address from which the debt will be burned +@param amount The amount getting burned +@param index The variable debt index of the reserve +@param metadata_address The address of the metadata object + + +
public(friend) fun burn(from: address, amount: u256, index: u256, metadata_address: address)
+
+ + + + + +## Function `get_revision` + + + +
#[view]
+public fun get_revision(): u256
+
+ + + + + +## Function `get_underlying_asset_address` + +@notice Returns the address of the underlying asset of this debtToken (E.g. WETH for variableDebtWETH) +@param metadata_address The address of the metadata object +@return The address of the underlying asset + + +
#[view]
+public fun get_underlying_asset_address(metadata_address: address): address
+
+ + + + + +## Function `get_metadata_by_symbol` + + + +
#[view]
+public fun get_metadata_by_symbol(owner: address, symbol: string::String): object::Object<fungible_asset::Metadata>
+
+ + + + + +## Function `token_address` + + + +
#[view]
+public fun token_address(owner: address, symbol: string::String): address
+
+ + + + + +## Function `asset_metadata` + + + +
#[view]
+public fun asset_metadata(owner: address, symbol: string::String): object::Object<fungible_asset::Metadata>
+
+ + + + + +## Function `get_previous_index` + +@notice Returns last index interest was accrued to the user's balance +@param user The address of the user +@param metadata_address The address of the variable debt token +@return The last index interest was accrued to the user's balance, expressed in ray + + +
#[view]
+public fun get_previous_index(user: address, metadata_address: address): u256
+
+ + + + + +## Function `scaled_balance_of` + +@notice Returns the scaled balance of the user. +@dev The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index +at the moment of the update +@param owner The user whose balance is calculated +@param metadata_address The address of the variable debt token +@return The scaled balance of the user + + +
#[view]
+public fun scaled_balance_of(owner: address, metadata_address: address): u256
+
+ + + + + +## Function `scaled_total_supply` + +@notice Returns the scaled total supply of the scaled balance token. Represents sum(debt/index) +@param metadata_address The address of the variable debt token +@return The scaled total supply + + +
#[view]
+public fun scaled_total_supply(metadata_address: address): u256
+
+ + + + + +## Function `get_scaled_user_balance_and_supply` + +@notice Returns the scaled balance of the user and the scaled total supply. +@param owner The address of the user +@param metadata_address The address of the variable debt token +@return The scaled balance of the user +@return The scaled total supply + + +
#[view]
+public fun get_scaled_user_balance_and_supply(owner: address, metadata_address: address): (u256, u256)
+
+ + + + + +## Function `name` + +Get the name of the fungible asset from the metadata object. + + +
#[view]
+public fun name(metadata_address: address): string::String
+
+ + + + + +## Function `symbol` + +Get the symbol of the fungible asset from the metadata object. + + +
#[view]
+public fun symbol(metadata_address: address): string::String
+
+ + + + + +## Function `decimals` + +Get the decimals from the metadata object. + + +
#[view]
+public fun decimals(metadata_address: address): u8
+
diff --git a/aave-core/sources/aave-bridge/bridge_logic.move b/aave-core/sources/aave-bridge/bridge_logic.move index 6e0da28..749ae79 100644 --- a/aave-core/sources/aave-bridge/bridge_logic.move +++ b/aave-core/sources/aave-bridge/bridge_logic.move @@ -10,18 +10,27 @@ module aave_pool::bridge_logic { use aave_math::wad_ray_math; use aave_pool::a_token_factory; + use aave_pool::mock_underlying_token_factory; use aave_pool::pool::Self; use aave_pool::pool_validation; - use aave_pool::underlying_token_factory; use aave_pool::validation_logic; #[event] + /// @dev Emitted on setUserUseReserveAsCollateral() + /// @param reserve The address of the underlying asset of the reserve + /// @param user The address of the user enabling the usage as collateral struct ReserveUsedAsCollateralEnabled has store, drop { reserve: address, user: address } #[event] + /// @dev Emitted on mint_unbacked() + /// @param reserve The address of the underlying asset of the reserve + /// @param user The address initiating the supply + /// @param on_behalf_of The beneficiary of the supplied assets, receiving the aTokens + /// @param amount The amount of supplied assets + /// @param referral_code The referral code used struct MintUnbacked has store, drop { reserve: address, user: address, @@ -31,6 +40,11 @@ module aave_pool::bridge_logic { } #[event] + /// @dev Emitted on back_unbacked() + /// @param reserve The address of the underlying asset of the reserve + /// @param backer The address paying for the backing + /// @param amount The amount added as backing + /// @param fee The amount paid in fees struct BackUnbacked has store, drop { reserve: address, backer: address, @@ -38,6 +52,15 @@ module aave_pool::bridge_logic { fee: u256 } + /// @notice Mint unbacked aTokens to a user and updates the unbacked for the reserve. + /// @dev Essentially a supply without transferring the underlying. + /// @dev Emits the `MintUnbacked` event + /// @dev Emits the `ReserveUsedAsCollateralEnabled` if asset is set as collateral + /// @param asset The address of the underlying asset to mint aTokens of + /// @param amount The amount to mint + /// @param on_behalf_of The address that will receive the aTokens + /// @param referral_code Code used to register the integrator originating the operation, for potential rewards. + /// 0 if the action is executed directly by the user, without any middle-man public entry fun mint_unbacked( account: &signer, asset: address, @@ -54,56 +77,72 @@ module aave_pool::bridge_logic { validation_logic::validate_supply(&reserve_data, amount); // validate unbacked mint cap - let reserve_config_map = pool::get_reserve_configuration_by_reserve_data(&reserve_data); + let reserve_config_map = + pool::get_reserve_configuration_by_reserve_data(&reserve_data); let unbacked_mint_cap = reserve_config::get_unbacked_mint_cap(&reserve_config_map); let reserve_decimals = reserve_config::get_decimals(&reserve_config_map); let unbacked = (pool::get_reserve_unbacked(&reserve_data) as u256) + amount; // update pool unbacked - pool::set_reserve_unbacked(asset, (unbacked as u128)); + pool::set_reserve_unbacked(asset, &mut reserve_data, (unbacked as u128)); - assert!(unbacked <= unbacked_mint_cap * (math_utils::pow(10, reserve_decimals)), - error_config::get_eunbacked_mint_cap_exceeded()); + assert!( + unbacked <= unbacked_mint_cap * (math_utils::pow(10, reserve_decimals)), + error_config::get_eunbacked_mint_cap_exceeded(), + ); let token_a_address = pool::get_reserve_a_token_address(&reserve_data); // update pool interest rates pool::update_interest_rates(&mut reserve_data, asset, 0, 0); let is_first_supply: bool = - a_token_factory::scale_balance_of(on_behalf_of, token_a_address) == 0; + a_token_factory::scaled_balance_of(on_behalf_of, token_a_address) == 0; - a_token_factory::mint(account_address, + a_token_factory::mint( + account_address, on_behalf_of, amount, (pool::get_reserve_liquidity_index(&reserve_data) as u256), - token_a_address); + token_a_address, + ); if (is_first_supply) { let user_config_map = pool::get_user_configuration(on_behalf_of); let reserve_id = pool::get_reserve_id(&reserve_data); - if (pool_validation::validate_automatic_use_as_collateral(account_address, &user_config_map, &reserve_config_map)) { - user_config::set_using_as_collateral(&mut user_config_map, (reserve_id as u256), true); + if (pool_validation::validate_automatic_use_as_collateral( + account_address, &user_config_map, &reserve_config_map + )) { + user_config::set_using_as_collateral( + &mut user_config_map, (reserve_id as u256), true + ); pool::set_user_configuration(on_behalf_of, user_config_map); - event::emit(ReserveUsedAsCollateralEnabled { - reserve: asset, - user: on_behalf_of - }); + event::emit( + ReserveUsedAsCollateralEnabled { reserve: asset, user: on_behalf_of } + ); } }; - event::emit(MintUnbacked { + event::emit( + MintUnbacked { reserve: asset, user: account_address, on_behalf_of, amount, referral_code - }); + }, + ); } + /// @notice Back the current unbacked with `amount` and pay `fee`. + /// @dev It is not possible to back more than the existing unbacked amount of the reserve + /// @dev Emits the `BackUnbacked` event + /// @param asset The address of the underlying asset to repay + /// @param amount The amount to back + /// @param fee The amount paid in fees + /// @return The backed amount public entry fun back_unbacked( account: &signer, asset: address, amount: u256, fee: u256, - protocol_fee_bps: u256 ) { let account_address = signer::address_of(account); assert!(only_brigde(account_address), error_config::get_ecaller_not_bridge()); @@ -113,43 +152,60 @@ module aave_pool::bridge_logic { let unbacked = (pool::get_reserve_unbacked(&reserve_data) as u256); let backing_amount = if (amount < unbacked) { amount } - else { unbacked }; + else { + unbacked + }; + let protocol_fee_bps = pool::get_bridge_protocol_fee(); let fee_to_protocol = math_utils::percent_mul(fee, protocol_fee_bps); let fee_to_lp = fee - fee_to_protocol; let added = backing_amount + fee; let token_a_address = pool::get_reserve_a_token_address(&reserve_data); let accrued_to_treasury = pool::get_reserve_accrued_to_treasury(&reserve_data); - let token_a_supply_and_treasury = pool::scale_a_token_total_supply(token_a_address) + wad_ray_math::ray_mul( - accrued_to_treasury, (pool::get_reserve_liquidity_index(&reserve_data) as u256)); + let token_a_supply_and_treasury = + pool::scaled_a_token_total_supply(token_a_address) + + wad_ray_math::ray_mul( + accrued_to_treasury, + (pool::get_reserve_liquidity_index(&reserve_data) as u256), + ); let next_liquidity_index = - pool::cumulate_to_liquidity_index(asset, &mut reserve_data, - token_a_supply_and_treasury, fee_to_lp); + pool::cumulate_to_liquidity_index( + asset, + &mut reserve_data, + token_a_supply_and_treasury, + fee_to_lp, + ); let accrued_to_treasury_amount = - accrued_to_treasury + wad_ray_math::ray_div(fee_to_protocol, - next_liquidity_index); + accrued_to_treasury + + wad_ray_math::ray_div(fee_to_protocol, next_liquidity_index); // update pool accrue to treasury pool::set_reserve_accrued_to_treasury(asset, accrued_to_treasury_amount); // update pool unbacked - pool::set_reserve_unbacked(asset, ((unbacked - backing_amount) as u128)); + pool::set_reserve_unbacked( + asset, &mut reserve_data, ((unbacked - backing_amount) as u128) + ); // update pool interest rates pool::update_interest_rates(&mut reserve_data, asset, added, 0); - underlying_token_factory::transfer_from(account_address, + mock_underlying_token_factory::transfer_from( + account_address, a_token_factory::get_token_account_address(token_a_address), (added as u64), - asset); + asset, + ); - event::emit(BackUnbacked { + event::emit( + BackUnbacked { reserve: asset, backer: account_address, amount: backing_amount, fee, - }) + }, + ) } fun only_brigde(brigde: address): bool { diff --git a/aave-core/sources/aave-flash-loan/flash_loan.move b/aave-core/sources/aave-flash-loan/flash_loan.move index 0805d0c..fe314e4 100644 --- a/aave-core/sources/aave-flash-loan/flash_loan.move +++ b/aave-core/sources/aave-flash-loan/flash_loan.move @@ -1,3 +1,6 @@ +/// @title flashloan_logic module +/// @author Aave +/// @notice Implements the logic for the flash loans module aave_pool::flashloan_logic { use std::option::Option; use std::option::Self; @@ -7,19 +10,28 @@ module aave_pool::flashloan_logic { use aave_acl::acl_manage; use aave_config::error as error_config; + use aave_config::error::{Self}; use aave_config::user as user_config; use aave_math::math_utils; use aave_math::wad_ray_math; use aave_pool::a_token_factory; use aave_pool::borrow_logic; + use aave_pool::mock_underlying_token_factory::Self; use aave_pool::pool; use aave_pool::pool::ReserveData; - use aave_pool::underlying_token_factory::Self; use aave_pool::validation_logic::Self; //// ================= STRUCTS ==================== /// #[event] + /// @dev Emitted on flashLoan() + /// @param target The address of the flash loan receiver contract + /// @param initiator The address initiating the flash loan + /// @param asset The address of the asset being flash borrowed + /// @param amount The amount flash borrowed + /// @param interest_rate_mode The flashloan mode: 0 for regular flashloan, 2 for Variable debt + /// @param premium The fee flash borrowed + /// @param referral_code The referral code used struct FlashLoan has store, drop { target: address, initiator: address, @@ -30,6 +42,7 @@ module aave_pool::flashloan_logic { referral_code: u16, } + /// Helper struct for internal variables used in the `executeFlashLoan` function struct FlashLoanLocalVars has copy, drop { sender: address, receiver: address, @@ -79,7 +92,20 @@ module aave_pool::flashloan_logic { } //// ================= METHODS ==================== /// - public entry fun flashloan( + /// @notice Allows smartcontracts to access the liquidity of the pool within one transaction, + /// as long as the amount taken plus a fee is returned. + /// @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept + /// into consideration. For further details please visit https://docs.aave.com/developers/ + /// @param receiver_address The address of the contract receiving the funds + /// @param assets The addresses of the assets being flash-borrowed + /// @param amounts The amounts of the assets being flash-borrowed + /// @param interest_rate_modes Types of the debt to open if the flash loan is not returned: + /// 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver + /// 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address + /// @param on_behalf_of The address that will receive the debt in the case of using on `modes` 2 + /// @param referral_code The code used to register the integrator originating the operation, for potential rewards. + /// 0 if the action is executed directly by the user, without any middle-man + public fun flashloan( account: &signer, receiver_address: address, assets: vector
, @@ -87,7 +113,7 @@ module aave_pool::flashloan_logic { interest_rate_modes: vector, on_behalf_of: address, referral_code: u16, - ) { + ): vector { execute_flash_loan_complex( account, receiver_address, @@ -98,7 +124,7 @@ module aave_pool::flashloan_logic { referral_code, (pool::get_flashloan_premium_to_protocol() as u256), (pool::get_flashloan_premium_total() as u256), - acl_manage::is_flash_borrower(signer::address_of(account)) + acl_manage::is_flash_borrower(signer::address_of(account)), ) } @@ -113,47 +139,72 @@ module aave_pool::flashloan_logic { flash_loan_premium_to_protocol: u256, flash_loan_premium_total: u256, is_authorized_flash_borrower: bool, - ) { + ): vector { // get signer account let account_address = signer::address_of(account); - assert!(account_address == on_behalf_of, error_config::get_esigner_and_on_behalf_of_no_same()); + assert!( + account_address == on_behalf_of, + error_config::get_esigner_and_on_behalf_of_no_same(), + ); // get all reserves data - let reservesData = vector::map_ref(&assets, |asset| { - let reserve_data = pool::get_reserve_data(*asset); - reserve_data - }); + let reservesData = vector::map_ref( + &assets, + |asset| { + let reserve_data = pool::get_reserve_data(*asset); + reserve_data + }, + ); // validate flashloans logic validation_logic::validate_flashloan_complex(&reservesData, &assets, &amounts); + // validate interest rates + assert!( + !vector::any( + &interest_rate_modes, + |interest_rate| { + let legitimate_interes_rate = + *interest_rate == user_config::get_interest_rate_mode_none() + || *interest_rate + == user_config::get_interest_rate_mode_variable(); + !legitimate_interes_rate + }, + ), + error::get_einvalid_interest_rate_mode_selected(), + ); + let flashloan_premium_total = if (is_authorized_flash_borrower) { 0 } - else { flash_loan_premium_total }; + else { + flash_loan_premium_total + }; let flashloan_premium_to_protocol = if (is_authorized_flash_borrower) { 0 } - else { flash_loan_premium_to_protocol }; + else { + flash_loan_premium_to_protocol + }; let flashloans = vector[]; for (i in 0..vector::length(&assets)) { // calculate premiums let total_premium = if (*vector::borrow(&interest_rate_modes, i) - == user_config::get_interest_rate_mode_none()) { - math_utils::percent_mul(*vector::borrow(&amounts, i), - flashloan_premium_total) + == user_config::get_interest_rate_mode_none()) { + math_utils::percent_mul( + *vector::borrow(&amounts, i), flashloan_premium_total + ) } else { 0 }; - let flashloan_vars = - FlashLoanLocalVars { - sender: account_address, - receiver: receiver_address, - i: (i as u256), - current_asset: *vector::borrow(&assets, i), - current_amount: *vector::borrow(&amounts, i), - total_premium, - flashloan_premium_total, - flashloan_premium_to_protocol, - }; + let flashloan_vars = FlashLoanLocalVars { + sender: account_address, + receiver: receiver_address, + i: (i as u256), + current_asset: *vector::borrow(&assets, i), + current_amount: *vector::borrow(&amounts, i), + total_premium, + flashloan_premium_total, + flashloan_premium_to_protocol, + }; // transfer the underlying to the receiver transfer_underlying_to(&flashloan_vars); @@ -162,31 +213,37 @@ module aave_pool::flashloan_logic { vector::push_back(&mut flashloans, flashloan_vars); }; - let flashloan_receipts = vector::map(flashloans, + let flashloan_receipts = vector::map( + flashloans, |flashloan| { let flashloan: FlashLoanLocalVars = flashloan; - let interest_rate_mode = *vector::borrow(&interest_rate_modes, (flashloan.i as u64)); - create_complex_flashloan_receipt(&flashloan, + let interest_rate_mode = + *vector::borrow(&interest_rate_modes, (flashloan.i as u64)); + create_complex_flashloan_receipt( + &flashloan, account_address, referral_code, on_behalf_of, - option::some(interest_rate_mode)) - }); + option::some(interest_rate_mode), + ) + }, + ); - pay_flash_loan_complex(account, flashloan_receipts) + flashloan_receipts } - fun pay_flash_loan_complex( + public fun pay_flash_loan_complex( account: &signer, flashloan_receipts: vector ) { // get the payer account let account_address = signer::address_of(account); // destroy all receipts and handle their repayment - vector::destroy(flashloan_receipts, + vector::destroy( + flashloan_receipts, |flashloan| { let ComplexFlashLoansReceipt { - sender, + sender: _, receiver, i: _, current_asset, @@ -199,45 +256,50 @@ module aave_pool::flashloan_logic { on_behalf_of } = flashloan; - // check the signer could be either sender or receiver that the receipt was issued for - assert!(signer::address_of(account) == sender || signer::address_of(account) == - receiver, 2); + // check the signer is the receiver that the receipt was issued for + assert!( + signer::address_of(account) == receiver, + error::get_flashloan_payer_not_receiver(), + ); if (*option::borrow(&interest_rate_mode) - == user_config::get_interest_rate_mode_none()) { + == user_config::get_interest_rate_mode_none()) { // do flashloan repayment - let repayment_params = - FlashLoanRepaymentParams { - amount: current_amount, - total_premium, - flashloan_premium_to_protocol, - asset: current_asset, - receiver_address: receiver, - referral_code, - }; + let repayment_params = FlashLoanRepaymentParams { + amount: current_amount, + total_premium, + flashloan_premium_to_protocol, + asset: current_asset, + receiver_address: receiver, + referral_code, + }; handle_flash_loan_repayment(account, &repayment_params); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position - borrow_logic::internal_borrow(account, // account + borrow_logic::internal_borrow( + account, // account current_asset, // asset - on_behalf_of, // on behalf of, current_amount, // amount *option::borrow(&interest_rate_mode), //interest_rate_mode referral_code, // referral_code - false // release_underlying + on_behalf_of, // on behalf of, + false, // release_underlying + ); + event::emit( + FlashLoan { + target: receiver, + initiator: account_address, + asset: current_asset, + amount: current_amount, + interest_rate_mode: *option::borrow(&interest_rate_mode), + premium: 0, + referral_code, + }, ); - event::emit(FlashLoan { - target: receiver, - initiator: account_address, - asset: current_asset, - amount: current_amount, - interest_rate_mode: *option::borrow(&interest_rate_mode), - premium: 0, - referral_code, - }); }; - }) + }, + ) } fun create_simple_flashloan_receipt( @@ -287,17 +349,27 @@ module aave_pool::flashloan_logic { fun transfer_underlying_to(flashloan_vars: &FlashLoanLocalVars) { let reserve_data = pool::get_reserve_data(flashloan_vars.current_asset); let a_token_address = pool::get_reserve_a_token_address(&reserve_data); - a_token_factory::transfer_underlying_to(flashloan_vars.receiver, flashloan_vars.current_amount, - a_token_address) + a_token_factory::transfer_underlying_to( + flashloan_vars.receiver, flashloan_vars.current_amount, a_token_address + ) } - public entry fun flash_loan_simple( + /// @notice Allows smartcontracts to access the liquidity of the pool within one transaction, + /// as long as the amount taken plus a fee is returned. + /// @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept + /// into consideration. For further details please visit https://docs.aave.com/developers/ + /// @param receiver_address The address of the contract receiving the funds + /// @param asset The address of the asset being flash-borrowed + /// @param amount The amount of the asset being flash-borrowed + /// @param referral_code The code used to register the integrator originating the operation, for potential rewards. + /// 0 if the action is executed directly by the user, without any middle-man + public fun flash_loan_simple( account: &signer, receiver_address: address, asset: address, amount: u256, referral_code: u16 - ) { + ): SimpleFlashLoansReceipt { execute_flash_loan_simple( account, receiver_address, @@ -305,7 +377,7 @@ module aave_pool::flashloan_logic { amount, referral_code, (pool::get_flashloan_premium_to_protocol() as u256), - (pool::get_flashloan_premium_total() as u256) + (pool::get_flashloan_premium_total() as u256), ) } @@ -317,7 +389,7 @@ module aave_pool::flashloan_logic { referral_code: u16, flashloan_premium_to_protocol: u256, flashloan_premium_total: u256 - ) { + ): SimpleFlashLoansReceipt { // sender account address let account_address = signer::address_of(account); @@ -328,37 +400,39 @@ module aave_pool::flashloan_logic { validation_logic::validate_flashloan_simple(&reserve_data); // create flashloan - let flashloan = - FlashLoanLocalVars { - sender: account_address, - receiver: receiver_address, - i: 0, - current_asset: asset, - current_amount: amount, - total_premium: math_utils::percent_mul(amount, flashloan_premium_total), - flashloan_premium_total, - flashloan_premium_to_protocol, - }; + let flashloan = FlashLoanLocalVars { + sender: account_address, + receiver: receiver_address, + i: 0, + current_asset: asset, + current_amount: amount, + total_premium: math_utils::percent_mul(amount, flashloan_premium_total), + flashloan_premium_total, + flashloan_premium_to_protocol, + }; // transfer the underlying to the receiver transfer_underlying_to(&flashloan); // create and return the flashloan receipt - let flashloan_receipt = create_simple_flashloan_receipt(&flashloan, - account_address, - referral_code, - receiver_address, - option::none(),); + let flashloan_receipt = + create_simple_flashloan_receipt( + &flashloan, + account_address, + referral_code, + receiver_address, + option::none(), + ); - pay_flash_loan_simple(account, flashloan_receipt) + flashloan_receipt } - fun pay_flash_loan_simple( + public fun pay_flash_loan_simple( account: &signer, flashloan_receipt: SimpleFlashLoansReceipt ) { // destructure the receipt let SimpleFlashLoansReceipt { - sender, + sender: _, receiver, i: _, current_asset, @@ -371,23 +445,27 @@ module aave_pool::flashloan_logic { on_behalf_of: _ } = flashloan_receipt; - // check the signer could be either sender or receiver that the receipt was issued for - assert!(signer::address_of(account) == sender || signer::address_of(account) == receiver, - 2); + // check the signer is the receiver that the receipt was issued for + assert!( + signer::address_of(account) == receiver, + error::get_flashloan_payer_not_receiver(), + ); // do flashloan repayment - let repayment_params = - FlashLoanRepaymentParams { - amount: current_amount, - total_premium, - flashloan_premium_to_protocol, - asset: current_asset, - receiver_address: receiver, - referral_code, - }; + let repayment_params = FlashLoanRepaymentParams { + amount: current_amount, + total_premium, + flashloan_premium_to_protocol, + asset: current_asset, + receiver_address: receiver, + referral_code, + }; handle_flash_loan_repayment(account, &repayment_params); } + /// @notice Handles repayment of flashloaned assets + premium + /// @dev Will pull the amount + premium from the receiver, so must have approved pool + /// @param params The additional parameters needed to execute the repayment function fun handle_flash_loan_repayment( account: &signer, repayment_params: &FlashLoanRepaymentParams ) { @@ -397,7 +475,10 @@ module aave_pool::flashloan_logic { // compute amount plus premiums let premium_to_protocol = - math_utils::percent_mul(repayment_params.total_premium, repayment_params.flashloan_premium_to_protocol); + math_utils::percent_mul( + repayment_params.total_premium, + repayment_params.flashloan_premium_to_protocol, + ); let premium_to_lp = repayment_params.total_premium - premium_to_protocol; let amount_plus_premium = repayment_params.amount + repayment_params.total_premium; @@ -405,47 +486,67 @@ module aave_pool::flashloan_logic { pool::update_state(repayment_params.asset, &mut reserve_data); // update liquidity index - let a_token_supply = pool::scale_a_token_total_supply(a_token_address); - let reserve_accrued_to_treasury = pool::get_reserve_accrued_to_treasury(&reserve_data); + let a_token_supply = pool::scaled_a_token_total_supply(a_token_address); + let reserve_accrued_to_treasury = + pool::get_reserve_accrued_to_treasury(&reserve_data); let reserve_liquidity_index = pool::get_reserve_liquidity_index(&reserve_data); let total_liq = - a_token_supply + wad_ray_math::ray_mul(reserve_accrued_to_treasury, - (reserve_liquidity_index as u256)); - let next_liquidity_index = pool::cumulate_to_liquidity_index(repayment_params.asset, &mut reserve_data, - total_liq, premium_to_lp); + a_token_supply + + wad_ray_math::ray_mul( + reserve_accrued_to_treasury, (reserve_liquidity_index as u256) + ); + let next_liquidity_index = + pool::cumulate_to_liquidity_index( + repayment_params.asset, + &mut reserve_data, + total_liq, + premium_to_lp, + ); // update accrued to treasury let new_reserve_accrued_to_treasury = - reserve_accrued_to_treasury + wad_ray_math::ray_div(premium_to_protocol, - (next_liquidity_index as u256)); - pool::set_reserve_accrued_to_treasury(repayment_params.asset, - new_reserve_accrued_to_treasury); + reserve_accrued_to_treasury + + wad_ray_math::ray_div(premium_to_protocol, next_liquidity_index); + pool::set_reserve_accrued_to_treasury( + repayment_params.asset, new_reserve_accrued_to_treasury + ); // update pool interest rates - pool::update_interest_rates(&mut reserve_data, repayment_params.asset, - amount_plus_premium, 0); + pool::update_interest_rates( + &mut reserve_data, + repayment_params.asset, + amount_plus_premium, + 0, + ); // transfer underlying tokens - let a_token_account_address = underlying_token_factory::get_token_account_address(); - underlying_token_factory::transfer_from(repayment_params.receiver_address, + let a_token_account_address = + a_token_factory::get_token_account_address(a_token_address); + mock_underlying_token_factory::transfer_from( + repayment_params.receiver_address, a_token_account_address, (amount_plus_premium as u64), - repayment_params.asset); + repayment_params.asset, + ); // handle the a token repayment - a_token_factory::handle_repayment(repayment_params.receiver_address, + a_token_factory::handle_repayment( + repayment_params.receiver_address, repayment_params.receiver_address, amount_plus_premium, - a_token_address); - - event::emit(FlashLoan { - target: repayment_params.receiver_address, - initiator: signer::address_of(account), - asset: repayment_params.asset, - amount: repayment_params.amount, - interest_rate_mode: user_config::get_interest_rate_mode_none(), - premium: repayment_params.total_premium, - referral_code: repayment_params.referral_code, - }) + a_token_address, + ); + + event::emit( + FlashLoan { + target: repayment_params.receiver_address, + initiator: signer::address_of(account), + asset: repayment_params.asset, + amount: repayment_params.amount, + interest_rate_mode: user_config::get_interest_rate_mode_none(), + premium: repayment_params.total_premium, + referral_code: repayment_params.referral_code, + }, + ) } -} \ No newline at end of file +} diff --git a/aave-core/sources/aave-periphery/admin_controlled_ecosystem_reserve.move b/aave-core/sources/aave-periphery/admin_controlled_ecosystem_reserve.move index 8d98fdb..98418fe 100644 --- a/aave-core/sources/aave-periphery/admin_controlled_ecosystem_reserve.move +++ b/aave-core/sources/aave-periphery/admin_controlled_ecosystem_reserve.move @@ -14,9 +14,9 @@ module aave_pool::admin_controlled_ecosystem_reserve { const NOT_FUNDS_ADMIN: u64 = 1; - const REVISION: u256 = 1; + const REVISION: u256 = 2; - const ONLY_BY_FUNDS_ADMIN: u64 = 1; + const ONLY_BY_FUNDS_ADMIN: u64 = 3; const ADMIN_CONTROLLED_ECOSYSTEM_RESERVE: vector = b"ADMIN_CONTROLLED_ECOSYSTEM_RESERVE"; @@ -37,18 +37,22 @@ module aave_pool::admin_controlled_ecosystem_reserve { &object::create_named_object(sender, ADMIN_CONTROLLED_ECOSYSTEM_RESERVE); let state_object_signer = &object::generate_signer(state_object_constructor_ref); - move_to(state_object_signer, + move_to( + state_object_signer, AdminControlledEcosystemReserveData { fungible_assets: smart_table::new, Object>(), transfer_ref: object::generate_transfer_ref(state_object_constructor_ref), extend_ref: object::generate_extend_ref(state_object_constructor_ref), funds_admin: signer::address_of(sender), - }); + }, + ); } public fun check_is_funds_admin(account: address) { - assert!(acl_manage::is_admin_controlled_ecosystem_reserve_funds_admin_role(account), - NOT_FUNDS_ADMIN); + assert!( + acl_manage::is_admin_controlled_ecosystem_reserve_funds_admin_role(account), + NOT_FUNDS_ADMIN, + ); } public fun get_revision(): u256 { @@ -58,7 +62,8 @@ module aave_pool::admin_controlled_ecosystem_reserve { public fun get_funds_admin(): address acquires AdminControlledEcosystemReserveData { let admin_controlled_ecosystem_reserve_data = borrow_global_mut( - admin_controlled_ecosystem_reserve_address()); + admin_controlled_ecosystem_reserve_address() + ); let account = admin_controlled_ecosystem_reserve_data.funds_admin; check_is_funds_admin(account); account @@ -73,16 +78,21 @@ module aave_pool::admin_controlled_ecosystem_reserve { public fun admin_controlled_ecosystem_reserve_object() : Object { object::address_to_object( - admin_controlled_ecosystem_reserve_address()) + admin_controlled_ecosystem_reserve_address() + ) } fun set_funds_admin_internal(admin: &signer, account: address) acquires AdminControlledEcosystemReserveData { let admin_controlled_ecosystem_reserve_data = borrow_global_mut( - admin_controlled_ecosystem_reserve_address()); - acl_manage::remove_admin_controlled_ecosystem_reserve_funds_admin_role(admin, - admin_controlled_ecosystem_reserve_data.funds_admin); - acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role(admin, account); + admin_controlled_ecosystem_reserve_address() + ); + acl_manage::remove_admin_controlled_ecosystem_reserve_funds_admin_role( + admin, admin_controlled_ecosystem_reserve_data.funds_admin + ); + acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( + admin, account + ); admin_controlled_ecosystem_reserve_data.funds_admin = account; event::emit(NewFundsAdmin { funds_admin: account }); @@ -95,21 +105,32 @@ module aave_pool::admin_controlled_ecosystem_reserve { let admin_controlled_ecosystem_reserve_data = borrow_global_mut( - admin_controlled_ecosystem_reserve_address()); + admin_controlled_ecosystem_reserve_address() + ); - if (smart_table::contains(&admin_controlled_ecosystem_reserve_data.fungible_assets, - asset_metadata)) { + if (smart_table::contains( + &admin_controlled_ecosystem_reserve_data.fungible_assets, asset_metadata + )) { let collector_fungible_store = - smart_table::borrow(&admin_controlled_ecosystem_reserve_data.fungible_assets, - asset_metadata); + smart_table::borrow( + &admin_controlled_ecosystem_reserve_data.fungible_assets, + asset_metadata, + ); let collector_fungible_store_signer = - object::generate_signer_for_extending(&admin_controlled_ecosystem_reserve_data - .extend_ref); + object::generate_signer_for_extending( + &admin_controlled_ecosystem_reserve_data.extend_ref + ); let receiver_fungible_store = - primary_fungible_store::ensure_primary_store_exists(receiver, asset_metadata); - - fungible_asset::transfer(&collector_fungible_store_signer, *collector_fungible_store, - receiver_fungible_store, amount); + primary_fungible_store::ensure_primary_store_exists( + receiver, asset_metadata + ); + + fungible_asset::transfer( + &collector_fungible_store_signer, + *collector_fungible_store, + receiver_fungible_store, + amount, + ); } } @@ -124,7 +145,8 @@ module aave_pool::admin_controlled_ecosystem_reserve { #[test_only] fun create_test_fa(creator: &signer): Object { let test_symbol = b"TEST"; - standard_token::initialize(creator, + standard_token::initialize( + creator, 0, utf8(b"Test Token"), utf8(test_symbol), @@ -133,9 +155,10 @@ module aave_pool::admin_controlled_ecosystem_reserve { utf8(b"http://example.com"), vector[true, true, true], @0x1, - false,); - let metadata_address = object::create_object_address(&signer::address_of(creator), - test_symbol); + false, + ); + let metadata_address = + object::create_object_address(&signer::address_of(creator), test_symbol); object::address_to_object(metadata_address) } @@ -151,7 +174,8 @@ module aave_pool::admin_controlled_ecosystem_reserve { acl_manage::test_init_module(aave_role_super_admin); // set fund admin acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(acl_fund_admin)); + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted check_is_funds_admin(signer::address_of(acl_fund_admin)); @@ -161,14 +185,21 @@ module aave_pool::admin_controlled_ecosystem_reserve { // mint coins to user let _creator_address = signer::address_of(fa_creator); let user_address = signer::address_of(user_account); - standard_token::mint_to_primary_stores(fa_creator, metadata, vector[user_address], - vector[100]); - assert!(primary_fungible_store::balance(user_address, metadata) == 100, TEST_SUCCESS); + standard_token::mint_to_primary_stores( + fa_creator, metadata, vector[user_address], vector[100] + ); + assert!( + primary_fungible_store::balance(user_address, metadata) == 100, TEST_SUCCESS + ); // user withdraws all fas he has let fa = - standard_token::withdraw_from_primary_stores(fa_creator, metadata, vector[user_address], - vector[100]); + standard_token::withdraw_from_primary_stores( + fa_creator, + metadata, + vector[user_address], + vector[100], + ); assert!(fungible_asset::amount(&fa) == 100, TEST_SUCCESS); initialize(periphery_account); @@ -177,7 +208,8 @@ module aave_pool::admin_controlled_ecosystem_reserve { let admin_controlled_ecosystem_reserve_data = borrow_global_mut( - admin_controlled_ecosystem_reserve_address()); + admin_controlled_ecosystem_reserve_address() + ); let asset_object_constructor_ref = object::create_object(admin_controlled_ecosystem_reserve_address()); @@ -186,9 +218,11 @@ module aave_pool::admin_controlled_ecosystem_reserve { fungible_asset::deposit(collector_fungible_store, fa); - smart_table::upsert(&mut admin_controlled_ecosystem_reserve_data.fungible_assets, + smart_table::upsert( + &mut admin_controlled_ecosystem_reserve_data.fungible_assets, asset_metadata, - collector_fungible_store); + collector_fungible_store, + ); transfer_out(acl_fund_admin, metadata, user_address, 50); } diff --git a/aave-core/sources/aave-periphery/coin_wrapper.move b/aave-core/sources/aave-periphery/coin_wrapper.move index cb7c15e..d526174 100644 --- a/aave-core/sources/aave-periphery/coin_wrapper.move +++ b/aave-core/sources/aave-periphery/coin_wrapper.move @@ -44,16 +44,19 @@ module aave_pool::coin_wrapper { if (is_initialized()) { return }; let signer = &package_manager::get_signer(); - let (coin_wrapper_signer, signer_cap) = account::create_resource_account(signer, - COIN_WRAPPER_NAME); - package_manager::add_address(string::utf8(COIN_WRAPPER_NAME), - signer::address_of(&coin_wrapper_signer)); - move_to(&coin_wrapper_signer, + let (coin_wrapper_signer, signer_cap) = + account::create_resource_account(signer, COIN_WRAPPER_NAME); + package_manager::add_address( + string::utf8(COIN_WRAPPER_NAME), signer::address_of(&coin_wrapper_signer) + ); + move_to( + &coin_wrapper_signer, WrapperAccount { signer_cap, coin_to_fungible_asset: smart_table::new(), fungible_asset_to_coin: smart_table::new(), - }); + }, + ); } #[view] @@ -150,7 +153,9 @@ module aave_pool::coin_wrapper { &account::create_signer_with_capability(&wrapper_account.signer_cap); if (!smart_table::contains(coin_to_fungible_asset, coin_type)) { let metadata_constructor_ref = - &object::create_named_object(wrapper_signer, *string::bytes(&coin_type)); + &object::create_named_object( + wrapper_signer, *string::bytes(&coin_type) + ); primary_fungible_store::create_primary_store_enabled_fungible_asset( metadata_constructor_ref, option::none(), @@ -158,17 +163,23 @@ module aave_pool::coin_wrapper { coin::symbol(), coin::decimals(), string::utf8(b""), - string::utf8(b""),); + string::utf8(b""), + ); let mint_ref = fungible_asset::generate_mint_ref(metadata_constructor_ref); let burn_ref = fungible_asset::generate_burn_ref(metadata_constructor_ref); let metadata = - object::object_from_constructor_ref(metadata_constructor_ref); - smart_table::add(coin_to_fungible_asset, + object::object_from_constructor_ref( + metadata_constructor_ref + ); + smart_table::add( + coin_to_fungible_asset, coin_type, - FungibleAssetData { metadata, mint_ref, burn_ref, }); - smart_table::add(&mut wrapper_account.fungible_asset_to_coin, metadata, - coin_type); + FungibleAssetData { metadata, mint_ref, burn_ref, }, + ); + smart_table::add( + &mut wrapper_account.fungible_asset_to_coin, metadata, coin_type + ); }; smart_table::borrow(coin_to_fungible_asset, coin_type).metadata } @@ -195,4 +206,9 @@ module aave_pool::coin_wrapper { public fun test_unwrap(fa: FungibleAsset): Coin acquires WrapperAccount { unwrap(fa) } + + #[test_only] + public fun test_get_original(fungible_asset: Object): String acquires WrapperAccount { + get_original(fungible_asset) + } } diff --git a/aave-core/sources/aave-periphery/collector.move b/aave-core/sources/aave-periphery/collector.move index a5a312d..e3d2940 100644 --- a/aave-core/sources/aave-periphery/collector.move +++ b/aave-core/sources/aave-periphery/collector.move @@ -42,17 +42,19 @@ module aave_pool::collector { /// Initialize metadata object and store the refs specified by `ref_flags`. fun init_module(sender: &signer) { // 1, create the object and a generate a signer - let state_object_constructor_ref = &object::create_named_object(sender, - COLLECTOR_NAME); + let state_object_constructor_ref = + &object::create_named_object(sender, COLLECTOR_NAME); let state_object_signer = &object::generate_signer(state_object_constructor_ref); // 2. move the resources into it, incl. the references - move_to(state_object_signer, + move_to( + state_object_signer, CollectorData { fungible_assets: smart_table::new, Object>(), transfer_ref: object::generate_transfer_ref(state_object_constructor_ref), extend_ref: object::generate_extend_ref(state_object_constructor_ref), - }); + }, + ); } #[test_only] @@ -95,15 +97,18 @@ module aave_pool::collector { if (!smart_table::contains(&collector_data.fungible_assets, asset_metadata)) { // create fungible store (object) with the collector being its address(owner) - let collector_fungible_store = generate_secondary_collector_fungible_store( - asset_metadata); + let collector_fungible_store = + generate_secondary_collector_fungible_store(asset_metadata); // deposit the fa fungible_asset::deposit(collector_fungible_store, fa); // update the resource - smart_table::upsert(&mut collector_data.fungible_assets, asset_metadata, - collector_fungible_store); + smart_table::upsert( + &mut collector_data.fungible_assets, + asset_metadata, + collector_fungible_store, + ); } else { let collector_fungible_store = smart_table::borrow(&collector_data.fungible_assets, asset_metadata); @@ -127,11 +132,17 @@ module aave_pool::collector { let collector_fungible_store_signer = object::generate_signer_for_extending(&collector_data.extend_ref); let receiver_fungible_store = - primary_fungible_store::ensure_primary_store_exists(receiver, asset_metadata); + primary_fungible_store::ensure_primary_store_exists( + receiver, asset_metadata + ); // transfer the amount from the collector's sec store to the receiver's store using the collectors signer which is also the owner of the sec.store - fungible_asset::transfer(&collector_fungible_store_signer, *collector_fungible_store, - receiver_fungible_store, amount); + fungible_asset::transfer( + &collector_fungible_store_signer, + *collector_fungible_store, + receiver_fungible_store, + amount, + ); } } diff --git a/aave-core/sources/aave-periphery/ecosystem_reserve_v2.move b/aave-core/sources/aave-periphery/ecosystem_reserve_v2.move index 2d69636..6c32752 100644 --- a/aave-core/sources/aave-periphery/ecosystem_reserve_v2.move +++ b/aave-core/sources/aave-periphery/ecosystem_reserve_v2.move @@ -6,9 +6,9 @@ module aave_pool::ecosystem_reserve_v2 { use aptos_framework::timestamp; use aave_acl::acl_manage::Self; - use aave_pool::underlying_token_factory; use aave_pool::admin_controlled_ecosystem_reserve::check_is_funds_admin; + use aave_pool::mock_underlying_token_factory; use aave_pool::stream::{Self, Stream}; #[test_only] @@ -17,17 +17,17 @@ module aave_pool::ecosystem_reserve_v2 { use aptos_framework::timestamp::set_time_has_started_for_testing; const EROLE_NOT_EXISTS: u64 = 1; - const ESTREAM_NOT_EXISTS: u64 = 1; - const NOT_FUNDS_ADMIN: u64 = 1; - const ESTREAM_TO_THE_CONTRACT_ITSELF: u64 = 1; - const ESTREAM_TO_THE_CALLER: u64 = 1; - const EDEPOSIT_IS_ZERO: u64 = 1; - const ESTART_TIME_BEFORE_BLOCK_TIMESTAMP: u64 = 1; - const ESTOP_TIME_BEFORE_THE_START_TIME: u64 = 1; - const EDEPOSIT_SMALLER_THAN_TIME_DELTA: u64 = 1; - const EDEPOSIT_NOT_MULTIPLE_OF_TIME_DELTA: u64 = 1; - const EAMOUNT_IS_ZERO: u64 = 1; - const EAMOUNT_EXCEEDS_THE_AVAILABLE_BALANCE: u64 = 1; + const ESTREAM_NOT_EXISTS: u64 = 2; + const NOT_FUNDS_ADMIN: u64 = 3; + const ESTREAM_TO_THE_CONTRACT_ITSELF: u64 = 4; + const ESTREAM_TO_THE_CALLER: u64 = 5; + const EDEPOSIT_IS_ZERO: u64 = 6; + const ESTART_TIME_BEFORE_BLOCK_TIMESTAMP: u64 = 7; + const ESTOP_TIME_BEFORE_THE_START_TIME: u64 = 8; + const EDEPOSIT_SMALLER_THAN_TIME_DELTA: u64 = 9; + const EDEPOSIT_NOT_MULTIPLE_OF_TIME_DELTA: u64 = 10; + const EAMOUNT_IS_ZERO: u64 = 11; + const EAMOUNT_EXCEEDS_THE_AVAILABLE_BALANCE: u64 = 12; const ECOSYSTEM_RESERVE_V2_NAME: vector = b"AAVE_ECOSYSTEM_RESERVE_V2"; @@ -64,8 +64,10 @@ module aave_pool::ecosystem_reserve_v2 { } fun only_admin_or_recipient(account: address, stream_id: u256) acquires EcosystemReserveV2Data { - assert!(acl_manage::is_funds_admin(account) || is_recipient(account, stream_id), - NOT_FUNDS_ADMIN); + assert!( + acl_manage::is_funds_admin(account) || is_recipient(account, stream_id), + NOT_FUNDS_ADMIN, + ); } fun is_recipient(account: address, stream_id: u256): bool acquires EcosystemReserveV2Data { @@ -86,8 +88,10 @@ module aave_pool::ecosystem_reserve_v2 { let ecosystem_reserve_v2_data = borrow_global(ecosystem_reserve_v2_data_address()); - assert!(smart_table::contains(&ecosystem_reserve_v2_data.streams, stream_id), - ESTREAM_NOT_EXISTS); + assert!( + smart_table::contains(&ecosystem_reserve_v2_data.streams, stream_id), + ESTREAM_NOT_EXISTS, + ); let stream_item = smart_table::borrow(&ecosystem_reserve_v2_data.streams, stream_id); assert!(stream::is_entity(stream_item), ESTREAM_NOT_EXISTS); @@ -100,15 +104,17 @@ module aave_pool::ecosystem_reserve_v2 { } public fun initialize(sender: &signer,) { - let state_object_constructor_ref = &object::create_named_object(sender, - ECOSYSTEM_RESERVE_V2_NAME); + let state_object_constructor_ref = + &object::create_named_object(sender, ECOSYSTEM_RESERVE_V2_NAME); let state_object_signer = &object::generate_signer(state_object_constructor_ref); - move_to(state_object_signer, + move_to( + state_object_signer, EcosystemReserveV2Data { streams: smart_table::new(), next_stream_id: 1, - }); + }, + ); } #[view] @@ -118,7 +124,9 @@ module aave_pool::ecosystem_reserve_v2 { #[view] public fun ecosystem_reserve_v2_data_object(): Object { - object::address_to_object(ecosystem_reserve_v2_data_address()) + object::address_to_object( + ecosystem_reserve_v2_data_address() + ) } fun get_stream(stream_id: u256): (address, address, u256, address, u256, u256, u256, u256) acquires EcosystemReserveV2Data { @@ -164,8 +172,8 @@ module aave_pool::ecosystem_reserve_v2 { let stream_item = smart_table::borrow(&ecosystem_reserve_v2_data.streams, stream_id); - let (sender, recipient, deposit, _, _, _, remaining_balance, rate_per_second) = stream::get_stream( - stream_item); + let (sender, recipient, deposit, _, _, _, remaining_balance, rate_per_second) = + stream::get_stream(stream_item); let recipient_balance = delta * rate_per_second; @@ -195,8 +203,10 @@ module aave_pool::ecosystem_reserve_v2 { ): u256 acquires EcosystemReserveV2Data { check_is_funds_admin(signer::address_of(sender)); - assert!(recipient != ecosystem_reserve_v2_data_address(), - ESTREAM_TO_THE_CONTRACT_ITSELF); + assert!( + recipient != ecosystem_reserve_v2_data_address(), + ESTREAM_TO_THE_CONTRACT_ITSELF, + ); assert!(recipient != signer::address_of(sender), ESTREAM_TO_THE_CALLER); assert!(deposit > 0, EDEPOSIT_IS_ZERO); let now = (timestamp::now_seconds() as u256); @@ -214,9 +224,12 @@ module aave_pool::ecosystem_reserve_v2 { let stream_id = get_next_stream_id(); let ecosystem_reserve_v2_data = - borrow_global_mut(ecosystem_reserve_v2_data_address()); + borrow_global_mut( + ecosystem_reserve_v2_data_address() + ); let stream_item = - stream::create_stream(deposit, + stream::create_stream( + deposit, rate_per_second, deposit, start_time, @@ -224,14 +237,18 @@ module aave_pool::ecosystem_reserve_v2 { recipient, signer::address_of(sender), token_address, - true); + true, + ); - smart_table::upsert(&mut ecosystem_reserve_v2_data.streams, stream_id, stream_item); + smart_table::upsert( + &mut ecosystem_reserve_v2_data.streams, stream_id, stream_item + ); ecosystem_reserve_v2_data.next_stream_id = ecosystem_reserve_v2_data.next_stream_id + 1; - event::emit(CreateStream { + event::emit( + CreateStream { stream_id, sender: signer::address_of(sender), recipient, @@ -239,12 +256,15 @@ module aave_pool::ecosystem_reserve_v2 { token_address, start_time, stop_time - }); + }, + ); stream_id } - fun withdraw_from_stream(sender: &signer, stream_id: u256, amount: u256): bool acquires EcosystemReserveV2Data { + fun withdraw_from_stream( + sender: &signer, stream_id: u256, amount: u256 + ): bool acquires EcosystemReserveV2Data { stream_exists(stream_id); check_is_funds_admin(signer::address_of(sender)); @@ -254,21 +274,23 @@ module aave_pool::ecosystem_reserve_v2 { let stream_item = smart_table::borrow(&ecosystem_reserve_v2_data.streams, stream_id); - let (_, recipient, _, _, _, _, remaining_balance, _) = stream::get_stream( - stream_item); + let (_, recipient, _, _, _, _, remaining_balance, _) = + stream::get_stream(stream_item); let balance = balance_of(stream_id, recipient); assert!(balance >= amount, EAMOUNT_EXCEEDS_THE_AVAILABLE_BALANCE); let ecosystem_reserve_v2_data = - borrow_global_mut(ecosystem_reserve_v2_data_address()); + borrow_global_mut( + ecosystem_reserve_v2_data_address() + ); let stream_item = smart_table::borrow_mut(&mut ecosystem_reserve_v2_data.streams, stream_id); stream::set_remaining_balance(stream_item, remaining_balance - amount); - let (_, recipient, _, _, _, _, remaining_balance, _) = stream::get_stream( - stream_item); + let (_, recipient, _, _, _, _, remaining_balance, _) = + stream::get_stream(stream_item); if (remaining_balance == 0) { smart_table::remove(&mut ecosystem_reserve_v2_data.streams, stream_id); @@ -287,29 +309,37 @@ module aave_pool::ecosystem_reserve_v2 { let stream_item = smart_table::borrow(&ecosystem_reserve_v2_data.streams, stream_id); - let (stream_sender, recipient, _, token_address, _, _, _, _) = stream::get_stream( - stream_item); + let (stream_sender, recipient, _, token_address, _, _, _, _) = + stream::get_stream(stream_item); let sender_balance = balance_of(stream_id, stream_sender); let recipient_balance = balance_of(stream_id, recipient); let ecosystem_reserve_v2_data = - borrow_global_mut(ecosystem_reserve_v2_data_address()); + borrow_global_mut( + ecosystem_reserve_v2_data_address() + ); smart_table::remove(&mut ecosystem_reserve_v2_data.streams, stream_id); if (recipient_balance > 0) { - underlying_token_factory::transfer_from(stream_sender, recipient, - (recipient_balance as u64), token_address); + mock_underlying_token_factory::transfer_from( + stream_sender, + recipient, + (recipient_balance as u64), + token_address, + ); }; - event::emit(CancelStream { + event::emit( + CancelStream { stream_id, sender: stream_sender, recipient, sender_balance, recipient_balance, - }); + }, + ); true } @@ -338,12 +368,69 @@ module aave_pool::ecosystem_reserve_v2 { // set fund admin acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(acl_fund_admin)); + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); + // assert role is granted + acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)); + + acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( + aave_role_super_admin, signer::address_of(periphery_account) + ); + + initialize(periphery_account); + + let _rate_per_second = 1; + let _remaining_balance = 1; + let start_time = (one_hour_in_secs as u256) * 2; + let stop_time = (one_hour_in_secs as u256) * 3; + let deposit = (one_hour_in_secs as u256) * 2; + let recipient = signer::address_of(user_account); + let _sender = signer::address_of(periphery_account); + let token_address = signer::address_of(periphery_account); + let _is_entity = true; + + let stream_id = + create_stream( + periphery_account, + recipient, + deposit, + token_address, + start_time, + stop_time, + ); + + assert!(stream_id == 1, TEST_SUCCESS); + } + + #[test(aave_role_super_admin = @aave_acl, periphery_account = @aave_pool, acl_fund_admin = @0x111, user_account = @0x222, creator = @0x1)] + fun test_only_admin_or_recipient( + aave_role_super_admin: &signer, + periphery_account: &signer, + acl_fund_admin: &signer, + user_account: &signer, + creator: &signer, + ) acquires EcosystemReserveV2Data { + // init acl + acl_manage::test_init_module(aave_role_super_admin); + + set_time_has_started_for_testing(creator); + + let one_hour_in_secs = 1 * 60 * 60; + + fast_forward_seconds(one_hour_in_secs); + // get the ts for one hour ago + let _ts_one_hour_ago = timestamp::now_seconds() - one_hour_in_secs; + + // set fund admin + acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)); acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(periphery_account)); + aave_role_super_admin, signer::address_of(periphery_account) + ); initialize(periphery_account); @@ -358,14 +445,18 @@ module aave_pool::ecosystem_reserve_v2 { let _is_entity = true; let stream_id = - create_stream(periphery_account, + create_stream( + periphery_account, recipient, deposit, token_address, start_time, - stop_time); + stop_time, + ); assert!(stream_id == 1, TEST_SUCCESS); + + only_admin_or_recipient(token_address, 1); } #[test(aave_role_super_admin = @aave_acl, periphery_account = @aave_pool, acl_fund_admin = @0x111, user_account = @0x222, creator = @0x1)] @@ -389,12 +480,14 @@ module aave_pool::ecosystem_reserve_v2 { // set fund admin acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(acl_fund_admin)); + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)); acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(periphery_account)); + aave_role_super_admin, signer::address_of(periphery_account) + ); initialize(periphery_account); @@ -409,12 +502,14 @@ module aave_pool::ecosystem_reserve_v2 { let _is_entity = true; let stream_id = - create_stream(periphery_account, + create_stream( + periphery_account, recipient, deposit, token_address, start_time, - stop_time); + stop_time, + ); assert!(stream_id == 1, 1); @@ -442,12 +537,14 @@ module aave_pool::ecosystem_reserve_v2 { // set fund admin acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(acl_fund_admin)); + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)); acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(periphery_account)); + aave_role_super_admin, signer::address_of(periphery_account) + ); initialize(periphery_account); @@ -462,12 +559,14 @@ module aave_pool::ecosystem_reserve_v2 { let _is_entity = true; let stream_id = - create_stream(periphery_account, + create_stream( + periphery_account, recipient, deposit, token_address, start_time, - stop_time); + stop_time, + ); assert!(stream_id == 1, 1); @@ -498,12 +597,14 @@ module aave_pool::ecosystem_reserve_v2 { // set fund admin acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(acl_fund_admin)); + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)); acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(periphery_account)); + aave_role_super_admin, signer::address_of(periphery_account) + ); initialize(periphery_account); @@ -518,12 +619,14 @@ module aave_pool::ecosystem_reserve_v2 { let _is_entity = true; let stream_id = - create_stream(periphery_account, + create_stream( + periphery_account, recipient, deposit, token_address, start_time, - stop_time); + stop_time, + ); assert!(stream_id == 1, 1); @@ -556,12 +659,14 @@ module aave_pool::ecosystem_reserve_v2 { // set fund admin acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(acl_fund_admin)); + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)); acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(periphery_account)); + aave_role_super_admin, signer::address_of(periphery_account) + ); initialize(periphery_account); @@ -576,23 +681,27 @@ module aave_pool::ecosystem_reserve_v2 { let _is_entity = true; let stream_id = - create_stream(periphery_account, + create_stream( + periphery_account, recipient, deposit, token_address, start_time, - stop_time); + stop_time, + ); assert!(stream_id == 1, 1); - let (stream_sender, + let ( + stream_sender, stream_recipient, stream_deposit, stream_token_address, stream_start_time, stream_stop_time, stream_remaining_balance, - stream_rate_per_second) = get_stream(stream_id); + stream_rate_per_second + ) = get_stream(stream_id); assert!(stream_sender == sender, 1); assert!(stream_recipient == recipient, 1); @@ -625,12 +734,14 @@ module aave_pool::ecosystem_reserve_v2 { // set fund admin acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(acl_fund_admin)); + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)); acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(periphery_account)); + aave_role_super_admin, signer::address_of(periphery_account) + ); initialize(periphery_account); @@ -645,12 +756,14 @@ module aave_pool::ecosystem_reserve_v2 { let _is_entity = true; let stream_id = - create_stream(periphery_account, + create_stream( + periphery_account, recipient, deposit, token_address, start_time, - stop_time); + stop_time, + ); assert!(stream_id == 1, 1); @@ -684,12 +797,14 @@ module aave_pool::ecosystem_reserve_v2 { // set fund admin acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(acl_fund_admin)); + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)); acl_manage::add_admin_controlled_ecosystem_reserve_funds_admin_role( - aave_role_super_admin, signer::address_of(periphery_account)); + aave_role_super_admin, signer::address_of(periphery_account) + ); initialize(periphery_account); @@ -704,12 +819,14 @@ module aave_pool::ecosystem_reserve_v2 { let _is_entity = true; let stream_id = - create_stream(periphery_account, + create_stream( + periphery_account, recipient, deposit, token_address, start_time, - stop_time); + stop_time, + ); assert!(stream_id == 1, 1); diff --git a/aave-core/sources/aave-periphery/emission_manager.move b/aave-core/sources/aave-periphery/emission_manager.move index d277c37..4945714 100644 --- a/aave-core/sources/aave-periphery/emission_manager.move +++ b/aave-core/sources/aave-periphery/emission_manager.move @@ -21,8 +21,8 @@ module aave_pool::emission_manager { }; const ENOT_MANAGEMENT: u64 = 1; - const NOT_EMISSION_ADMIN: u64 = 1; - const ONLY_EMISSION_ADMIN: u64 = 1; + const NOT_EMISSION_ADMIN: u64 = 2; + const ONLY_EMISSION_ADMIN: u64 = 3; const EMISSION_MANAGER_NAME: vector = b"EMISSION_MANAGER"; @@ -46,17 +46,19 @@ module aave_pool::emission_manager { } public fun initialize(sender: &signer, rewards_controller: address,) { - let state_object_constructor_ref = &object::create_named_object(sender, - EMISSION_MANAGER_NAME); + let state_object_constructor_ref = + &object::create_named_object(sender, EMISSION_MANAGER_NAME); let state_object_signer = &object::generate_signer(state_object_constructor_ref); - move_to(state_object_signer, + move_to( + state_object_signer, EmissionManagerData { emission_admins: smart_table::new(), transfer_ref: object::generate_transfer_ref(state_object_constructor_ref), extend_ref: object::generate_extend_ref(state_object_constructor_ref), rewards_controller, - }); + }, + ); } #[view] @@ -77,43 +79,63 @@ module aave_pool::emission_manager { for (i in 0..vector::length(&config)) { let reward = get_reward(vector::borrow(&config, i)); - assert!(*smart_table::borrow(&emission_manager_data.emission_admins, reward) - == signer::address_of(account), - ONLY_EMISSION_ADMIN); + assert!( + *smart_table::borrow(&emission_manager_data.emission_admins, reward) + == signer::address_of(account), + ONLY_EMISSION_ADMIN, + ); }; - rewards_controller::configure_assets(account, config, emission_manager_data.rewards_controller); + rewards_controller::configure_assets( + account, config, emission_manager_data.rewards_controller + ); } public fun set_pull_rewards_transfer_strategy( - caller: &signer, reward: address, pull_rewards_transfer_strategy: PullRewardsTransferStrategy, + caller: &signer, + reward: address, + pull_rewards_transfer_strategy: PullRewardsTransferStrategy, ) acquires EmissionManagerData { check_is_emission_admin(reward); let emission_manager_data = borrow_global_mut(emission_manager_address()); - rewards_controller::set_pull_rewards_transfer_strategy(caller, reward, - pull_rewards_transfer_strategy, emission_manager_data.rewards_controller); + rewards_controller::set_pull_rewards_transfer_strategy( + caller, + reward, + pull_rewards_transfer_strategy, + emission_manager_data.rewards_controller, + ); } public fun set_staked_token_transfer_strategy( - caller: &signer, reward: address, staked_token_transfer_strategy: StakedTokenTransferStrategy, + caller: &signer, + reward: address, + staked_token_transfer_strategy: StakedTokenTransferStrategy, ) acquires EmissionManagerData { check_is_emission_admin(reward); let emission_manager_data = borrow_global_mut(emission_manager_address()); - rewards_controller::set_staked_token_transfer_strategy(caller, reward, - staked_token_transfer_strategy, emission_manager_data.rewards_controller); + rewards_controller::set_staked_token_transfer_strategy( + caller, + reward, + staked_token_transfer_strategy, + emission_manager_data.rewards_controller, + ); } public fun set_reward_oracle( caller: &signer, reward: address, reward_oracle: RewardOracle ) acquires EmissionManagerData { check_is_emission_admin(reward); - let emission_manager_data = borrow_global( - emission_manager_address()); - rewards_controller::set_reward_oracle(caller, reward, reward_oracle, - emission_manager_data.rewards_controller); + let emission_manager_data = + borrow_global(emission_manager_address()); + rewards_controller::set_reward_oracle( + caller, + reward, + reward_oracle, + emission_manager_data.rewards_controller, + ); } public fun set_distribution_end( @@ -121,13 +143,15 @@ module aave_pool::emission_manager { ) acquires EmissionManagerData { check_is_emission_admin(reward); - let emission_manager_data = borrow_global( - emission_manager_address()); - rewards_controller::set_distribution_end(caller, + let emission_manager_data = + borrow_global(emission_manager_address()); + rewards_controller::set_distribution_end( + caller, asset, reward, new_distribution_end, - emission_manager_data.rewards_controller); + emission_manager_data.rewards_controller, + ); } public fun set_emission_per_second( @@ -139,23 +163,32 @@ module aave_pool::emission_manager { let emission_manager_data = borrow_global_mut(emission_manager_address()); for (i in 0..vector::length(&rewards)) { - assert!(*smart_table::borrow(&emission_manager_data.emission_admins, *vector::borrow( - &rewards, i)) - == signer::address_of(caller), - ONLY_EMISSION_ADMIN); + assert!( + *smart_table::borrow( + &emission_manager_data.emission_admins, + *vector::borrow(&rewards, i), + ) == signer::address_of(caller), + ONLY_EMISSION_ADMIN, + ); }; - rewards_controller::set_emission_per_second(caller, + rewards_controller::set_emission_per_second( + caller, asset, rewards, new_emissions_per_second, - emission_manager_data.rewards_controller); + emission_manager_data.rewards_controller, + ); } - public fun set_claimer(account: &signer, user: address, claimer: address) acquires EmissionManagerData { + public fun set_claimer( + account: &signer, user: address, claimer: address + ) acquires EmissionManagerData { check_admin(signer::address_of(account)); - let emission_manager_data = borrow_global( - emission_manager_address()); - rewards_controller::set_claimer(user, claimer, emission_manager_data.rewards_controller); + let emission_manager_data = + borrow_global(emission_manager_address()); + rewards_controller::set_claimer( + user, claimer, emission_manager_data.rewards_controller + ); } public fun set_emission_admin( @@ -172,7 +205,9 @@ module aave_pool::emission_manager { event::emit(EmissionAdminUpdated { reward, old_admin, new_admin }); } - public fun set_rewards_controller(account: &signer, controller: address) acquires EmissionManagerData { + public fun set_rewards_controller( + account: &signer, controller: address + ) acquires EmissionManagerData { check_admin(signer::address_of(account)); let emission_manager_data = borrow_global_mut(emission_manager_address()); @@ -180,14 +215,14 @@ module aave_pool::emission_manager { } public fun get_rewards_controller(): address acquires EmissionManagerData { - let emission_manager_data = borrow_global( - emission_manager_address()); + let emission_manager_data = + borrow_global(emission_manager_address()); emission_manager_data.rewards_controller } public fun get_emission_admin(reward: address): address acquires EmissionManagerData { - let emission_manager_data = borrow_global( - emission_manager_address()); + let emission_manager_data = + borrow_global(emission_manager_address()); let emission_admin = smart_table::borrow(&emission_manager_data.emission_admins, reward); *emission_admin diff --git a/aave-core/sources/aave-periphery/package-manager.move b/aave-core/sources/aave-periphery/package-manager.move index 799dbcf..72f6383 100644 --- a/aave-core/sources/aave-periphery/package-manager.move +++ b/aave-core/sources/aave-periphery/package-manager.move @@ -19,8 +19,14 @@ module aave_pool::package_manager { fun initialize(sender: &signer) { let signer_cap = resource_account::retrieve_resource_account_cap(sender, @deployer_pm); - move_to(sender, - PermissionConfig { addresses: smart_table::new(), signer_cap, }); + initialize_helper(sender, signer_cap); + } + + fun initialize_helper(sender: &signer, signer_cap: SignerCapability) { + move_to( + sender, + PermissionConfig { addresses: smart_table::new(), signer_cap, }, + ); } /// Can be called by friended modules to obtain the resource account signer. @@ -67,15 +73,12 @@ module aave_pool::package_manager { public fun initialize_for_test(deployer: &signer) { let deployer_addr = std::signer::address_of(deployer); if (!exists(deployer_addr)) { - aptos_framework::timestamp::set_time_has_started_for_testing(&account::create_signer_for_test( - @0x1)); + aptos_framework::timestamp::set_time_has_started_for_testing( + &account::create_signer_for_test(@0x1) + ); account::create_account_for_test(deployer_addr); - move_to(deployer, - PermissionConfig { - addresses: smart_table::new(), - signer_cap: account::create_test_signer_cap(deployer_addr), - }); + initialize_helper(deployer, account::create_test_signer_cap(deployer_addr)); }; } } diff --git a/aave-core/sources/aave-periphery/rewards_controller.move b/aave-core/sources/aave-periphery/rewards_controller.move index d0373d0..93887cc 100644 --- a/aave-core/sources/aave-periphery/rewards_controller.move +++ b/aave-core/sources/aave-periphery/rewards_controller.move @@ -1,42 +1,44 @@ module aave_pool::rewards_controller { - use aptos_framework::object::{Self, Object, ObjectGroup}; - use aptos_std::smart_table::{Self, SmartTable}; use std::signer; - use std::vector; use std::simple_map::{Self, SimpleMap}; + use std::vector; + use aptos_std::smart_table::{Self, SmartTable}; use aptos_framework::event; - use aave_pool::transfer_strategy::check_is_emission_admin; - use aave_pool::a_token_factory; + use aptos_framework::object::{Self, Object, ObjectGroup}; use aptos_framework::timestamp; + + use aave_acl::acl_manage::Self; use aave_math::math_utils; use aave_mock_oracle::oracle::{Self, RewardOracle}; + + use aave_pool::a_token_factory; + use aave_pool::transfer_strategy::check_is_emission_admin; use aave_pool::transfer_strategy::{ - PullRewardsTransferStrategy, - StakedTokenTransferStrategy, - RewardsConfigInput, - validate_rewards_config_input, - has_pull_rewards_transfer_strategy, - pull_rewards_transfer_strategy_get_strategy, - staked_token_transfer_strategy_get_strategy, - set_total_supply, get_asset, + get_emission_per_second, get_reward, get_total_supply, - get_emission_per_second + has_pull_rewards_transfer_strategy, + pull_rewards_transfer_strategy_get_strategy, + PullRewardsTransferStrategy, + RewardsConfigInput, + set_total_supply, + staked_token_transfer_strategy_get_strategy, + StakedTokenTransferStrategy, + validate_rewards_config_input }; - use aave_acl::acl_manage::Self; const REVISION: u64 = 1; const CLAIMER_UNAUTHORIZED: u64 = 1; - const INDEX_OVERFLOW: u64 = 1; - const ONLY_EMISSION_MANAGER: u64 = 1; - const INVALID_INPUT: u64 = 1; - const DISTRIBUTION_DOES_NOT_EXIST: u64 = 1; - const ORACLE_MUST_RETURN_PRICE: u64 = 1; - const TRANSFER_ERROR: u64 = 1; + const INDEX_OVERFLOW: u64 = 2; + const ONLY_EMISSION_MANAGER: u64 = 3; + const INVALID_INPUT: u64 = 4; + const DISTRIBUTION_DOES_NOT_EXIST: u64 = 5; + const ORACLE_MUST_RETURN_PRICE: u64 = 6; + const TRANSFER_ERROR: u64 = 7; - const NOT_REWARDS_CONTROLLER_ADMIN: u64 = 1; + const NOT_REWARDS_CONTROLLER_ADMIN: u64 = 8; const REWARDS_CONTROLLER_NAME: vector = b"REWARDS_CONTROLLER_NAME"; @@ -54,16 +56,19 @@ module aave_pool::rewards_controller { } fun assert_access(account: address) { - assert!(acl_manage::is_rewards_controller_admin_role(account), - NOT_REWARDS_CONTROLLER_ADMIN); + assert!( + acl_manage::is_rewards_controller_admin_role(account), + NOT_REWARDS_CONTROLLER_ADMIN, + ); } public fun initialize(sender: &signer, emission_manager: address,) { - let state_object_constructor_ref = &object::create_named_object(sender, - REWARDS_CONTROLLER_NAME); + let state_object_constructor_ref = + &object::create_named_object(sender, REWARDS_CONTROLLER_NAME); let state_object_signer = &object::generate_signer(state_object_constructor_ref); - move_to(state_object_signer, + move_to( + state_object_signer, RewardsControllerData { authorized_claimers: smart_table::new(), pull_rewards_transfer_strategy_table: smart_table::new(), @@ -74,7 +79,8 @@ module aave_pool::rewards_controller { is_reward_enabled: smart_table::new(), rewards_list: vector[], assets_list: vector[], - }); + }, + ); } struct AssetData has key, store, drop { @@ -179,14 +185,17 @@ module aave_pool::rewards_controller { fun only_authorized_claimers( claimer: address, user: address, rewards_controller_address: address ) acquires RewardsControllerData { - assert!(get_claimer(user, rewards_controller_address) == claimer, - CLAIMER_UNAUTHORIZED); + assert!( + get_claimer(user, rewards_controller_address) == claimer, CLAIMER_UNAUTHORIZED + ); } #[view] - public fun get_claimer(user: address, rewards_controller_address: address): address acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + public fun get_claimer( + user: address, rewards_controller_address: address + ): address acquires RewardsControllerData { + let rewards_controller_data = + borrow_global(rewards_controller_address); let claimer = smart_table::borrow(&rewards_controller_data.authorized_claimers, user); *claimer @@ -201,31 +210,35 @@ module aave_pool::rewards_controller { public fun get_reward_oracle( reward: address, rewards_controller_address: address ): RewardOracle acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); *smart_table::borrow(&rewards_controller_data.reward_oracle, reward) } public fun get_pull_rewards_transfer_strategy( reward: address, rewards_controller_address: address ): PullRewardsTransferStrategy acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); - *smart_table::borrow(&rewards_controller_data.pull_rewards_transfer_strategy_table, - reward) + let rewards_controller_data = + borrow_global(rewards_controller_address); + *smart_table::borrow( + &rewards_controller_data.pull_rewards_transfer_strategy_table, reward + ) } public fun get_staked_token_transfer_strategy( reward: address, rewards_controller_address: address ): StakedTokenTransferStrategy acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); - *smart_table::borrow(&rewards_controller_data.staked_token_transfer_strategy_table, - reward) + let rewards_controller_data = + borrow_global(rewards_controller_address); + *smart_table::borrow( + &rewards_controller_data.staked_token_transfer_strategy_table, reward + ) } public fun configure_assets( - caller: &signer, config: vector, rewards_controller_address: address + caller: &signer, + config: vector, + rewards_controller_address: address ) acquires RewardsControllerData { only_emission_manager(caller, rewards_controller_address); for (i in 0..vector::length(&config)) { @@ -234,24 +247,32 @@ module aave_pool::rewards_controller { validate_rewards_config_input(config_el); let asset = get_asset(config_el); - set_total_supply(config_el, a_token_factory::scale_total_supply(asset)); + set_total_supply(config_el, a_token_factory::scaled_total_supply(asset)); let reward = aave_pool::transfer_strategy::get_reward(config_el); if (has_pull_rewards_transfer_strategy(config_el)) { - install_pull_rewards_transfer_strategy(reward, + install_pull_rewards_transfer_strategy( + reward, pull_rewards_transfer_strategy_get_strategy(config_el), - rewards_controller_address); + rewards_controller_address, + ); } else { - install_staked_token_transfer_strategy(reward, + install_staked_token_transfer_strategy( + reward, staked_token_transfer_strategy_get_strategy(config_el), - rewards_controller_address); + rewards_controller_address, + ); }; - set_reward_oracle(caller, + set_reward_oracle( + caller, reward, - aave_pool::transfer_strategy::get_reward_oracle(vector::borrow(&config, i)), - rewards_controller_address); + aave_pool::transfer_strategy::get_reward_oracle( + vector::borrow(&config, i) + ), + rewards_controller_address, + ); }; configure_assets_internal(config, rewards_controller_address); } @@ -263,8 +284,9 @@ module aave_pool::rewards_controller { rewards_controller_address: address ) acquires RewardsControllerData { only_emission_manager(caller, rewards_controller_address); - install_pull_rewards_transfer_strategy(reward, pull_rewards_transfer_strategy, - rewards_controller_address); + install_pull_rewards_transfer_strategy( + reward, pull_rewards_transfer_strategy, rewards_controller_address + ); } public fun set_staked_token_transfer_strategy( @@ -274,8 +296,9 @@ module aave_pool::rewards_controller { rewards_controller_address: address ) acquires RewardsControllerData { only_emission_manager(caller, rewards_controller_address); - install_staked_token_transfer_strategy(reward, staked_token_transfer_strategy, - rewards_controller_address); + install_staked_token_transfer_strategy( + reward, staked_token_transfer_strategy, rewards_controller_address + ); } public fun set_reward_oracle( @@ -309,8 +332,16 @@ module aave_pool::rewards_controller { rewards_controller_address: address ): u256 acquires RewardsControllerData { let addr = signer::address_of(caller); - claim_rewards_internal(caller, assets, amount, addr, addr, to, reward, - rewards_controller_address) + claim_rewards_internal( + caller, + assets, + amount, + addr, + addr, + to, + reward, + rewards_controller_address, + ) } fun claim_rewards_on_behalf( @@ -325,8 +356,16 @@ module aave_pool::rewards_controller { let addr = signer::address_of(caller); only_authorized_claimers(addr, user, rewards_controller_address); - claim_rewards_internal(caller, assets, amount, addr, user, to, reward, - rewards_controller_address) + claim_rewards_internal( + caller, + assets, + amount, + addr, + user, + to, + reward, + rewards_controller_address, + ) } fun claim_rewards_to_self( @@ -337,22 +376,33 @@ module aave_pool::rewards_controller { rewards_controller_address: address ): u256 acquires RewardsControllerData { let addr = signer::address_of(caller); - claim_rewards_internal(caller, + claim_rewards_internal( + caller, assets, amount, addr, addr, addr, reward, - rewards_controller_address) + rewards_controller_address, + ) } public fun claim_all_rewards( - caller: &signer, assets: vector
, to: address, rewards_controller_address: address + caller: &signer, + assets: vector
, + to: address, + rewards_controller_address: address ): (vector
, vector) acquires RewardsControllerData { let addr = signer::address_of(caller); - claim_all_rewards_internal(caller, assets, addr, addr, to, - rewards_controller_address) + claim_all_rewards_internal( + caller, + assets, + addr, + addr, + to, + rewards_controller_address, + ) } fun claim_all_rewards_on_behalf( @@ -365,16 +415,28 @@ module aave_pool::rewards_controller { let addr = signer::address_of(caller); only_authorized_claimers(addr, user, rewards_controller_address); - claim_all_rewards_internal(caller, assets, addr, user, to, - rewards_controller_address) + claim_all_rewards_internal( + caller, + assets, + addr, + user, + to, + rewards_controller_address, + ) } fun claim_all_rewards_to_self( caller: &signer, assets: vector
, rewards_controller_address: address ): (vector
, vector) acquires RewardsControllerData { let addr = signer::address_of(caller); - claim_all_rewards_internal(caller, assets, addr, addr, addr, - rewards_controller_address) + claim_all_rewards_internal( + caller, + assets, + addr, + addr, + addr, + rewards_controller_address, + ) } public fun set_claimer( @@ -384,7 +446,9 @@ module aave_pool::rewards_controller { let rewards_controller_data = borrow_global_mut(rewards_controller_address); - smart_table::upsert(&mut rewards_controller_data.authorized_claimers, user, claimer); + smart_table::upsert( + &mut rewards_controller_data.authorized_claimers, user, claimer + ); event::emit(ClaimerSet { user, claimer }); } @@ -393,14 +457,13 @@ module aave_pool::rewards_controller { let user_asset_balances = vector[]; for (i in 0..vector::length(&assets)) { let asset = *vector::borrow(&assets, i); - let user_balance = a_token_factory::scale_balance_of(user, asset); - let total_supply = a_token_factory::scale_total_supply(asset); + let user_balance = a_token_factory::scaled_balance_of(user, asset); + let total_supply = a_token_factory::scaled_total_supply(asset); - vector::push_back(&mut user_asset_balances, UserAssetBalance { - asset, - user_balance, - total_supply - }); + vector::push_back( + &mut user_asset_balances, + UserAssetBalance { asset, user_balance, total_supply }, + ); }; user_asset_balances } @@ -420,8 +483,11 @@ module aave_pool::rewards_controller { }; let total_rewards = 0; - update_data_multiple(user, get_user_asset_balances(assets, user), - rewards_controller_address); + update_data_multiple( + user, + get_user_asset_balances(assets, user), + rewards_controller_address, + ); let rewards_controller_data = borrow_global_mut(rewards_controller_address); @@ -431,8 +497,10 @@ module aave_pool::rewards_controller { let asset_el = smart_table::borrow_mut(&mut rewards_controller_data.assets, asset); - let reward_data: &mut RewardData = simple_map::borrow_mut(&mut asset_el.rewards, &reward); - let user_data: &mut UserData = simple_map::borrow_mut(&mut reward_data.users_data, &user); + let reward_data: &mut RewardData = + simple_map::borrow_mut(&mut asset_el.rewards, &reward); + let user_data: &mut UserData = + simple_map::borrow_mut(&mut reward_data.users_data, &user); total_rewards = total_rewards + (user_data.accrued as u256); if (total_rewards <= amount) { @@ -449,16 +517,30 @@ module aave_pool::rewards_controller { return 0 }; - if (smart_table::contains(&rewards_controller_data.pull_rewards_transfer_strategy_table, - reward)) { - transfer_pull_rewards_transfer_strategy_rewards(caller, to, reward, - total_rewards, rewards_controller_data) - } else if (smart_table::contains(&rewards_controller_data.pull_rewards_transfer_strategy_table, - reward)) { - transfer_staked_token_transfer_strategy_rewards(caller, to, reward, - total_rewards, rewards_controller_data) + if (smart_table::contains( + &rewards_controller_data.pull_rewards_transfer_strategy_table, reward + )) { + transfer_pull_rewards_transfer_strategy_rewards( + caller, + to, + reward, + total_rewards, + rewards_controller_data, + ) + } else if (smart_table::contains( + &rewards_controller_data.pull_rewards_transfer_strategy_table, reward + )) { + transfer_staked_token_transfer_strategy_rewards( + caller, + to, + reward, + total_rewards, + rewards_controller_data, + ) }; - event::emit(RewardsClaimed { user, reward: claimer, to, claimer, amount: total_rewards }); + event::emit( + RewardsClaimed { user, reward: claimer, to, claimer, amount: total_rewards }, + ); total_rewards } @@ -474,8 +556,11 @@ module aave_pool::rewards_controller { let rewards_list = vector[]; let claimed_amounts = vector[]; - update_data_multiple(user, get_user_asset_balances(assets, user), - rewards_controller_address); + update_data_multiple( + user, + get_user_asset_balances(assets, user), + rewards_controller_address, + ); let rewards_controller_data = borrow_global_mut(rewards_controller_address); @@ -488,42 +573,56 @@ module aave_pool::rewards_controller { for (j in 0..rewards_list_length) { let reward_data: &mut RewardData = - simple_map::borrow_mut(&mut asset_el.rewards, - vector::borrow(&rewards_list, j)); - let user_data: &mut UserData = simple_map::borrow_mut(&mut reward_data.users_data, &user); + simple_map::borrow_mut( + &mut asset_el.rewards, vector::borrow(&rewards_list, j) + ); + let user_data: &mut UserData = + simple_map::borrow_mut(&mut reward_data.users_data, &user); let reward_amount = (user_data.accrued as u256); if (reward_amount != 0) { let claimed_amounts_j = *vector::borrow_mut(&mut claimed_amounts, j); - vector::insert(&mut claimed_amounts, j, claimed_amounts_j + reward_amount); + vector::insert( + &mut claimed_amounts, j, claimed_amounts_j + reward_amount + ); user_data.accrued = 0; }; }; }; for (i in 0..rewards_list_length) { - if (smart_table::contains(&rewards_controller_data.pull_rewards_transfer_strategy_table, - *vector::borrow(&rewards_list, i))) { - transfer_pull_rewards_transfer_strategy_rewards(caller, + if (smart_table::contains( + &rewards_controller_data.pull_rewards_transfer_strategy_table, + *vector::borrow(&rewards_list, i), + )) { + transfer_pull_rewards_transfer_strategy_rewards( + caller, to, *vector::borrow(&rewards_list, i), *vector::borrow(&claimed_amounts, i), - rewards_controller_data) - } else if (smart_table::contains(&rewards_controller_data.pull_rewards_transfer_strategy_table, - *vector::borrow(&rewards_list, i))) { - transfer_staked_token_transfer_strategy_rewards(caller, + rewards_controller_data, + ) + } else if (smart_table::contains( + &rewards_controller_data.pull_rewards_transfer_strategy_table, + *vector::borrow(&rewards_list, i), + )) { + transfer_staked_token_transfer_strategy_rewards( + caller, to, *vector::borrow(&rewards_list, i), *vector::borrow(&claimed_amounts, i), - rewards_controller_data) + rewards_controller_data, + ) }; - event::emit(RewardsClaimed { + event::emit( + RewardsClaimed { user, reward: *vector::borrow(&rewards_list, i), to, claimer, amount: *vector::borrow(&claimed_amounts, i) - }); + }, + ); }; (rewards_list, claimed_amounts) } @@ -536,11 +635,17 @@ module aave_pool::rewards_controller { rewards_controller_data: &mut RewardsControllerData ) { let pull_rewards_transfer_strategy = - *smart_table::borrow(&rewards_controller_data.pull_rewards_transfer_strategy_table, - reward); + *smart_table::borrow( + &rewards_controller_data.pull_rewards_transfer_strategy_table, reward + ); let success = - aave_pool::transfer_strategy::pull_rewards_transfer_strategy_perform_transfer(caller, to, - reward, amount, pull_rewards_transfer_strategy); + aave_pool::transfer_strategy::pull_rewards_transfer_strategy_perform_transfer( + caller, + to, + reward, + amount, + pull_rewards_transfer_strategy, + ); assert!(success, TRANSFER_ERROR); } @@ -553,11 +658,17 @@ module aave_pool::rewards_controller { rewards_controller_data: &mut RewardsControllerData ) { let staked_token_transfer_strategy = - *smart_table::borrow(&rewards_controller_data.staked_token_transfer_strategy_table, - reward); + *smart_table::borrow( + &rewards_controller_data.staked_token_transfer_strategy_table, reward + ); let success = - aave_pool::transfer_strategy::staked_token_transfer_strategy_perform_transfer(caller, to, - reward, amount, staked_token_transfer_strategy); + aave_pool::transfer_strategy::staked_token_transfer_strategy_perform_transfer( + caller, + to, + reward, + amount, + staked_token_transfer_strategy, + ); assert!(success, TRANSFER_ERROR); } @@ -569,14 +680,15 @@ module aave_pool::rewards_controller { ) acquires RewardsControllerData { let rewards_controller_data = borrow_global_mut(rewards_controller_address); - smart_table::upsert(&mut rewards_controller_data.pull_rewards_transfer_strategy_table, + smart_table::upsert( + &mut rewards_controller_data.pull_rewards_transfer_strategy_table, reward, - pull_rewards_transfer_strategy); + pull_rewards_transfer_strategy, + ); - event::emit(PullRewardsTransferStrategyInstalled { - reward, - pull_rewards_transfer_strategy - }); + event::emit( + PullRewardsTransferStrategyInstalled { reward, pull_rewards_transfer_strategy }, + ); } fun install_staked_token_transfer_strategy( @@ -586,14 +698,15 @@ module aave_pool::rewards_controller { ) acquires RewardsControllerData { let rewards_controller_data = borrow_global_mut(rewards_controller_address); - smart_table::upsert(&mut rewards_controller_data.staked_token_transfer_strategy_table, + smart_table::upsert( + &mut rewards_controller_data.staked_token_transfer_strategy_table, reward, - staked_token_transfer_strategy); + staked_token_transfer_strategy, + ); - event::emit(StakedTokenTransferStrategyInstalled { - reward, - staked_token_transfer_strategy - }); + event::emit( + StakedTokenTransferStrategyInstalled { reward, staked_token_transfer_strategy }, + ); } public fun set_reward_oracle_internal( @@ -603,8 +716,9 @@ module aave_pool::rewards_controller { let rewards_controller_data = borrow_global_mut(rewards_controller_address()); - smart_table::upsert(&mut rewards_controller_data.reward_oracle, reward, - reward_oracle); + smart_table::upsert( + &mut rewards_controller_data.reward_oracle, reward, reward_oracle + ); event::emit(RewardOracleUpdated { reward, reward_oracle }); } @@ -612,22 +726,24 @@ module aave_pool::rewards_controller { fun only_emission_manager( sender: &signer, rewards_controller_address: address ) acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); - assert!(signer::address_of(sender) - == rewards_controller_data.emission_manager, - ONLY_EMISSION_MANAGER); + let rewards_controller_data = + borrow_global(rewards_controller_address); + assert!( + signer::address_of(sender) == rewards_controller_data.emission_manager, + ONLY_EMISSION_MANAGER, + ); } #[view] public fun get_rewards_data( asset: address, reward: address, rewards_controller_address: address ): (u256, u256, u256, u256) acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); let asset = smart_table::borrow(&rewards_controller_data.assets, asset); let rewards_data: &RewardData = simple_map::borrow(&asset.rewards, &reward); - ((rewards_data.index as u256), + ( + (rewards_data.index as u256), (rewards_data.emission_per_second as u256), (rewards_data.last_update_timestamp as u256), (rewards_data.distribution_end as u256), @@ -638,20 +754,23 @@ module aave_pool::rewards_controller { public fun get_asset_index( asset: address, reward: address, rewards_controller_address: address ): (u256, u256) acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); let asset_el = smart_table::borrow(&rewards_controller_data.assets, asset); let rewards_data: &RewardData = simple_map::borrow(&asset_el.rewards, &reward); - get_asset_index_internal(rewards_data, a_token_factory::scale_total_supply(asset), - math_utils::pow(10, (asset_el.decimals as u256))) + get_asset_index_internal( + rewards_data, + a_token_factory::scaled_total_supply(asset), + math_utils::pow(10, (asset_el.decimals as u256)), + ) } #[view] public fun get_distribution_end( asset: address, reward: address, rewards_controller_address: address ): u256 acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); let asset = smart_table::borrow(&rewards_controller_data.assets, asset); let reward_data: &RewardData = simple_map::borrow(&asset.rewards, &reward); (reward_data.distribution_end as u256) @@ -661,8 +780,8 @@ module aave_pool::rewards_controller { public fun get_rewards_by_asset( asset: address, rewards_controller_address: address ): vector
acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); let asset = smart_table::borrow(&rewards_controller_data.assets, asset); let rewards_count = asset.available_rewards_count; @@ -677,8 +796,8 @@ module aave_pool::rewards_controller { #[view] public fun get_rewards_list(rewards_controller_address: address): vector
acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); rewards_controller_data.rewards_list } @@ -686,8 +805,8 @@ module aave_pool::rewards_controller { public fun get_user_asset_index( user: address, asset: address, reward: address, rewards_controller_address: address ): u256 acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); let asset = smart_table::borrow(&rewards_controller_data.assets, asset); let reward_data: &RewardData = simple_map::borrow(&asset.rewards, &reward); let user_data: &UserData = simple_map::borrow(&reward_data.users_data, &user); @@ -700,14 +819,17 @@ module aave_pool::rewards_controller { ): u256 acquires RewardsControllerData { let total_accrued = 0; - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); let assets_list = rewards_controller_data.assets_list; for (i in 0..vector::length(&assets_list)) { let asset = - smart_table::borrow(&rewards_controller_data.assets, *vector::borrow(&assets_list, i)); + smart_table::borrow( + &rewards_controller_data.assets, + *vector::borrow(&assets_list, i), + ); let reward_data: &RewardData = simple_map::borrow(&asset.rewards, &reward); let user_data: &UserData = simple_map::borrow(&reward_data.users_data, &user); @@ -719,12 +841,17 @@ module aave_pool::rewards_controller { #[view] public fun get_user_rewards( - assets: vector
, user: address, reward: address, rewards_controller_address: address + assets: vector
, + user: address, + reward: address, + rewards_controller_address: address ): u256 acquires RewardsControllerData { - get_user_reward(user, + get_user_reward( + user, reward, get_user_asset_balances(assets, user), - rewards_controller_address) + rewards_controller_address, + ) } #[view] @@ -735,29 +862,42 @@ module aave_pool::rewards_controller { let rewards_list = vector[]; let unclaimed_amounts = vector[]; - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); let rewards_list_len = vector::length(&rewards_controller_data.rewards_list); for (i in 0..rewards_list_len) { for (r in 0..rewards_list_len) { - vector::push_back(&mut rewards_list, *vector::borrow(&rewards_controller_data - .rewards_list, r)); + vector::push_back( + &mut rewards_list, + *vector::borrow(&rewards_controller_data.rewards_list, r), + ); let asset_el = - smart_table::borrow(&rewards_controller_data.assets, - vector::borrow(&user_asset_balances, r).asset); + smart_table::borrow( + &rewards_controller_data.assets, + vector::borrow(&user_asset_balances, r).asset, + ); let rewards_el = - simple_map::borrow(&asset_el.rewards, vector::borrow(&rewards_list, r)); + simple_map::borrow( + &asset_el.rewards, vector::borrow(&rewards_list, r) + ); let user_data = simple_map::borrow(&rewards_el.users_data, &user); vector::push_back(&mut unclaimed_amounts, (user_data.accrued as u256)); - if (vector::borrow(&user_asset_balances, i).user_balance == 0) { continue }; + if (vector::borrow(&user_asset_balances, i).user_balance == 0) { + continue + }; let prev = vector::pop_back(&mut unclaimed_amounts); - vector::push_back(&mut unclaimed_amounts, - prev + get_pending_rewards(user, - *vector::borrow(&rewards_list, r), - vector::borrow(&user_asset_balances, i), - rewards_controller_data)); + vector::push_back( + &mut unclaimed_amounts, + prev + + get_pending_rewards( + user, + *vector::borrow(&rewards_list, r), + vector::borrow(&user_asset_balances, i), + rewards_controller_data, + ), + ); }; }; (rewards_list, unclaimed_amounts) @@ -776,12 +916,14 @@ module aave_pool::rewards_controller { borrow_global_mut(rewards_controller_address); let asset_el: &mut AssetData = smart_table::borrow_mut(&mut rewards_controller_data.assets, asset); - let reward_data: &mut RewardData = simple_map::borrow_mut(&mut asset_el.rewards, &reward); + let reward_data: &mut RewardData = + simple_map::borrow_mut(&mut asset_el.rewards, &reward); let old_distribution_end = (reward_data.distribution_end as u256); reward_data.distribution_end = new_distribution_end; - event::emit(AssetConfigUpdated { + event::emit( + AssetConfigUpdated { asset, reward, old_emission: (reward_data.emission_per_second as u256), @@ -789,7 +931,8 @@ module aave_pool::rewards_controller { old_distribution_end, new_distribution_end: (new_distribution_end as u256), asset_index: (reward_data.index as u256) - }); + }, + ); } public fun set_emission_per_second( @@ -812,21 +955,30 @@ module aave_pool::rewards_controller { let asset_config: &mut AssetData = smart_table::borrow_mut(&mut rewards_controller_data.assets, asset); let reward_config: &mut RewardData = - simple_map::borrow_mut(&mut asset_config.rewards, - vector::borrow(&rewards, i)); + simple_map::borrow_mut( + &mut asset_config.rewards, vector::borrow(&rewards, i) + ); let decimals = asset_config.decimals; - assert!(decimals != 0 && reward_config.last_update_timestamp != 0, - DISTRIBUTION_DOES_NOT_EXIST); + assert!( + decimals != 0 && reward_config.last_update_timestamp != 0, + DISTRIBUTION_DOES_NOT_EXIST, + ); let (new_index, _) = - update_reward_data(reward_config, a_token_factory::scale_total_supply(asset), - math_utils::pow(10, (decimals as u256))); + update_reward_data( + reward_config, + a_token_factory::scaled_total_supply(asset), + math_utils::pow(10, (decimals as u256)), + ); let old_emission_per_second = (reward_config.emission_per_second as u256); - reward_config.emission_per_second = *vector::borrow(&new_emissions_per_second, i); + reward_config.emission_per_second = *vector::borrow( + &new_emissions_per_second, i + ); - event::emit(AssetConfigUpdated { + event::emit( + AssetConfigUpdated { asset, reward: *vector::borrow(&rewards, i), old_emission: old_emission_per_second, @@ -834,7 +986,8 @@ module aave_pool::rewards_controller { old_distribution_end: (reward_config.distribution_end as u256), new_distribution_end: (reward_config.distribution_end as u256), asset_index: new_index - }); + }, + ); } } @@ -868,8 +1021,9 @@ module aave_pool::rewards_controller { }; let is_reward_enabled_reward = - *smart_table::borrow_mut(&mut rewards_controller_data.is_reward_enabled, - reward); + *smart_table::borrow_mut( + &mut rewards_controller_data.is_reward_enabled, reward + ); if (is_reward_enabled_reward == false) { //is_reward_enabled_reward = true; vector::push_back(&mut rewards_controller_data.rewards_list, reward); @@ -878,16 +1032,21 @@ module aave_pool::rewards_controller { let total_supply = get_total_supply(reward_input); let (new_index, _) = - update_reward_data(reward_config, total_supply, - math_utils::pow(10, (decimals as u256))); + update_reward_data( + reward_config, + total_supply, + math_utils::pow(10, (decimals as u256)), + ); let old_emissions_per_second = reward_config.emission_per_second; let old_distribution_end = reward_config.distribution_end; reward_config.emission_per_second = get_emission_per_second(reward_input); reward_config.distribution_end = aave_pool::transfer_strategy::get_distribution_end( - reward_input); + reward_input + ); - event::emit(AssetConfigUpdated { + event::emit( + AssetConfigUpdated { asset, reward, old_emission: (old_emissions_per_second as u256), @@ -895,15 +1054,16 @@ module aave_pool::rewards_controller { old_distribution_end: (old_distribution_end as u256), new_distribution_end: (reward_config.distribution_end as u256), asset_index: new_index - }); + }, + ); } } fun update_reward_data( reward_data: &mut RewardData, total_supply: u256, asset_unit: u256 ): (u256, bool) { - let (old_index, new_index) = get_asset_index_internal(reward_data, total_supply, - asset_unit); + let (old_index, new_index) = + get_asset_index_internal(reward_data, total_supply, asset_unit); let index_updated = false; if (new_index != old_index) { assert!(new_index <= math_utils::pow(2, 104), INDEX_OVERFLOW); @@ -932,8 +1092,12 @@ module aave_pool::rewards_controller { if (data_updated) { user.index = (new_asset_index as u128); if (user_balance != 0) { - rewards_accrued = get_rewards(user_balance, new_asset_index, (user_index as u256), - asset_unit); + rewards_accrued = get_rewards( + user_balance, + new_asset_index, + (user_index as u256), + asset_unit, + ); user.accrued = user.accrued + (rewards_accrued as u128); }; @@ -950,8 +1114,7 @@ module aave_pool::rewards_controller { ) acquires RewardsControllerData { let rewards_controller_data = borrow_global_mut(rewards_controller_address); - let asset_el = - smart_table::borrow_mut(&mut rewards_controller_data.assets, asset); + let asset_el = smart_table::borrow_mut(&mut rewards_controller_data.assets, asset); let num_available_rewards = asset_el.available_rewards_count; let asset_unit = math_utils::pow(10, (asset_el.decimals as u256)); @@ -959,24 +1122,32 @@ module aave_pool::rewards_controller { for (r in 0..num_available_rewards) { let reward: address = *simple_map::borrow(&mut asset_el.available_rewards, &r); - let reward_data: &mut RewardData = simple_map::borrow_mut(&mut asset_el.rewards, &reward); + let reward_data: &mut RewardData = + simple_map::borrow_mut(&mut asset_el.rewards, &reward); let (new_asset_index, reward_data_updated) = update_reward_data(reward_data, total_supply, asset_unit); let (rewards_accrued, user_data_updated) = - update_user_data(reward_data, user, user_balance, new_asset_index, - asset_unit); + update_user_data( + reward_data, + user, + user_balance, + new_asset_index, + asset_unit, + ); if (reward_data_updated || user_data_updated) { - event::emit(Accrued { + event::emit( + Accrued { asset, reward, user, asset_index: new_asset_index, user_index: new_asset_index, rewards_accrued - }) + }, + ) }; }; } @@ -988,11 +1159,13 @@ module aave_pool::rewards_controller { ) acquires RewardsControllerData { for (i in 0..vector::length(&user_asset_balances)) { let user_asset_balances_i = vector::borrow(&user_asset_balances, i); - update_data(user_asset_balances_i.asset, + update_data( + user_asset_balances_i.asset, user, user_asset_balances_i.user_balance, user_asset_balances_i.total_supply, - rewards_controller_address); + rewards_controller_address, + ); }; } @@ -1002,15 +1175,16 @@ module aave_pool::rewards_controller { user_asset_balances: vector, rewards_controller_address: address ): u256 acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); let unclaimed_rewards = 0; for (i in 0..vector::length(&user_asset_balances)) { let user_asset_balances_i = vector::borrow(&user_asset_balances, i); let asset = - smart_table::borrow(&rewards_controller_data.assets, user_asset_balances_i - .asset); + smart_table::borrow( + &rewards_controller_data.assets, user_asset_balances_i.asset + ); let reward_data: &RewardData = simple_map::borrow(&asset.rewards, &reward); let user_data: &UserData = simple_map::borrow(&reward_data.users_data, &user); @@ -1018,9 +1192,14 @@ module aave_pool::rewards_controller { unclaimed_rewards = unclaimed_rewards + (user_data.accrued as u256); } else { let pending_rewards = - get_pending_rewards(user, reward, user_asset_balances_i, - rewards_controller_data); - unclaimed_rewards = unclaimed_rewards + pending_rewards + (user_data.accrued as u256); + get_pending_rewards( + user, + reward, + user_asset_balances_i, + rewards_controller_data, + ); + unclaimed_rewards = unclaimed_rewards + pending_rewards + + (user_data.accrued as u256); }; }; @@ -1034,16 +1213,21 @@ module aave_pool::rewards_controller { rewards_controller_data: &RewardsControllerData ): u256 { let asset: &AssetData = - smart_table::borrow(&rewards_controller_data.assets, user_asset_balance.asset); + smart_table::borrow( + &rewards_controller_data.assets, user_asset_balance.asset + ); let reward_data: &RewardData = simple_map::borrow(&asset.rewards, &reward); let user_asset = - smart_table::borrow(&rewards_controller_data.assets, user_asset_balance.asset); + smart_table::borrow( + &rewards_controller_data.assets, user_asset_balance.asset + ); let asset_unit = math_utils::pow(10, (user_asset.decimals as u256)); let (_, next_index) = - get_asset_index_internal(reward_data, user_asset_balance.total_supply, - asset_unit); + get_asset_index_internal( + reward_data, user_asset_balance.total_supply, asset_unit + ); let user_data: &UserData = simple_map::borrow(&reward_data.users_data, &user); let index = (user_data.index as u256); @@ -1070,7 +1254,7 @@ module aave_pool::rewards_controller { || total_supply == 0 || last_update_timestamp == (timestamp::now_seconds() as u256) || last_update_timestamp >= distribution_end) { - return(old_index, old_index) + return (old_index, old_index) }; let current_timestamp = (timestamp::now_seconds() as u256); @@ -1089,16 +1273,16 @@ module aave_pool::rewards_controller { public fun get_asset_decimals( asset: address, rewards_controller_address: address ): u8 acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); let asset = smart_table::borrow(&rewards_controller_data.assets, asset); asset.decimals } #[view] public fun get_emission_manager(rewards_controller_address: address): address acquires RewardsControllerData { - let rewards_controller_data = borrow_global( - rewards_controller_address); + let rewards_controller_data = + borrow_global(rewards_controller_address); rewards_controller_data.emission_manager } } diff --git a/aave-core/sources/aave-periphery/staked_token.move b/aave-core/sources/aave-periphery/staked_token.move index 64863cb..ca9ef1e 100644 --- a/aave-core/sources/aave-periphery/staked_token.move +++ b/aave-core/sources/aave-periphery/staked_token.move @@ -9,21 +9,13 @@ module aave_pool::staked_token { public fun stake( _mock_staked_token: &MockStakedToken, _to: address, _amount: u256 - ) { + ) {} - } - - fun redeem(_to: address, _amount: u256) { + fun redeem(_to: address, _amount: u256) {} - } + fun cooldown() {} - fun cooldown() { - - } - - fun claim_rewards(_to: address, _amount: u256) { - - } + fun claim_rewards(_to: address, _amount: u256) {} public fun create_mock_staked_token(addr: address): MockStakedToken { MockStakedToken { addr } @@ -40,4 +32,23 @@ module aave_pool::staked_token { assert!(mock_staked_token.addr == addr, 0); } + + #[test(account = @aave_pool)] + fun test_cooldown(account: &signer,) { + cooldown(); + } + + #[test(account = @aave_pool)] + fun test_redeem(account: &signer,) { + let to = signer::address_of(account); + let amount = 1; + redeem(to, amount); + } + + #[test(account = @aave_pool)] + fun test_claim_rewards(account: &signer,) { + let to = signer::address_of(account); + let amount = 1; + claim_rewards(to, amount); + } } diff --git a/aave-core/sources/aave-periphery/stream.move b/aave-core/sources/aave-periphery/stream.move index 205c3bf..5be1368 100644 --- a/aave-core/sources/aave-periphery/stream.move +++ b/aave-core/sources/aave-periphery/stream.move @@ -21,15 +21,19 @@ module aave_pool::stream { } public fun get_stream(stream: &Stream) - : (address, address, u256, address, u256, u256, u256, u256) { - (stream.sender, + : ( + address, address, u256, address, u256, u256, u256, u256 + ) { + ( + stream.sender, stream.recipient, stream.deposit, stream.token_address, stream.start_time, stream.stop_time, stream.remaining_balance, - stream.rate_per_second) + stream.rate_per_second + ) } public fun set_remaining_balance( @@ -81,7 +85,8 @@ module aave_pool::stream { let is_entity = true; let stream = - create_stream(deposit, + create_stream( + deposit, rate_per_second, remaining_balance, start_time, @@ -89,7 +94,8 @@ module aave_pool::stream { recipient, sender, token_address, - is_entity); + is_entity, + ); assert!(stream.deposit == deposit, TEST_SUCCESS); assert!(stream.rate_per_second == rate_per_second, TEST_SUCCESS); @@ -115,7 +121,8 @@ module aave_pool::stream { let _is_entity = true; let stream_true = - create_stream(deposit, + create_stream( + deposit, rate_per_second, remaining_balance, start_time, @@ -123,12 +130,14 @@ module aave_pool::stream { recipient, sender, token_address, - true); + true, + ); assert!(is_entity(&stream_true) == true, TEST_SUCCESS); let stream_false = - create_stream(deposit, + create_stream( + deposit, rate_per_second, remaining_balance, start_time, @@ -136,7 +145,8 @@ module aave_pool::stream { recipient, sender, token_address, - false); + false, + ); assert!(is_entity(&stream_false) == false, TEST_SUCCESS); } @@ -154,7 +164,8 @@ module aave_pool::stream { let is_entity = true; let stream_true = - create_stream(deposit, + create_stream( + deposit, rate_per_second, remaining_balance, start_time, @@ -162,7 +173,8 @@ module aave_pool::stream { recipient, sender, token_address, - is_entity); + is_entity, + ); assert!(recipient(&stream_true) == recipient, TEST_SUCCESS); } @@ -180,7 +192,8 @@ module aave_pool::stream { let arg_is_entity = true; let stream = - create_stream(arg_deposit, + create_stream( + arg_deposit, arg_rate_per_second, arg_remaining_balance, arg_start_time, @@ -188,16 +201,19 @@ module aave_pool::stream { arg_recipient, arg_sender, arg_token_address, - arg_is_entity); + arg_is_entity, + ); - let (_sender, + let ( + _sender, _recipient, _deposit, _token_address, _start_time, _stop_time, _remaining_balance, - _rate_per_second) = get_stream(&stream); + _rate_per_second + ) = get_stream(&stream); assert!(stream.deposit == arg_deposit, TEST_SUCCESS); assert!(stream.rate_per_second == arg_rate_per_second, TEST_SUCCESS); @@ -223,7 +239,8 @@ module aave_pool::stream { let arg_is_entity = true; let stream = - create_stream(arg_deposit, + create_stream( + arg_deposit, arg_rate_per_second, arg_remaining_balance, arg_start_time, @@ -231,16 +248,19 @@ module aave_pool::stream { arg_recipient, arg_sender, arg_token_address, - arg_is_entity); + arg_is_entity, + ); - let (_sender, + let ( + _sender, _recipient, _deposit, _token_address, _start_time, _stop_time, _remaining_balance, - _rate_per_second) = get_stream(&stream); + _rate_per_second + ) = get_stream(&stream); assert!(stream.remaining_balance == arg_remaining_balance, TEST_SUCCESS); diff --git a/aave-core/sources/aave-periphery/transfer_strategy.move b/aave-core/sources/aave-periphery/transfer_strategy.move index cb3b4c0..adf2926 100644 --- a/aave-core/sources/aave-periphery/transfer_strategy.move +++ b/aave-core/sources/aave-periphery/transfer_strategy.move @@ -2,17 +2,18 @@ module aave_pool::transfer_strategy { use std::option::{Self, Option}; use std::signer; use aptos_framework::event; + use aave_acl::acl_manage::Self; use aave_mock_oracle::oracle::RewardOracle; - use aave_pool::underlying_token_factory; + use aave_pool::mock_underlying_token_factory; use aave_pool::staked_token::{MockStakedToken, stake, staked_token}; - // friend aave_pool::underlying_token_factory; - #[test_only] use std::string::utf8; + // friend aave_pool::underlying_token_factory; + const ONLY_REWARDS_ADMIN: u64 = 1; const CALLER_NOT_INCENTIVES_CONTROLLER: u64 = 1; const REWARD_TOKEN_NOT_STAKE_CONTRACT: u64 = 1; @@ -44,10 +45,16 @@ module aave_pool::transfer_strategy { amount: u256, pull_rewards_transfer_strategy: PullRewardsTransferStrategy ): bool { - pull_rewards_transfer_strategy_only_incentives_controller(caller, &pull_rewards_transfer_strategy); + pull_rewards_transfer_strategy_only_incentives_controller( + caller, &pull_rewards_transfer_strategy + ); - underlying_token_factory::transfer_from(pull_rewards_transfer_strategy.rewards_vault, to, - (amount as u64), reward); + mock_underlying_token_factory::transfer_from( + pull_rewards_transfer_strategy.rewards_vault, + to, + (amount as u64), + reward, + ); true } @@ -61,17 +68,20 @@ module aave_pool::transfer_strategy { fun pull_rewards_transfer_strategy_only_rewards_admin( caller: &signer, pull_rewards_transfer_strategy: PullRewardsTransferStrategy ) { - assert!(signer::address_of(caller) - == pull_rewards_transfer_strategy.rewards_admin, - ONLY_REWARDS_ADMIN); + assert!( + signer::address_of(caller) == pull_rewards_transfer_strategy.rewards_admin, + ONLY_REWARDS_ADMIN, + ); } fun pull_rewards_transfer_strategy_only_incentives_controller( caller: &signer, pull_rewards_transfer_strategy: &PullRewardsTransferStrategy ) { - assert!(signer::address_of(caller) - == pull_rewards_transfer_strategy.incentives_controller, - CALLER_NOT_INCENTIVES_CONTROLLER); + assert!( + signer::address_of(caller) + == pull_rewards_transfer_strategy.incentives_controller, + CALLER_NOT_INCENTIVES_CONTROLLER, + ); } public fun pull_rewards_transfer_strategy_get_incentives_controller( @@ -93,11 +103,13 @@ module aave_pool::transfer_strategy { amount: u256, pull_rewards_transfer_strategy: PullRewardsTransferStrategy, ) { - pull_rewards_transfer_strategy_only_rewards_admin(caller, - pull_rewards_transfer_strategy); + pull_rewards_transfer_strategy_only_rewards_admin( + caller, pull_rewards_transfer_strategy + ); - underlying_token_factory::transfer_from(signer::address_of(caller), to, (amount as u64), - token); + mock_underlying_token_factory::transfer_from( + signer::address_of(caller), to, (amount as u64), token + ); emit_emergency_withdrawal_event(caller, token, to, amount); } @@ -130,10 +142,13 @@ module aave_pool::transfer_strategy { amount: u256, staked_token_transfer_strategy: StakedTokenTransferStrategy ): bool { - staked_token_transfer_strategy_only_incentives_controller(caller, &staked_token_transfer_strategy); - assert!(reward - == staked_token(&staked_token_transfer_strategy.stake_contract), - REWARD_TOKEN_NOT_STAKE_CONTRACT); + staked_token_transfer_strategy_only_incentives_controller( + caller, &staked_token_transfer_strategy + ); + assert!( + reward == staked_token(&staked_token_transfer_strategy.stake_contract), + REWARD_TOKEN_NOT_STAKE_CONTRACT, + ); stake(&staked_token_transfer_strategy.stake_contract, to, amount); @@ -155,17 +170,20 @@ module aave_pool::transfer_strategy { fun staked_token_transfer_strategy_only_rewards_admin( caller: &signer, staked_token_transfer_strategy: StakedTokenTransferStrategy ) { - assert!(signer::address_of(caller) - == staked_token_transfer_strategy.rewards_admin, - ONLY_REWARDS_ADMIN); + assert!( + signer::address_of(caller) == staked_token_transfer_strategy.rewards_admin, + ONLY_REWARDS_ADMIN, + ); } fun staked_token_transfer_strategy_only_incentives_controller( caller: &signer, staked_token_transfer_strategy: &StakedTokenTransferStrategy ) { - assert!(signer::address_of(caller) - == staked_token_transfer_strategy.incentives_controller, - CALLER_NOT_INCENTIVES_CONTROLLER); + assert!( + signer::address_of(caller) + == staked_token_transfer_strategy.incentives_controller, + CALLER_NOT_INCENTIVES_CONTROLLER, + ); } public fun staked_token_transfer_strategy_get_incentives_controller( @@ -187,11 +205,13 @@ module aave_pool::transfer_strategy { amount: u256, staked_token_transfer_strategy: StakedTokenTransferStrategy, ) { - staked_token_transfer_strategy_only_rewards_admin(caller, - staked_token_transfer_strategy); + staked_token_transfer_strategy_only_rewards_admin( + caller, staked_token_transfer_strategy + ); - underlying_token_factory::transfer_from(signer::address_of(caller), to, (amount as u64), - token); + mock_underlying_token_factory::transfer_from( + signer::address_of(caller), to, (amount as u64), token + ); emit_emergency_withdrawal_event(caller, token, to, amount); } @@ -211,7 +231,9 @@ module aave_pool::transfer_strategy { rewards_config_input.reward } - public fun get_reward_oracle(rewards_config_input: &RewardsConfigInput): RewardOracle { + public fun get_reward_oracle( + rewards_config_input: &RewardsConfigInput + ): RewardOracle { rewards_config_input.reward_oracle } @@ -257,11 +279,20 @@ module aave_pool::transfer_strategy { rewards_config_input: &RewardsConfigInput ) { assert!( - (option::is_some(&rewards_config_input.staked_token_transfer_strategy) && !option::is_some( - &rewards_config_input.pull_rewards_transfer_strategy)) - || (!option::is_some(&rewards_config_input.staked_token_transfer_strategy) && option::is_some( - &rewards_config_input.pull_rewards_transfer_strategy)), - TOO_MANY_STRATEGIES); + ( + option::is_some(&rewards_config_input.staked_token_transfer_strategy) + && !option::is_some( + &rewards_config_input.pull_rewards_transfer_strategy + ) + ) + || ( + !option::is_some(&rewards_config_input.staked_token_transfer_strategy) + && option::is_some( + &rewards_config_input.pull_rewards_transfer_strategy + ) + ), + TOO_MANY_STRATEGIES, + ); } public fun has_pull_rewards_transfer_strategy( @@ -281,7 +312,9 @@ module aave_pool::transfer_strategy { public fun emit_emergency_withdrawal_event( caller: &signer, token: address, to: address, amount: u256 ) { - event::emit(EmergencyWithdrawal { caller: signer::address_of(caller), token, to, amount }); + event::emit( + EmergencyWithdrawal { caller: signer::address_of(caller), token, to, amount }, + ); } #[test(_aave_role_super_admin = @aave_acl, _periphery_account = @aave_pool, _acl_fund_admin = @0x111, _user_account = @0x222, _creator = @0x1, underlying_tokens_admin = @underlying_tokens, aave_pool = @aave_pool)] @@ -294,41 +327,49 @@ module aave_pool::transfer_strategy { underlying_tokens_admin: &signer, aave_pool: &signer, ) { - let pull_rewards_transfer_strategy = - PullRewardsTransferStrategy { - rewards_admin: signer::address_of(underlying_tokens_admin), - incentives_controller: signer::address_of(underlying_tokens_admin), - rewards_vault: signer::address_of(underlying_tokens_admin), - }; - - underlying_token_factory::test_init_module(aave_pool); + let pull_rewards_transfer_strategy = PullRewardsTransferStrategy { + rewards_admin: signer::address_of(underlying_tokens_admin), + incentives_controller: signer::address_of(underlying_tokens_admin), + rewards_vault: signer::address_of(underlying_tokens_admin), + }; + + mock_underlying_token_factory::test_init_module(aave_pool); let underlying_token_name = utf8(b"TOKEN_1"); let underlying_token_symbol = utf8(b"T1"); let underlying_token_decimals = 3; let underlying_token_max_supply = 10000; - underlying_token_factory::create_token(underlying_tokens_admin, + mock_underlying_token_factory::create_token( + underlying_tokens_admin, underlying_token_max_supply, underlying_token_name, underlying_token_symbol, underlying_token_decimals, utf8(b""), - utf8(b""),); - let underlying_token_address = underlying_token_factory::token_address( - underlying_token_symbol); + utf8(b""), + ); + let underlying_token_address = + mock_underlying_token_factory::token_address(underlying_token_symbol); - underlying_token_factory::mint(underlying_tokens_admin, + mock_underlying_token_factory::mint( + underlying_tokens_admin, signer::address_of(underlying_tokens_admin), 100, - underlying_token_address); + underlying_token_address, + ); let caller: &signer = underlying_tokens_admin; let to: address = signer::address_of(underlying_tokens_admin); let reward: address = underlying_token_address; let amount: u256 = 1; - pull_rewards_transfer_strategy_perform_transfer(caller, to, reward, amount, - pull_rewards_transfer_strategy); + pull_rewards_transfer_strategy_perform_transfer( + caller, + to, + reward, + amount, + pull_rewards_transfer_strategy, + ); } #[test(_aave_role_super_admin = @aave_acl, _periphery_account = @aave_pool, _acl_fund_admin = @0x111, _user_account = @0x222, _creator = @0x1, underlying_tokens_admin = @underlying_tokens, aave_pool = @aave_pool,)] @@ -341,47 +382,57 @@ module aave_pool::transfer_strategy { underlying_tokens_admin: &signer, aave_pool: &signer, ) { - let pull_rewards_transfer_strategy = - PullRewardsTransferStrategy { - rewards_admin: signer::address_of(underlying_tokens_admin), - incentives_controller: signer::address_of(underlying_tokens_admin), - rewards_vault: signer::address_of(underlying_tokens_admin), - }; - - underlying_token_factory::test_init_module(aave_pool); + let pull_rewards_transfer_strategy = PullRewardsTransferStrategy { + rewards_admin: signer::address_of(underlying_tokens_admin), + incentives_controller: signer::address_of(underlying_tokens_admin), + rewards_vault: signer::address_of(underlying_tokens_admin), + }; + + mock_underlying_token_factory::test_init_module(aave_pool); let underlying_token_name = utf8(b"TOKEN_1"); let underlying_token_symbol = utf8(b"T1"); let underlying_token_decimals = 3; let underlying_token_max_supply = 10000; - underlying_token_factory::create_token(underlying_tokens_admin, + mock_underlying_token_factory::create_token( + underlying_tokens_admin, underlying_token_max_supply, underlying_token_name, underlying_token_symbol, underlying_token_decimals, utf8(b""), - utf8(b""),); - let underlying_token_address = underlying_token_factory::token_address( - underlying_token_symbol); + utf8(b""), + ); + let underlying_token_address = + mock_underlying_token_factory::token_address(underlying_token_symbol); - underlying_token_factory::mint(underlying_tokens_admin, + mock_underlying_token_factory::mint( + underlying_tokens_admin, signer::address_of(underlying_tokens_admin), 100, - underlying_token_address); + underlying_token_address, + ); let caller: &signer = underlying_tokens_admin; let to: address = signer::address_of(underlying_tokens_admin); let reward: address = underlying_token_address; let amount: u256 = 1; - pull_rewards_transfer_strategy_perform_transfer(caller, to, reward, amount, - pull_rewards_transfer_strategy); + pull_rewards_transfer_strategy_perform_transfer( + caller, + to, + reward, + amount, + pull_rewards_transfer_strategy, + ); - pull_rewards_transfer_strategy_emergency_withdrawal(caller, + pull_rewards_transfer_strategy_emergency_withdrawal( + caller, underlying_token_address, to, amount, - pull_rewards_transfer_strategy); + pull_rewards_transfer_strategy, + ); } #[test(_aave_role_super_admin = @aave_acl, _periphery_account = @aave_pool, _acl_fund_admin = @0x111, _user_account = @0x222, _creator = @0x1, underlying_tokens_admin = @underlying_tokens, aave_pool = @aave_pool,)] @@ -394,43 +445,52 @@ module aave_pool::transfer_strategy { underlying_tokens_admin: &signer, aave_pool: &signer ) { - underlying_token_factory::test_init_module(aave_pool); + mock_underlying_token_factory::test_init_module(aave_pool); let underlying_token_name = utf8(b"TOKEN_1"); let underlying_token_symbol = utf8(b"T1"); let underlying_token_decimals = 3; let underlying_token_max_supply = 10000; - underlying_token_factory::create_token(underlying_tokens_admin, + mock_underlying_token_factory::create_token( + underlying_tokens_admin, underlying_token_max_supply, underlying_token_name, underlying_token_symbol, underlying_token_decimals, utf8(b""), - utf8(b""),); - let underlying_token_address = underlying_token_factory::token_address( - underlying_token_symbol); + utf8(b""), + ); + let underlying_token_address = + mock_underlying_token_factory::token_address(underlying_token_symbol); - underlying_token_factory::mint(underlying_tokens_admin, + mock_underlying_token_factory::mint( + underlying_tokens_admin, signer::address_of(underlying_tokens_admin), 100, - underlying_token_address); + underlying_token_address, + ); - let staked_token_transfer_strategy = - StakedTokenTransferStrategy { - rewards_admin: signer::address_of(underlying_tokens_admin), - incentives_controller: signer::address_of(underlying_tokens_admin), - stake_contract: aave_pool::staked_token::create_mock_staked_token(signer::address_of( - underlying_tokens_admin)), - underlying_token: underlying_token_address, - }; + let staked_token_transfer_strategy = StakedTokenTransferStrategy { + rewards_admin: signer::address_of(underlying_tokens_admin), + incentives_controller: signer::address_of(underlying_tokens_admin), + stake_contract: aave_pool::staked_token::create_mock_staked_token( + signer::address_of(underlying_tokens_admin) + ), + underlying_token: underlying_token_address, + }; let caller: &signer = underlying_tokens_admin; let to: address = signer::address_of(underlying_tokens_admin); let reward: address = signer::address_of(underlying_tokens_admin); let amount: u256 = 1; - staked_token_transfer_strategy_perform_transfer(caller, to, reward, amount, - staked_token_transfer_strategy); + staked_token_transfer_strategy_perform_transfer( + caller, + to, + reward, + amount, + staked_token_transfer_strategy, + ); } #[test(_aave_role_super_admin = @aave_acl, _periphery_account = @aave_pool, _acl_fund_admin = @0x111, _user_account = @0x222, _creator = @0x1, underlying_tokens_admin = @underlying_tokens, aave_pool = @aave_pool,)] @@ -443,48 +503,59 @@ module aave_pool::transfer_strategy { underlying_tokens_admin: &signer, aave_pool: &signer, ) { - underlying_token_factory::test_init_module(aave_pool); + mock_underlying_token_factory::test_init_module(aave_pool); let underlying_token_name = utf8(b"TOKEN_1"); let underlying_token_symbol = utf8(b"T1"); let underlying_token_decimals = 3; let underlying_token_max_supply = 10000; - underlying_token_factory::create_token(underlying_tokens_admin, + mock_underlying_token_factory::create_token( + underlying_tokens_admin, underlying_token_max_supply, underlying_token_name, underlying_token_symbol, underlying_token_decimals, utf8(b""), - utf8(b""),); - let underlying_token_address = underlying_token_factory::token_address( - underlying_token_symbol); + utf8(b""), + ); + let underlying_token_address = + mock_underlying_token_factory::token_address(underlying_token_symbol); - underlying_token_factory::mint(underlying_tokens_admin, + mock_underlying_token_factory::mint( + underlying_tokens_admin, signer::address_of(underlying_tokens_admin), 100, - underlying_token_address); + underlying_token_address, + ); - let staked_token_transfer_strategy = - StakedTokenTransferStrategy { - rewards_admin: signer::address_of(underlying_tokens_admin), - incentives_controller: signer::address_of(underlying_tokens_admin), - stake_contract: aave_pool::staked_token::create_mock_staked_token(signer::address_of( - underlying_tokens_admin)), - underlying_token: underlying_token_address, - }; + let staked_token_transfer_strategy = StakedTokenTransferStrategy { + rewards_admin: signer::address_of(underlying_tokens_admin), + incentives_controller: signer::address_of(underlying_tokens_admin), + stake_contract: aave_pool::staked_token::create_mock_staked_token( + signer::address_of(underlying_tokens_admin) + ), + underlying_token: underlying_token_address, + }; let caller: &signer = underlying_tokens_admin; let to: address = signer::address_of(underlying_tokens_admin); let reward: address = signer::address_of(underlying_tokens_admin); let amount: u256 = 1; - staked_token_transfer_strategy_perform_transfer(caller, to, reward, amount, - staked_token_transfer_strategy); + staked_token_transfer_strategy_perform_transfer( + caller, + to, + reward, + amount, + staked_token_transfer_strategy, + ); - staked_token_transfer_strategy_emergency_withdrawal(caller, + staked_token_transfer_strategy_emergency_withdrawal( + caller, underlying_token_address, to, amount, - staked_token_transfer_strategy); + staked_token_transfer_strategy, + ); } } diff --git a/aave-core/sources/aave-periphery/ui_incentive_data_provider_v3.move b/aave-core/sources/aave-periphery/ui_incentive_data_provider_v3.move new file mode 100644 index 0000000..d0bf030 --- /dev/null +++ b/aave-core/sources/aave-periphery/ui_incentive_data_provider_v3.move @@ -0,0 +1,390 @@ +module aave_pool::ui_incentive_data_provider_v3 { + use std::string::String; + use std::vector; + use aptos_framework::object::{Self, Object}; + use aave_pool::rewards_controller::Self; + use aave_pool::eac_aggregator_proxy::Self; + use aave_pool::pool::{Self,}; + use aave_pool::a_token_factory::Self; + + const EMPTY_ADDRESS: address = @0x0; + + const UI_INCENTIVE_DATA_PROVIDER_V3_NAME: vector = b"AAVE_UI_INCENTIVE_DATA_PROVIDER_V3"; + + struct UiIncentiveDataProviderV3Data has key {} + + struct AggregatedReserveIncentiveData has store, drop { + underlying_asset: address, + a_incentive_data: IncentiveData, + v_incentive_data: IncentiveData, + } + + struct IncentiveData has store, drop { + token_address: address, + incentive_controller_address: address, + rewards_token_information: vector, + } + + struct RewardInfo has store, drop { + reward_token_symbol: String, + reward_token_address: address, + reward_oracle_address: address, + emission_per_second: u256, + incentives_last_update_timestamp: u256, + token_incentives_index: u256, + emission_end_timestamp: u256, + reward_price_feed: u256, + reward_token_decimals: u8, + precision: u8, + price_feed_decimals: u8, + } + + struct UserReserveIncentiveData has store, drop { + underlying_asset: address, + a_token_incentives_user_data: UserIncentiveData, + v_token_incentives_user_data: UserIncentiveData, + } + + struct UserIncentiveData has store, drop { + token_address: address, + incentive_controller_address: address, + user_rewards_information: vector + } + + struct UserRewardInfo has store, drop { + reward_token_symbol: String, + reward_oracle_address: address, + reward_token_address: address, + user_unclaimed_rewards: u256, + token_incentives_user_index: u256, + reward_price_feed: u256, + price_feed_decimals: u8, + reward_token_decimals: u8, + } + + fun init_module(sender: &signer,) { + let state_object_constructor_ref = + &object::create_named_object(sender, UI_INCENTIVE_DATA_PROVIDER_V3_NAME); + let state_object_signer = &object::generate_signer(state_object_constructor_ref); + + move_to( + state_object_signer, + UiIncentiveDataProviderV3Data {}, + ); + } + + #[test_only] + public fun init_module_test(sender: &signer) { + init_module(sender); + } + + #[view] + public fun ui_incentive_data_provider_v3_data_address(): address { + object::create_object_address(&@aave_pool, UI_INCENTIVE_DATA_PROVIDER_V3_NAME) + } + + #[view] + public fun ui_incentive_data_provider_v3_data_object() + : Object { + object::address_to_object( + ui_incentive_data_provider_v3_data_address() + ) + } + + #[view] + public fun get_full_reserves_incentive_data(user: address) + : ( + vector, vector + ) { + (get_reserves_incentives_data(), get_user_reserves_incentives_data(user)) + } + + #[view] + public fun get_reserves_incentives_data(): vector { + let reserves = pool::get_reserves_list(); + let reserves_incentives_data = vector::empty(); + + for (i in 0..vector::length(&reserves)) { + let underlying_asset = *vector::borrow(&reserves, i); + let base_data = pool::get_reserve_data(underlying_asset); + let rewards_controller_address = + rewards_controller::rewards_controller_address(); + // TODO Waiting for Chainlink oracle functionality + let reward_oracle_address = @aave_mock_oracle; + + if (rewards_controller_address != EMPTY_ADDRESS) { + + // ===================== a token ==================== + let a_token_address = pool::get_reserve_a_token_address(&base_data); + let a_token_reward_addresses = + rewards_controller::get_rewards_by_asset( + a_token_address, + rewards_controller_address, + ); + let reward_information: vector = vector[]; + + for (j in 0..vector::length(&a_token_reward_addresses)) { + let reward_token_address = + *vector::borrow(&a_token_reward_addresses, j); + + let ( + token_incentives_index, + emission_per_second, + incentives_last_update_timestamp, + emission_end_timestamp + ) = + rewards_controller::get_rewards_data( + a_token_address, + reward_token_address, + rewards_controller_address, + ); + + let precision = + rewards_controller::get_asset_decimals( + a_token_address, rewards_controller_address + ); + let reward_token_decimals = + a_token_factory::decimals(reward_token_address); + let reward_token_symbol = + a_token_factory::symbol(reward_token_address); + + let price_feed_decimals = eac_aggregator_proxy::decimals(); + let reward_price_feed = eac_aggregator_proxy::latest_answer(); + + vector::push_back( + &mut reward_information, + RewardInfo { + reward_token_symbol, + reward_token_address, + reward_oracle_address, + emission_per_second, + incentives_last_update_timestamp, + token_incentives_index, + emission_end_timestamp, + reward_price_feed, + reward_token_decimals, + precision, + price_feed_decimals, + }, + ); + }; + + let a_incentive_data = IncentiveData { + token_address: a_token_address, + incentive_controller_address: rewards_controller_address, + rewards_token_information: reward_information, + }; + + // ===================== variable debt token ==================== + let variable_debt_token_address = + pool::get_reserve_variable_debt_token_address(&base_data); + let var_debt_token_reward_addresses = + rewards_controller::get_rewards_by_asset( + variable_debt_token_address, + rewards_controller_address, + ); + let reward_information: vector = vector[]; + + for (j in 0..vector::length(&var_debt_token_reward_addresses)) { + let reward_token_address = + *vector::borrow(&var_debt_token_reward_addresses, j); + + let ( + token_incentives_index, + emission_per_second, + incentives_last_update_timestamp, + emission_end_timestamp + ) = + rewards_controller::get_rewards_data( + variable_debt_token_address, + reward_token_address, + rewards_controller_address, + ); + + let precision = + rewards_controller::get_asset_decimals( + variable_debt_token_address, rewards_controller_address + ); + let reward_token_decimals = + a_token_factory::decimals(reward_token_address); + let reward_token_symbol = + a_token_factory::symbol(reward_token_address); + + let price_feed_decimals = eac_aggregator_proxy::decimals(); + let reward_price_feed = eac_aggregator_proxy::latest_answer(); + + vector::push_back( + &mut reward_information, + RewardInfo { + reward_token_symbol, + reward_token_address, + reward_oracle_address, + emission_per_second, + incentives_last_update_timestamp, + token_incentives_index, + emission_end_timestamp, + reward_price_feed, + reward_token_decimals, + precision, + price_feed_decimals, + }, + ); + }; + + let v_incentive_data = IncentiveData { + token_address: variable_debt_token_address, + incentive_controller_address: rewards_controller_address, + rewards_token_information: reward_information, + }; + + vector::push_back( + &mut reserves_incentives_data, + AggregatedReserveIncentiveData { + underlying_asset, + a_incentive_data, + v_incentive_data, + }, + ) + }; + }; + reserves_incentives_data + } + + #[view] + public fun get_user_reserves_incentives_data(user: address) + : vector { + let reserves = pool::get_reserves_list(); + let user_reserves_incentives_data = vector::empty(); + + for (i in 0..vector::length(&reserves)) { + let underlying_asset = *vector::borrow(&reserves, i); + let base_data = pool::get_reserve_data(underlying_asset); + let rewards_controller_address = + rewards_controller::rewards_controller_address(); + // TODO Waiting for Chainlink oracle functionality + let reward_oracle_address = @aave_mock_oracle; + + if (rewards_controller_address != EMPTY_ADDRESS) { + + // ===================== a token ==================== + let a_token_address = pool::get_reserve_a_token_address(&base_data); + let a_token_reward_addresses = + rewards_controller::get_rewards_by_asset( + a_token_address, + rewards_controller_address, + ); + let user_rewards_information: vector = vector[]; + + for (j in 0..vector::length(&a_token_reward_addresses)) { + let reward_token_address = + *vector::borrow(&a_token_reward_addresses, j); + + let token_incentives_user_index = + rewards_controller::get_user_asset_index( + user, + a_token_address, + reward_token_address, + rewards_controller_address, + ); + + let user_unclaimed_rewards = + rewards_controller::get_user_accrued_rewards( + user, reward_token_address, rewards_controller_address + ); + let reward_token_decimals = + a_token_factory::decimals(reward_token_address); + let reward_token_symbol = + a_token_factory::symbol(reward_token_address); + + let price_feed_decimals = eac_aggregator_proxy::decimals(); + let reward_price_feed = eac_aggregator_proxy::latest_answer(); + + vector::push_back( + &mut user_rewards_information, + UserRewardInfo { + reward_token_symbol, + reward_oracle_address, + reward_token_address, + user_unclaimed_rewards, + token_incentives_user_index, + reward_price_feed, + price_feed_decimals, + reward_token_decimals, + }, + ); + }; + + let a_incentive_data = UserIncentiveData { + token_address: a_token_address, + incentive_controller_address: rewards_controller_address, + user_rewards_information, + }; + + // ===================== variable debt token ==================== + let variable_debt_token_address = + pool::get_reserve_variable_debt_token_address(&base_data); + let var_debt_token_reward_addresses = + rewards_controller::get_rewards_by_asset( + variable_debt_token_address, + rewards_controller_address, + ); + let user_rewards_information: vector = vector[]; + + for (j in 0..vector::length(&var_debt_token_reward_addresses)) { + let reward_token_address = + *vector::borrow(&var_debt_token_reward_addresses, j); + + let token_incentives_user_index = + rewards_controller::get_user_asset_index( + user, + variable_debt_token_address, + reward_token_address, + rewards_controller_address, + ); + + let user_unclaimed_rewards = + rewards_controller::get_user_accrued_rewards( + user, reward_token_address, rewards_controller_address + ); + let reward_token_decimals = + a_token_factory::decimals(reward_token_address); + let reward_token_symbol = + a_token_factory::symbol(reward_token_address); + + let price_feed_decimals = eac_aggregator_proxy::decimals(); + let reward_price_feed = eac_aggregator_proxy::latest_answer(); + + vector::push_back( + &mut user_rewards_information, + UserRewardInfo { + reward_token_symbol, + reward_oracle_address, + reward_token_address, + user_unclaimed_rewards, + token_incentives_user_index, + reward_price_feed, + price_feed_decimals, + reward_token_decimals, + }, + ); + }; + + let v_incentive_data = UserIncentiveData { + token_address: variable_debt_token_address, + incentive_controller_address: rewards_controller_address, + user_rewards_information, + }; + + vector::push_back( + &mut user_reserves_incentives_data, + UserReserveIncentiveData { + underlying_asset, + a_token_incentives_user_data: a_incentive_data, + v_token_incentives_user_data: v_incentive_data, + }, + ) + }; + }; + user_reserves_incentives_data + } +} diff --git a/aave-core/sources/aave-periphery/ui_pool_data_provider_v3.move b/aave-core/sources/aave-periphery/ui_pool_data_provider_v3.move index 81d1037..3f2fd84 100644 --- a/aave-core/sources/aave-periphery/ui_pool_data_provider_v3.move +++ b/aave-core/sources/aave-periphery/ui_pool_data_provider_v3.move @@ -1,58 +1,59 @@ module aave_pool::ui_pool_data_provider_v3 { + use std::option::Self; + use std::string::String; + use std::vector; use aptos_framework::object::{Self, Object}; + + use aave_config::reserve as reserve_config; + use aave_config::user::Self as user_config; + use aave_mock_oracle::oracle::{get_asset_price, get_base_currency_unit}; + use aave_pool::mock_underlying_token_factory::Self; + use aave_pool::a_token_factory; + use aave_pool::default_reserve_interest_rate_strategy::{ + get_base_variable_borrow_rate, + get_optimal_usage_ratio, + get_variable_rate_slope1, + get_variable_rate_slope2, + }; use aave_pool::eac_aggregator_proxy::{ - MockEacAggregatorProxy, create_eac_aggregator_proxy, + decimals, latest_answer, - decimals + MockEacAggregatorProxy }; - use std::string::String; - use std::vector; - use std::option::Self; + use aave_pool::emode_logic; use aave_pool::pool::{ Self, + get_reserve_a_token_address, get_reserve_accrued_to_treasury, + get_reserve_current_liquidity_rate, + get_reserve_current_variable_borrow_rate, get_reserve_isolation_mode_total_debt, - get_reserve_unbacked, + get_reserve_last_update_timestamp, get_reserve_liquidity_index, + get_reserve_unbacked, get_reserve_variable_borrow_index, - get_reserve_current_liquidity_rate, - get_reserve_current_variable_borrow_rate, - get_reserve_variable_debt_token_address, - get_reserve_a_token_address, - get_reserve_last_update_timestamp + get_reserve_variable_debt_token_address }; - use aave_pool::emode_logic; - use aave_pool::pool_addresses_provider::get_price_oracle; - use aave_pool::a_token_factory; - use aave_pool::variable_token_factory; use aave_pool::token_base; - use aave_config::user::{Self as user_config}; - use aave_config::reserve as reserve_config; - use aave_pool::default_reserve_interest_rate_strategy::{ - get_base_variable_borrow_rate, - get_variable_rate_slope1, - get_variable_rate_slope2, - get_optimal_usage_ratio, - }; - use aave_mock_oracle::oracle::{get_asset_price, get_base_currency_unit}; + use aave_pool::variable_debt_token_factory; const EMPTY_ADDRESS: address = @0x0; const ETH_CURRENCY_UNIT: u256 = 1; const EROLE_NOT_EXISTS: u64 = 1; - const ESTREAM_NOT_EXISTS: u64 = 1; - const NOT_FUNDS_ADMIN: u64 = 1; - const ESTREAM_TO_THE_CONTRACT_ITSELF: u64 = 1; - const ESTREAM_TO_THE_CALLER: u64 = 1; - const EDEPOSIT_IS_ZERO: u64 = 1; - const ESTART_TIME_BEFORE_BLOCK_TIMESTAMP: u64 = 1; - const ESTOP_TIME_BEFORE_THE_START_TIME: u64 = 1; - const EDEPOSIT_SMALLER_THAN_TIME_DELTA: u64 = 1; - const EDEPOSIT_NOT_MULTIPLE_OF_TIME_DELTA: u64 = 1; - const EAMOUNT_IS_ZERO: u64 = 1; - const EAMOUNT_EXCEEDS_THE_AVAILABLE_BALANCE: u64 = 1; + const ESTREAM_NOT_EXISTS: u64 = 2; + const NOT_FUNDS_ADMIN: u64 = 3; + const ESTREAM_TO_THE_CONTRACT_ITSELF: u64 = 4; + const ESTREAM_TO_THE_CALLER: u64 = 5; + const EDEPOSIT_IS_ZERO: u64 = 6; + const ESTART_TIME_BEFORE_BLOCK_TIMESTAMP: u64 = 7; + const ESTOP_TIME_BEFORE_THE_START_TIME: u64 = 8; + const EDEPOSIT_SMALLER_THAN_TIME_DELTA: u64 = 9; + const EDEPOSIT_NOT_MULTIPLE_OF_TIME_DELTA: u64 = 10; + const EAMOUNT_IS_ZERO: u64 = 11; + const EAMOUNT_EXCEEDS_THE_AVAILABLE_BALANCE: u64 = 12; const UI_POOL_DATA_PROVIDER_V3_NAME: vector = b"AAVE_UI_POOL_DATA_PROVIDER_V3"; @@ -132,11 +133,13 @@ module aave_pool::ui_pool_data_provider_v3 { &object::create_named_object(sender, UI_POOL_DATA_PROVIDER_V3_NAME); let state_object_signer = &object::generate_signer(state_object_constructor_ref); - move_to(state_object_signer, + move_to( + state_object_signer, UiPoolDataProviderV3Data { network_base_token_price_in_usd_proxy_aggregator: create_eac_aggregator_proxy(), market_reference_currency_price_in_usd_proxy_aggregator: create_eac_aggregator_proxy(), - }); + }, + ); } #[test_only] @@ -145,14 +148,15 @@ module aave_pool::ui_pool_data_provider_v3 { } #[view] - public fun ui_pool_data_provider_v32_data_address(): address { + public fun ui_pool_data_provider_v3_data_address(): address { object::create_object_address(&@aave_pool, UI_POOL_DATA_PROVIDER_V3_NAME) } #[view] public fun ui_pool_data_provider_v3_data_object(): Object { object::address_to_object( - ui_pool_data_provider_v32_data_address()) + ui_pool_data_provider_v3_data_address() + ) } #[view] @@ -162,7 +166,8 @@ module aave_pool::ui_pool_data_provider_v3 { #[view] public fun get_reserves_data(): (vector, BaseCurrencyInfo) { - let oracle = get_price_oracle(); + // TODO Waiting for Chainlink oracle functionality + let oracle = @aave_mock_oracle; let reserves = pool::get_reserves_list(); @@ -176,55 +181,63 @@ module aave_pool::ui_pool_data_provider_v3 { let liquidity_index = get_reserve_liquidity_index(&base_data); let variable_borrow_index = get_reserve_variable_borrow_index(&base_data); let liquidity_rate = get_reserve_current_liquidity_rate(&base_data); - let variable_borrow_rate = get_reserve_current_variable_borrow_rate(&base_data); + let variable_borrow_rate = + get_reserve_current_variable_borrow_rate(&base_data); let last_update_timestamp = get_reserve_last_update_timestamp(&base_data); let a_token_address = get_reserve_a_token_address(&base_data); - let variable_debt_token_address = get_reserve_variable_debt_token_address(&base_data); + let variable_debt_token_address = + get_reserve_variable_debt_token_address(&base_data); let price_in_market_reference_currency = get_asset_price(underlying_asset); - let price_oracle = - if (option::is_some(&oracle)) { - *option::borrow(&oracle) - } else { EMPTY_ADDRESS }; + let price_oracle = oracle; - let available_liquidity = a_token_factory::scale_balance_of(a_token_address, - underlying_asset); + let available_liquidity = + mock_underlying_token_factory::balance_of( + a_token_address, underlying_asset + ); - let total_scaled_variable_debt = token_base::scale_total_supply( - variable_debt_token_address); + let total_scaled_variable_debt = + token_base::scaled_total_supply(variable_debt_token_address); - let symbol = a_token_factory::symbol(a_token_address); - let name = a_token_factory::name(a_token_address); + let symbol = mock_underlying_token_factory::symbol(underlying_asset); + let name = mock_underlying_token_factory::name(underlying_asset); - let reserve_configuration_map = pool::get_reserve_configuration_by_reserve_data( - &base_data); + let reserve_configuration_map = + pool::get_reserve_configuration_by_reserve_data(&base_data); - let (base_lt_vas_collateral, + let ( + base_lt_vas_collateral, reserve_liquidation_threshold, reserve_liquidation_bonus, decimals, reserve_factor, - e_mode_category_id) = reserve_config::get_params(&reserve_configuration_map); + e_mode_category_id + ) = reserve_config::get_params(&reserve_configuration_map); let usage_as_collateral_enabled = base_lt_vas_collateral != 0; - let (is_active, is_frozen, borrowing_enabled, is_paused) = reserve_config::get_flags( - &reserve_configuration_map); + let (is_active, is_frozen, borrowing_enabled, is_paused) = + reserve_config::get_flags(&reserve_configuration_map); let variable_rate_slope1 = get_variable_rate_slope1(underlying_asset); let variable_rate_slope2 = get_variable_rate_slope2(underlying_asset); - let base_variable_borrow_rate = get_base_variable_borrow_rate(underlying_asset); + let base_variable_borrow_rate = + get_base_variable_borrow_rate(underlying_asset); let optimal_usage_ratio = get_optimal_usage_ratio(underlying_asset); - let debt_ceiling: u256 = reserve_config::get_debt_ceiling(&reserve_configuration_map); + let debt_ceiling: u256 = + reserve_config::get_debt_ceiling(&reserve_configuration_map); let debt_ceiling_decimals = reserve_config::get_debt_ceiling_decimals(); - let (borrow_cap, supply_cap) = reserve_config::get_caps(&reserve_configuration_map); + let (borrow_cap, supply_cap) = + reserve_config::get_caps(&reserve_configuration_map); let flash_loan_enabled = reserve_config::get_flash_loan_enabled(&reserve_configuration_map); - let is_siloed_borrowing = reserve_config::get_siloed_borrowing(&reserve_configuration_map); + let is_siloed_borrowing = + reserve_config::get_siloed_borrowing(&reserve_configuration_map); let unbacked = get_reserve_unbacked(&base_data); - let isolation_mode_total_debt = get_reserve_isolation_mode_total_debt(&base_data); + let isolation_mode_total_debt = + get_reserve_isolation_mode_total_debt(&base_data); let accrued_to_treasury = get_reserve_accrued_to_treasury(&base_data); let e_mode_category_id_u8 = (e_mode_category_id as u8); @@ -241,53 +254,52 @@ module aave_pool::ui_pool_data_provider_v3 { let borrowable_in_isolation = reserve_config::get_borrowable_in_isolation(&reserve_configuration_map); - let aggregated_reserve_data = - AggregatedReserveData { - underlying_asset, - name, - symbol, - decimals, - base_lt_vas_collateral, - reserve_liquidation_threshold, - reserve_liquidation_bonus, - reserve_factor, - usage_as_collateral_enabled, - borrowing_enabled, - is_active, - is_frozen, - liquidity_index, - variable_borrow_index, - liquidity_rate, - variable_borrow_rate, - last_update_timestamp: (last_update_timestamp as u128), - a_token_address, - variable_debt_token_address, - available_liquidity, - total_scaled_variable_debt, - price_in_market_reference_currency, - price_oracle, - variable_rate_slope1, - variable_rate_slope2, - base_variable_borrow_rate, - optimal_usage_ratio, - is_paused, - is_siloed_borrowing, - accrued_to_treasury: (accrued_to_treasury as u128), - unbacked, - isolation_mode_total_debt, - flash_loan_enabled, - debt_ceiling, - debt_ceiling_decimals, - e_mode_category_id: e_mode_category_id_u8, - borrow_cap, - supply_cap, - e_mode_ltv: (e_mode_ltv as u16), - e_mode_liquidation_threshold: (e_mode_liquidation_threshold as u16), - e_mode_liquidation_bonus, - e_mode_price_source, - e_mode_label, - borrowable_in_isolation - }; + let aggregated_reserve_data = AggregatedReserveData { + underlying_asset, + name, + symbol, + decimals, + base_lt_vas_collateral, + reserve_liquidation_threshold, + reserve_liquidation_bonus, + reserve_factor, + usage_as_collateral_enabled, + borrowing_enabled, + is_active, + is_frozen, + liquidity_index, + variable_borrow_index, + liquidity_rate, + variable_borrow_rate, + last_update_timestamp: (last_update_timestamp as u128), + a_token_address, + variable_debt_token_address, + available_liquidity: (available_liquidity as u256), + total_scaled_variable_debt, + price_in_market_reference_currency, + price_oracle, + variable_rate_slope1, + variable_rate_slope2, + base_variable_borrow_rate, + optimal_usage_ratio, + is_paused, + is_siloed_borrowing, + accrued_to_treasury: (accrued_to_treasury as u128), + unbacked, + isolation_mode_total_debt, + flash_loan_enabled, + debt_ceiling, + debt_ceiling_decimals, + e_mode_category_id: e_mode_category_id_u8, + borrow_cap, + supply_cap, + e_mode_ltv: (e_mode_ltv as u16), + e_mode_liquidation_threshold: (e_mode_liquidation_threshold as u16), + e_mode_liquidation_bonus, + e_mode_price_source, + e_mode_label, + borrowable_in_isolation + }; vector::push_back(&mut reserves_data, aggregated_reserve_data); }; @@ -300,7 +312,9 @@ module aave_pool::ui_pool_data_provider_v3 { let market_reference_currency_unit = if (option::is_some(&opt_base_currency_unit)) { *option::borrow(&opt_base_currency_unit) - } else { ETH_CURRENCY_UNIT }; + } else { + ETH_CURRENCY_UNIT + }; let market_reference_currency_price_in_usd = if (option::is_some(&opt_base_currency_unit)) { @@ -309,13 +323,12 @@ module aave_pool::ui_pool_data_provider_v3 { latest_answer() }; - let base_currency_info = - BaseCurrencyInfo { - market_reference_currency_unit, - market_reference_currency_price_in_usd, - network_base_token_price_in_usd, - network_base_token_price_decimals, - }; + let base_currency_info = BaseCurrencyInfo { + market_reference_currency_unit, + market_reference_currency_price_in_usd, + network_base_token_price_in_usd, + network_base_token_price_decimals, + }; (reserves_data, base_currency_info) } @@ -334,25 +347,29 @@ module aave_pool::ui_pool_data_provider_v3 { let base_data = pool::get_reserve_data(underlying_asset); let scaled_a_token_balance = - a_token_factory::scale_balance_of(user, - pool::get_reserve_a_token_address(&base_data)); + a_token_factory::scaled_balance_of( + user, pool::get_reserve_a_token_address(&base_data) + ); - let usage_as_collateral_enabled_on_user = user_config::is_using_as_collateral(&user_config, - (i as u256)); + let usage_as_collateral_enabled_on_user = + user_config::is_using_as_collateral(&user_config, (i as u256)); let scaled_variable_debt = 0; if (user_config::is_borrowing(&user_config, (i as u256))) { - scaled_variable_debt = variable_token_factory::scale_balance_of(pool::get_reserve_variable_debt_token_address( - &base_data), user); + scaled_variable_debt = variable_debt_token_factory::scaled_balance_of( + pool::get_reserve_variable_debt_token_address(&base_data), user + ); }; - vector::push_back(&mut user_reserves_data, + vector::push_back( + &mut user_reserves_data, UserReserveData { underlying_asset, scaled_a_token_balance, usage_as_collateral_enabled_on_user, scaled_variable_debt, - }); + }, + ); }; (user_reserves_data, (user_emode_category_id as u8)) diff --git a/aave-core/sources/aave-pool/default_reserve_interest_rate_strategy.move b/aave-core/sources/aave-pool/default_reserve_interest_rate_strategy.move index f95a78b..3095afb 100644 --- a/aave-core/sources/aave-pool/default_reserve_interest_rate_strategy.move +++ b/aave-core/sources/aave-pool/default_reserve_interest_rate_strategy.move @@ -1,8 +1,14 @@ +/// @title default_reserve_interest_rate_strategy module +/// @author Aave +/// @notice Implements the calculation of the interest rates depending on the reserve state +/// @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_USAGE_RATIO` +/// point of usage and another from that one to 100%. module aave_pool::default_reserve_interest_rate_strategy { use std::signer; use aptos_std::smart_table; use aptos_std::smart_table::SmartTable; + use aptos_framework::event; use aave_acl::acl_manage; use aave_config::error; @@ -10,12 +16,26 @@ module aave_pool::default_reserve_interest_rate_strategy { use aave_math::wad_ray_math::{Self, wad_to_ray}; use aave_pool::a_token_factory; - use aave_pool::underlying_token_factory; + use aave_pool::mock_underlying_token_factory; friend aave_pool::pool_configurator; + #[test_only] friend aave_pool::default_reserve_interest_rate_strategy_tests; + #[event] + struct ReserveInterestRateStrategy has store, drop { + asset: address, + optimal_usage_ratio: u256, + max_excess_usage_ratio: u256, + // Base variable borrow rate when usage rate = 0. Expressed in ray + base_variable_borrow_rate: u256, + // Slope of the variable interest curve when usage ratio > 0 and <= OPTIMAL_USAGE_RATIO. Expressed in ray + variable_rate_slope1: u256, + // Slope of the variable interest curve when usage ratio > OPTIMAL_USAGE_RATIO. Expressed in ray + variable_rate_slope2: u256 + } + struct DefaultReserveInterestRateStrategy has key, store, copy, drop { optimal_usage_ratio: u256, max_excess_usage_ratio: u256, @@ -42,15 +62,26 @@ module aave_pool::default_reserve_interest_rate_strategy { available_liquidity_plus_debt: u256, } + /// @notice Initializes the interest rate strategy public(friend) fun init_interest_rate_strategy(account: &signer) { - assert!((signer::address_of(account) == @aave_pool), - error::get_ecaller_not_pool_admin()); - move_to(account, + assert!( + (signer::address_of(account) == @aave_pool), + error::get_ecaller_not_pool_admin(), + ); + move_to( + account, ReserveInterestRateStrategyMap { vaule: smart_table::new() - }) + }, + ) } + /// @notice Sets the interest rate strategy of a reserve + /// @param asset The address of the reserve + /// @param optimal_usage_ratio The optimal usage ratio + /// @param base_variable_borrow_rate The base variable borrow rate + /// @param variable_rate_slope1 The variable rate slope below optimal usage ratio + /// @param variable_rate_slope2 The variable rate slope above optimal usage ratio public entry fun set_reserve_interest_rate_strategy( account: &signer, asset: address, @@ -60,45 +91,61 @@ module aave_pool::default_reserve_interest_rate_strategy { variable_rate_slope2: u256, ) acquires ReserveInterestRateStrategyMap { let account_address = signer::address_of(account); - assert!(only_risk_or_pool_admins(account_address), - error::get_ecaller_not_risk_or_pool_admin()); - assert!(wad_ray_math::ray() >= optimal_usage_ratio, - error::get_einvalid_optimal_usage_ratio()); + assert!( + only_risk_or_pool_admins(account_address), + error::get_ecaller_not_risk_or_pool_admin(), + ); + assert!( + wad_ray_math::ray() >= optimal_usage_ratio, + error::get_einvalid_optimal_usage_ratio(), + ); let rate_strategy = borrow_global_mut(@aave_pool); - let reserve_interest_rate_strategy = - DefaultReserveInterestRateStrategy { + let max_excess_usage_ratio = wad_ray_math::ray() - optimal_usage_ratio; + let reserve_interest_rate_strategy = DefaultReserveInterestRateStrategy { + optimal_usage_ratio, + max_excess_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + }; + + smart_table::upsert( + &mut rate_strategy.vaule, asset, reserve_interest_rate_strategy + ); + + event::emit( + ReserveInterestRateStrategy { + asset, optimal_usage_ratio, - max_excess_usage_ratio: wad_ray_math::ray() - optimal_usage_ratio, + max_excess_usage_ratio, base_variable_borrow_rate, variable_rate_slope1, variable_rate_slope2, - }; + }, + ) + } - smart_table::upsert(&mut rate_strategy.vaule, asset, reserve_interest_rate_strategy); + public fun asset_interest_rate_exists(asset: address) acquires ReserveInterestRateStrategyMap { + let rate_strategy = borrow_global(@aave_pool); + assert!( + smart_table::contains(&rate_strategy.vaule, asset), + error::get_easset_not_listed(), + ); } #[view] public fun get_reserve_interest_rate_strategy(asset: address) - : DefaultReserveInterestRateStrategy acquires ReserveInterestRateStrategyMap { + : DefaultReserveInterestRateStrategy acquires ReserveInterestRateStrategyMap { + asset_interest_rate_exists(asset); let rate_strategy = borrow_global(@aave_pool); - if (!smart_table::contains(&rate_strategy.vaule, asset)) { - return DefaultReserveInterestRateStrategy { - optimal_usage_ratio: 0, - max_excess_usage_ratio: 0, - base_variable_borrow_rate: 0, - variable_rate_slope1: 0, - variable_rate_slope2: 0 - } - } else { - *smart_table::borrow(&rate_strategy.vaule, asset) - } + *smart_table::borrow(&rate_strategy.vaule, asset) } #[view] public fun get_optimal_usage_ratio(asset: address): u256 acquires ReserveInterestRateStrategyMap { let rate_strategy_map = borrow_global(@aave_pool); if (!smart_table::contains(&rate_strategy_map.vaule, asset)) - return 0; + return 0; smart_table::borrow(&rate_strategy_map.vaule, asset).optimal_usage_ratio } @@ -107,7 +154,7 @@ module aave_pool::default_reserve_interest_rate_strategy { public fun get_max_excess_usage_ratio(asset: address): u256 acquires ReserveInterestRateStrategyMap { let rate_strategy_map = borrow_global(@aave_pool); if (!smart_table::contains(&rate_strategy_map.vaule, asset)) - return 0; + return 0; smart_table::borrow(&rate_strategy_map.vaule, asset).max_excess_usage_ratio } @@ -116,7 +163,7 @@ module aave_pool::default_reserve_interest_rate_strategy { public fun get_variable_rate_slope1(asset: address): u256 acquires ReserveInterestRateStrategyMap { let rate_strategy_map = borrow_global(@aave_pool); if (!smart_table::contains(&rate_strategy_map.vaule, asset)) - return 0; + return 0; smart_table::borrow(&rate_strategy_map.vaule, asset).variable_rate_slope1 } @@ -125,7 +172,7 @@ module aave_pool::default_reserve_interest_rate_strategy { public fun get_variable_rate_slope2(asset: address): u256 acquires ReserveInterestRateStrategyMap { let rate_strategy_map = borrow_global(@aave_pool); if (!smart_table::contains(&rate_strategy_map.vaule, asset)) - return 0; + return 0; smart_table::borrow(&rate_strategy_map.vaule, asset).variable_rate_slope2 } @@ -134,7 +181,7 @@ module aave_pool::default_reserve_interest_rate_strategy { public fun get_base_variable_borrow_rate(asset: address): u256 acquires ReserveInterestRateStrategyMap { let rate_strategy_map = borrow_global(@aave_pool); if (!smart_table::contains(&rate_strategy_map.vaule, asset)) - return 0; + return 0; smart_table::borrow(&rate_strategy_map.vaule, asset).base_variable_borrow_rate } @@ -143,13 +190,24 @@ module aave_pool::default_reserve_interest_rate_strategy { public fun get_max_variable_borrow_rate(asset: address): u256 acquires ReserveInterestRateStrategyMap { let rate_strategy_map = borrow_global(@aave_pool); if (!smart_table::contains(&rate_strategy_map.vaule, asset)) - return 0; + return 0; let strategy = smart_table::borrow(&rate_strategy_map.vaule, asset); - strategy.base_variable_borrow_rate + strategy.variable_rate_slope1 + strategy.variable_rate_slope2 + strategy.base_variable_borrow_rate + strategy.variable_rate_slope1 + + strategy.variable_rate_slope2 } #[view] + /// @notice Calculates the interest rates depending on the reserve's state and configurations + /// @param unbacked The amount of unbacked liquidity + /// @param liquidity_added The amount of liquidity added + /// @param liquidity_taken The amount of liquidity taken + /// @param total_variable_debt The total variable debt of the reserve + /// @param reserve_factor The reserve factor + /// @param reserve The address of the reserve + /// @param a_token_address The address of the aToken + /// @return current_liquidity_rate The liquidity rate expressed in rays + /// @return current_variable_borrow_rate The variable borrow rate expressed in rays public fun calculate_interest_rates( unbacked: u256, liquidity_added: u256, @@ -166,13 +224,20 @@ module aave_pool::default_reserve_interest_rate_strategy { if (vars.total_debt != 0) { let balance = - (underlying_token_factory::balance_of(a_token_factory::get_token_account_address( - a_token_address), reserve) as u256); + ( + mock_underlying_token_factory::balance_of( + a_token_factory::get_token_account_address(a_token_address), + reserve, + ) as u256 + ); vars.available_liquidity = balance + liquidity_added - liquidity_taken; vars.available_liquidity_plus_debt = vars.available_liquidity + vars.total_debt; - vars.borrow_usage_ratio = wad_ray_math::ray_div(vars.total_debt, vars.available_liquidity_plus_debt); - vars.supply_usage_ratio = wad_ray_math::ray_div(vars.total_debt, - (vars.available_liquidity_plus_debt + unbacked)); + vars.borrow_usage_ratio = wad_ray_math::ray_div( + vars.total_debt, vars.available_liquidity_plus_debt + ); + vars.supply_usage_ratio = wad_ray_math::ray_div( + vars.total_debt, (vars.available_liquidity_plus_debt + unbacked) + ); }; let rate_strategy = get_reserve_interest_rate_strategy(reserve); @@ -180,21 +245,33 @@ module aave_pool::default_reserve_interest_rate_strategy { let excess_borrow_usage_ratio = wad_ray_math::ray_div( (vars.borrow_usage_ratio - rate_strategy.optimal_usage_ratio), - rate_strategy.max_excess_usage_ratio); - - vars.current_variable_borrow_rate = vars.current_variable_borrow_rate + rate_strategy - .variable_rate_slope1 + wad_ray_math::ray_mul(rate_strategy.variable_rate_slope2, - excess_borrow_usage_ratio); + rate_strategy.max_excess_usage_ratio, + ); + + vars.current_variable_borrow_rate = vars.current_variable_borrow_rate + + rate_strategy.variable_rate_slope1 + + wad_ray_math::ray_mul( + rate_strategy.variable_rate_slope2, excess_borrow_usage_ratio + ); } else { - vars.current_variable_borrow_rate = vars.current_variable_borrow_rate + wad_ray_math::ray_div( - wad_ray_math::ray_mul(rate_strategy.variable_rate_slope1, vars.borrow_usage_ratio), - rate_strategy.optimal_usage_ratio); + vars.current_variable_borrow_rate = vars.current_variable_borrow_rate + + wad_ray_math::ray_div( + wad_ray_math::ray_mul( + rate_strategy.variable_rate_slope1, vars.borrow_usage_ratio + ), + rate_strategy.optimal_usage_ratio, + ); }; - vars.current_liquidity_rate = math_utils::percent_mul(wad_ray_math::ray_mul( - get_overall_borrow_rate(total_variable_debt, vars.current_variable_borrow_rate, ), - vars.supply_usage_ratio), - (math_utils::get_percentage_factor() - reserve_factor)); + vars.current_liquidity_rate = math_utils::percent_mul( + wad_ray_math::ray_mul( + get_overall_borrow_rate( + total_variable_debt, vars.current_variable_borrow_rate + ), + vars.supply_usage_ratio, + ), + (math_utils::get_percentage_factor() - reserve_factor), + ); return (vars.current_liquidity_rate, vars.current_variable_borrow_rate) } @@ -211,6 +288,10 @@ module aave_pool::default_reserve_interest_rate_strategy { } } + /// @dev Calculates the overall borrow rate as the weighted average between the total variable debt + /// @param total_variable_debt The total borrowed from the reserve at a variable rate + /// @param current_variable_borrow_rate The current variable borrow rate of the reserve + /// @return The weighted averaged borrow rate fun get_overall_borrow_rate( total_variable_debt: u256, current_variable_borrow_rate: u256, ): u256 { @@ -218,8 +299,9 @@ module aave_pool::default_reserve_interest_rate_strategy { if (totalDebt == 0) return 0; let weighted_variable_rate = - wad_ray_math::ray_mul(wad_to_ray(total_variable_debt), - current_variable_borrow_rate); + wad_ray_math::ray_mul( + wad_to_ray(total_variable_debt), current_variable_borrow_rate + ); let overall_borrow_rate = wad_ray_math::ray_div((weighted_variable_rate), wad_to_ray(totalDebt)); diff --git a/aave-core/sources/aave-pool/emode_logic.move b/aave-core/sources/aave-pool/emode_logic.move index 3b15a83..d82e127 100644 --- a/aave-core/sources/aave-pool/emode_logic.move +++ b/aave-core/sources/aave-pool/emode_logic.move @@ -1,3 +1,6 @@ +/// @title emode_logic module +/// @author Aave +/// @notice Implements the base logic for all the actions related to the eMode module aave_pool::emode_logic { use std::signer; use std::string; @@ -25,6 +28,9 @@ module aave_pool::emode_logic { const EMPTY_STRING: vector = b""; #[event] + /// @dev Emitted when the user selects a certain asset category for eMode + /// @param user The address of the user + /// @param category_id The category id struct UserEModeSet has store, drop { user: address, category_id: u8, @@ -34,54 +40,74 @@ module aave_pool::emode_logic { ltv: u16, liquidation_threshold: u16, liquidation_bonus: u16, - // each eMode category may or may not have a custom oracle to override the individual assets price oracles + /// each eMode category may or may not have a custom oracle to override the individual assets price oracles price_source: address, label: String, } - // List of eMode categories as a map (eModeCategoryId => eModeCategory). + /// List of eMode categories as a map (emode_category_id => EModeCategory). struct EModeCategoryList has key { value: SmartTable, } + /// Map of users address and their eMode category (user_address => emode_category_id) struct UsersEmodeCategory has key, store { value: SmartTable, } + /// @notice Initializes the eMode public(friend) fun init_emode(account: &signer) { - assert!((signer::address_of(account) == @aave_pool), - error::get_ecaller_not_pool_admin()); - move_to(account, EModeCategoryList { value: smart_table::new(), }); + assert!( + (signer::address_of(account) == @aave_pool), + error::get_ecaller_not_pool_admin(), + ); + move_to( + account, + EModeCategoryList { value: smart_table::new(), }, + ); move_to(account, UsersEmodeCategory { value: smart_table::new(), }) } + /// @notice Updates the user efficiency mode category + /// @dev Will revert if user is borrowing non-compatible asset or change will drop HF < HEALTH_FACTOR_LIQUIDATION_THRESHOLD + /// @dev Emits the `UserEModeSet` event + /// @param category_id The state of all users efficiency mode category public entry fun set_user_emode(account: &signer, category_id: u8) acquires UsersEmodeCategory, EModeCategoryList { // validate set user emode let account_address = signer::address_of(account); let user_config_map = pool::get_user_configuration(account_address); let reserves_count = pool::get_reserves_count(); let emode_configuration = get_emode_category_data(category_id); - pool_validation::validate_set_user_emode(&user_config_map, reserves_count, - category_id, emode_configuration.liquidation_threshold); + pool_validation::validate_set_user_emode( + &user_config_map, + reserves_count, + category_id, + emode_configuration.liquidation_threshold, + ); let prev_category_id = get_user_emode(account_address); let user_emode_category = borrow_global_mut(@aave_pool); smart_table::upsert(&mut user_emode_category.value, account_address, category_id); - let (emode_ltv, emode_liq_threshold, emode_asset_price) = get_emode_configuration( - category_id); + let (emode_ltv, emode_liq_threshold, emode_asset_price) = + get_emode_configuration(category_id); if (prev_category_id != 0) { - pool_validation::validate_health_factor(reserves_count, + pool_validation::validate_health_factor( + reserves_count, &user_config_map, account_address, category_id, emode_ltv, emode_liq_threshold, - emode_asset_price); + emode_asset_price, + ); }; event::emit(UserEModeSet { user: account_address, category_id }); } #[view] + /// @notice Returns the eMode the user is using + /// @param user The address of the user + /// @return The eMode id public fun get_user_emode(user: address): u256 acquires UsersEmodeCategory { let user_emode_category = borrow_global(@aave_pool); if (!smart_table::contains(&user_emode_category.value, user)) { @@ -91,6 +117,9 @@ module aave_pool::emode_logic { (*user_emode as u256) } + /// @notice Get the price source of the eMode category + /// @param user_emode_category The user eMode category + /// @return The price source of the eMode category public fun get_emode_e_mode_price_source(user_emode_category: u8): address acquires EModeCategoryList { let emode_category_list = borrow_global(@aave_pool); if (!smart_table::contains(&emode_category_list.value, user_emode_category)) { @@ -101,6 +130,12 @@ module aave_pool::emode_logic { emode_category.price_source } + /// @notice Gets the eMode configuration and calculates the eMode asset price if a custom oracle is configured + /// @dev The eMode asset price returned is 0 if no oracle is specified + /// @param category The user eMode category + /// @return The eMode ltv + /// @return The eMode liquidation threshold + /// @return The eMode asset price public fun get_emode_configuration(user_emode_category: u8): (u256, u256, u256) acquires EModeCategoryList { let emode_asset_price = 0; let emode_category_list = borrow_global(@aave_pool); @@ -113,10 +148,16 @@ module aave_pool::emode_logic { if (emode_price_source != @0x0) { emode_asset_price = oracle::get_asset_price(emode_price_source); }; - return ((emode_category.ltv as u256), (emode_category.liquidation_threshold as u256), - emode_asset_price) + return ( + (emode_category.ltv as u256), + (emode_category.liquidation_threshold as u256), + emode_asset_price + ) } + /// @notice Gets the eMode category label + /// @param user_emode_category The user eMode category + /// @return The label of the eMode category public fun get_emode_e_mode_label(user_emode_category: u8): String acquires EModeCategoryList { let emode_category_list = borrow_global(@aave_pool); if (!smart_table::contains(&emode_category_list.value, user_emode_category)) { @@ -127,6 +168,9 @@ module aave_pool::emode_logic { emode_category.label } + /// @notice Gets the eMode category liquidation_bonus + /// @param user_emode_category The user eMode category + /// @return The liquidation bonus of the eMode category public fun get_emode_e_mode_liquidation_bonus(user_emode_category: u8): u16 acquires EModeCategoryList { let emode_category_list = borrow_global(@aave_pool); if (!smart_table::contains(&emode_category_list.value, user_emode_category)) { @@ -137,6 +181,15 @@ module aave_pool::emode_logic { emode_category.liquidation_bonus } + /// @notice Configures a new category for the eMode. + /// @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category. + /// The category 0 is reserved as it's the default for volatile assets + /// @param id The id of the category + /// @param ltv The loan to value ratio + /// @param liquidation_threshold The liquidation threshold + /// @param liquidation_bonus The liquidation bonus + /// @param price_source The address of the oracle to override the individual assets price oracles + /// @param label The label of the category public(friend) fun configure_emode_category( id: u8, ltv: u16, @@ -147,7 +200,8 @@ module aave_pool::emode_logic { ) acquires EModeCategoryList { assert!(id != 0, error::get_eemode_category_reserved()); let emode_category_list = borrow_global_mut(@aave_pool); - smart_table::upsert(&mut emode_category_list.value, + smart_table::upsert( + &mut emode_category_list.value, id, EModeCategory { ltv, @@ -155,9 +209,14 @@ module aave_pool::emode_logic { liquidation_bonus, price_source, label, - }); + }, + ); } + /// @notice Checks if eMode is active for a user and if yes, if the asset belongs to the eMode category chosen + /// @param emode_user_category The user eMode category + /// @param emode_asset_category The asset eMode category + /// @return True if eMode is active and the asset belongs to the eMode category chosen by the user, false otherwise public fun is_in_emode_category( emode_user_category: u256, emode_assert_category: u256 ): bool { @@ -165,6 +224,9 @@ module aave_pool::emode_logic { } #[view] + /// @notice Returns the data of an eMode category + /// @param id The id of the category + /// @return The configuration data of the category public fun get_emode_category_data(id: u8): EModeCategory acquires EModeCategoryList { let emode_category_data = borrow_global(@aave_pool); if (!smart_table::contains(&emode_category_data.value, id)) { @@ -174,35 +236,50 @@ module aave_pool::emode_logic { liquidation_bonus: 0, // each eMode category may or may not have a custom oracle to override the individual assets price oracles price_source: @0x0, - label: string::utf8(b""), + label: string::utf8(EMPTY_STRING), } }; *smart_table::borrow(&emode_category_data.value, id) } + /// @notice Get the ltv of the eMode category + /// @param emode_category The eMode category + /// @return The ltv of the eMode category public fun get_emode_category_ltv(emode_category: &EModeCategory): u16 { emode_category.ltv } + /// @notice Get the liquidation threshold of the eMode category + /// @param emode_category The eMode category + /// @return The liquidation threshold of the eMode category public fun get_emode_category_liquidation_threshold( emode_category: &EModeCategory ): u16 { emode_category.liquidation_threshold } + /// @notice Get the liquidation bonus of the eMode category + /// @param emode_category The eMode category + /// @return The liquidation bonus of the eMode category public fun get_emode_category_liquidation_bonus( emode_category: &EModeCategory ): u16 { emode_category.liquidation_bonus } + /// @notice Get the price source of the eMode category + /// @param emode_category The eMode category + /// @return The price source of the eMode category public fun get_emode_category_price_source( emode_category: &EModeCategory ): address { emode_category.price_source } + /// @notice Get the label of the eMode category + /// @param emode_category The eMode category + /// @return The label of the eMode category public fun get_emode_category_label(emode_category: &EModeCategory): String { emode_category.label } diff --git a/aave-core/sources/aave-pool/generic_logic.move b/aave-core/sources/aave-pool/generic_logic.move index c24abe2..bb7bc02 100644 --- a/aave-core/sources/aave-pool/generic_logic.move +++ b/aave-core/sources/aave-pool/generic_logic.move @@ -1,3 +1,6 @@ +/// @title GenericLogic module +/// @author Aave +/// @notice Implements protocol-level logic to calculate and validate the state of a user module aave_pool::generic_logic { use aave_config::reserve as reserve_config; @@ -8,7 +11,7 @@ module aave_pool::generic_logic { use aave_pool::a_token_factory; use aave_pool::pool::{Self, ReserveData}; - use aave_pool::variable_token_factory; + use aave_pool::variable_debt_token_factory; struct CalculateUserAccountDataVars has drop { asset_price: u256, @@ -56,6 +59,22 @@ module aave_pool::generic_logic { } } + /// @notice Calculates the user data across the reserves. + /// @dev It includes the total liquidity/collateral/borrow balances in the base currency used by the price feed, + /// the average Loan To Value, the average Liquidation Ratio, and the Health factor. + /// @param params reserves_count The number of reserves + /// @param params user_config_map The user configuration map + /// @param params user The address of the user + /// @param params user_emode_category The category of the user in the emode + /// @param params emode_ltv The ltv of the user in the emode + /// @param params emode_liq_threshold The liquidation threshold of the user in the emode + /// @param params emode_asset_price The price of the asset in the emode + /// @return The total collateral of the user in the base currency used by the price feed + /// @return The total debt of the user in the base currency used by the price feed + /// @return The average ltv of the user + /// @return The average liquidation threshold of the user + /// @return The health factor of the user + /// @return True if the ltv is zero, false otherwise public fun calculate_user_account_data( reserves_count: u256, user_config_map: &UserConfigurationMap, @@ -66,7 +85,7 @@ module aave_pool::generic_logic { emode_asset_price: u256, ): (u256, u256, u256, u256, u256, bool) { if (user_config::is_empty(user_config_map)) { - return(0, 0, 0, 0, math_utils::u256_max(), false) + return (0, 0, 0, 0, math_utils::u256_max(), false) }; let vars = create_calculate_user_account_data_vars(); @@ -100,30 +119,34 @@ module aave_pool::generic_logic { vars.asset_unit = math_utils::pow(10, vars.decimals); - vars.asset_price = if (vars.emode_asset_price != 0 && user_emode_category == (vars.emode_asset_category as u8)) { + vars.asset_price = if (vars.emode_asset_price != 0 + && user_emode_category == (vars.emode_asset_category as u8)) { vars.emode_asset_price } else { oracle::get_asset_price(vars.current_reserve_address) }; - if (vars.liquidation_threshold != 0 && user_config::is_using_as_collateral(user_config_map, vars - .i)) { - vars.user_balance_in_base_currency = get_user_balance_in_base_currency(user, ¤t_reserve, vars - .asset_price, vars.asset_unit); + if (vars.liquidation_threshold != 0 + && user_config::is_using_as_collateral(user_config_map, vars.i)) { + vars.user_balance_in_base_currency = get_user_balance_in_base_currency( + user, + ¤t_reserve, + vars.asset_price, + vars.asset_unit, + ); vars.total_collateral_in_base_currency = vars.total_collateral_in_base_currency + vars.user_balance_in_base_currency; - vars.is_in_emode_category = user_emode_category != 0 && vars.emode_asset_category == - (user_emode_category as u256); + vars.is_in_emode_category = user_emode_category != 0 + && vars.emode_asset_category == (user_emode_category as u256); if (vars.ltv != 0) { - let ltv = - if (vars.is_in_emode_category) { - vars.emode_ltv - } else { - vars.ltv - }; + let ltv = if (vars.is_in_emode_category) { + vars.emode_ltv + } else { + vars.ltv + }; vars.avg_ltv = vars.avg_ltv + vars.user_balance_in_base_currency * ltv; } else { vars.has_zero_ltv_collateral = true @@ -135,15 +158,20 @@ module aave_pool::generic_logic { } else { vars.liquidation_threshold }; - vars.avg_liquidation_threshold = vars.avg_liquidation_threshold + vars.user_balance_in_base_currency - * liquidation_threshold; + vars.avg_liquidation_threshold = vars.avg_liquidation_threshold + + vars.user_balance_in_base_currency * liquidation_threshold; }; if (user_config::is_borrowing(user_config_map, vars.i)) { let user_debt_in_base_currency = - get_user_debt_in_base_currency(user, ¤t_reserve, vars.asset_price, vars - .asset_unit); - vars.total_debt_in_base_currency = vars.total_debt_in_base_currency + user_debt_in_base_currency; + get_user_debt_in_base_currency( + user, + ¤t_reserve, + vars.asset_price, + vars.asset_unit, + ); + vars.total_debt_in_base_currency = vars.total_debt_in_base_currency + + user_debt_in_base_currency; }; vars.i = vars.i + 1; @@ -160,24 +188,38 @@ module aave_pool::generic_logic { vars.health_factor = if (vars.total_debt_in_base_currency == 0) { math_utils::u256_max() } else { - wad_ray_math::wad_div(math_utils::percent_mul(vars.total_collateral_in_base_currency, vars - .avg_liquidation_threshold), - vars.total_debt_in_base_currency) + wad_ray_math::wad_div( + math_utils::percent_mul( + vars.total_collateral_in_base_currency, + vars.avg_liquidation_threshold, + ), + vars.total_debt_in_base_currency, + ) }; - return(vars.total_collateral_in_base_currency, + return ( + vars.total_collateral_in_base_currency, vars.total_debt_in_base_currency, vars.avg_ltv, vars.avg_liquidation_threshold, vars.health_factor, - vars.has_zero_ltv_collateral) + vars.has_zero_ltv_collateral + ) } + /// @notice Calculates the maximum amount that can be borrowed depending on the available collateral, the total debt + /// and the average Loan To Value + /// @param total_collateral_in_base_currency The total collateral in the base currency used by the price feed + /// @param total_debt_in_base_currency The total borrow balance in the base currency used by the price feed + /// @param ltv The average loan to value + /// @return The amount available to borrow in the base currency of the used by the price feed public fun calculate_available_borrows( - total_collateral_in_base_currency: u256, total_debt_in_base_currency: u256, ltv: u256, + total_collateral_in_base_currency: u256, + total_debt_in_base_currency: u256, + ltv: u256, ): u256 { - let available_borrows_in_base_currency = math_utils::percent_mul( - total_collateral_in_base_currency, ltv); + let available_borrows_in_base_currency = + math_utils::percent_mul(total_collateral_in_base_currency, ltv); if (available_borrows_in_base_currency < total_debt_in_base_currency) { return 0 @@ -186,12 +228,21 @@ module aave_pool::generic_logic { available_borrows_in_base_currency - total_debt_in_base_currency } + /// @notice Calculates total debt of the user in the based currency used to normalize the values of the assets + /// the variable debt balance is calculated by fetching `scaledBalancesOf` normalized debt, which is cheaper than + /// fetching `balanceOf` + /// @param user The address of the user + /// @param reserve_data The data of the reserve for which the total debt of the user is being calculated + /// @param asset_price The price of the asset for which the total debt of the user is being calculated + /// @param asset_unit The value representing one full unit of the asset (10^decimals) + /// @return The total debt of the user normalized to the base currency fun get_user_debt_in_base_currency( user: address, reserve_data: &ReserveData, asset_price: u256, asset_unit: u256 ): u256 { let user_total_debt = - variable_token_factory::scale_balance_of(user, - pool::get_reserve_variable_debt_token_address(reserve_data)); + variable_debt_token_factory::scaled_balance_of( + user, pool::get_reserve_variable_debt_token_address(reserve_data) + ); if (user_total_debt != 0) { let normalized_debt = pool::get_normalized_debt_by_reserve_data(reserve_data); @@ -203,14 +254,25 @@ module aave_pool::generic_logic { user_total_debt / asset_unit } + /// @notice Calculates total aToken balance of the user in the based currency used by the price oracle + /// @dev For gas reasons, the aToken balance is calculated by fetching `scaledBalancesOf` normalized debt, which + /// is cheaper than fetching `balanceOf` + /// @param user The address of the user + /// @param reserve_data The data of the reserve for which the total aToken balance of the user is being calculated + /// @param asset_price The price of the asset for which the total aToken balance of the user is being calculated + /// @param asset_unit The value representing one full unit of the asset (10^decimals) + /// @return The total aToken balance of the user normalized to the base currency of the price oracle fun get_user_balance_in_base_currency( user: address, reserve_data: &ReserveData, asset_price: u256, asset_unit: u256 ): u256 { let normalized_income = pool::get_normalized_income_by_reserve_data(reserve_data); let balance = - wad_ray_math::ray_mul(a_token_factory::scale_balance_of(user, - pool::get_reserve_a_token_address(reserve_data)), - normalized_income) * asset_price; + wad_ray_math::ray_mul( + a_token_factory::scaled_balance_of( + user, pool::get_reserve_a_token_address(reserve_data) + ), + normalized_income, + ) * asset_price; balance / asset_unit } } diff --git a/aave-core/sources/aave-pool/isolation_mode_logic.move b/aave-core/sources/aave-pool/isolation_mode_logic.move index 88350d4..892b7c5 100644 --- a/aave-core/sources/aave-pool/isolation_mode_logic.move +++ b/aave-core/sources/aave-pool/isolation_mode_logic.move @@ -11,42 +11,63 @@ module aave_pool::isolation_mode_logic { friend aave_pool::liquidation_logic; #[event] + /// @dev Emitted on borrow(), repay() and liquidation_call() when using isolated assets + /// @param asset The address of the underlying asset of the reserve + /// @param total_debt The total isolation mode debt for the reserve struct IsolationModeTotalDebtUpdated has store, drop { asset: address, total_debt: u256, } + /// @notice updated the isolated debt whenever a position collateralized by an isolated asset is repaid or liquidated + /// @param user_config_map The user configuration map + /// @param reserve_data The reserve data + /// @param repay_amount The amount being repaid public(friend) fun update_isolated_debt_if_isolated( - user_config_map: &UserConfigurationMap, reserve_data: &ReserveData, repay_amount: u256 + user_config_map: &UserConfigurationMap, + reserve_data: &ReserveData, + repay_amount: u256 ) { - let (isolation_mode_active, isolation_mode_collateral_address, _) = pool::get_isolation_mode_state(user_config_map); + let (isolation_mode_active, isolation_mode_collateral_address, _) = + pool::get_isolation_mode_state(user_config_map); if (isolation_mode_active) { - let isolation_mode_debt_reserve_data = pool::get_reserve_data( - isolation_mode_collateral_address); + let isolation_mode_debt_reserve_data = + pool::get_reserve_data(isolation_mode_collateral_address); let isolation_mode_total_debt = - pool::get_reserve_isolation_mode_total_debt(&isolation_mode_debt_reserve_data); - let reserve_config_map = pool::get_reserve_configuration_by_reserve_data( - reserve_data); + pool::get_reserve_isolation_mode_total_debt( + &isolation_mode_debt_reserve_data + ); + let reserve_config_map = + pool::get_reserve_configuration_by_reserve_data(reserve_data); let debt_decimals = - reserve_config::get_decimals(&reserve_config_map) - reserve_config::get_debt_ceiling_decimals(); + reserve_config::get_decimals(&reserve_config_map) + - reserve_config::get_debt_ceiling_decimals(); let isolated_debt_repaid = (repay_amount / math_utils::pow(10, debt_decimals)); + // since the debt ceiling does not take into account the interest accrued, it might happen that amount + // repaid > debt in isolation mode if (isolation_mode_total_debt <= (isolated_debt_repaid as u128)) { - pool::set_reserve_isolation_mode_total_debt(isolation_mode_collateral_address, 0); - event::emit(IsolationModeTotalDebtUpdated { + pool::set_reserve_isolation_mode_total_debt( + isolation_mode_collateral_address, 0 + ); + event::emit( + IsolationModeTotalDebtUpdated { asset: isolation_mode_collateral_address, total_debt: 0 - }) + }, + ) } else { - let next_isolation_mode_total_debt = isolation_mode_total_debt - ( - isolated_debt_repaid as u128 + let next_isolation_mode_total_debt = + isolation_mode_total_debt - (isolated_debt_repaid as u128); + pool::set_reserve_isolation_mode_total_debt( + isolation_mode_collateral_address, next_isolation_mode_total_debt ); - pool::set_reserve_isolation_mode_total_debt(isolation_mode_collateral_address, - next_isolation_mode_total_debt); - event::emit(IsolationModeTotalDebtUpdated { + event::emit( + IsolationModeTotalDebtUpdated { asset: isolation_mode_collateral_address, total_debt: (next_isolation_mode_total_debt as u256) - }) + }, + ) } } } diff --git a/aave-core/sources/aave-pool/pool.move b/aave-core/sources/aave-pool/pool.move index 5b68826..048770d 100644 --- a/aave-core/sources/aave-pool/pool.move +++ b/aave-core/sources/aave-pool/pool.move @@ -15,8 +15,8 @@ module aave_pool::pool { use aave_pool::a_token_factory; use aave_pool::default_reserve_interest_rate_strategy; - use aave_pool::underlying_token_factory; - use aave_pool::variable_token_factory; + use aave_pool::mock_underlying_token_factory; + use aave_pool::variable_debt_token_factory; friend aave_pool::pool_configurator; friend aave_pool::flashloan_logic; @@ -32,6 +32,10 @@ module aave_pool::pool { const POOL_REVISION: u256 = 0x1; #[event] + /// @dev Emitted when a reserve is initialized. + /// @param asset The address of the underlying asset of the reserve + /// @param a_token The address of the associated aToken contract + /// @param variable_debt_token The address of the associated variable rate debt token struct ReserveInitialized has store, drop { // Address of the underlying asset asset: address, @@ -42,6 +46,12 @@ module aave_pool::pool { } #[event] + /// @dev Emitted when the state of a reserve is updated. + /// @param reserve The address of the underlying asset of the reserve + /// @param liquidity_rate The next liquidity rate + /// @param variable_borrow_rate The next variable borrow rate + /// @param liquidity_index The next liquidity index + /// @param variable_borrow_index The next variable borrow index struct ReserveDataUpdated has store, drop { reserve: address, liquidity_rate: u256, @@ -51,20 +61,29 @@ module aave_pool::pool { } #[event] + /// @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest. + /// @param reserve The address of the reserve + /// @param amount_minted The amount minted to the treasury struct MintedToTreasury has store, drop { reserve: address, - amountMinted: u256, + amount_minted: u256, } #[event] + /// @dev Emitted on borrow(), repay() and liquidation_call() when using isolated assets + /// @param asset The address of the underlying asset of the reserve + /// @param totalDebt The total isolation mode debt for the reserve struct IsolationModeTotalDebtUpdated has store, drop { asset: address, total_debt: u256, } struct ReserveExtendConfiguration has key, store, drop { + /// Fee of the protocol bridge, expressed in bps bridge_protocol_fee: u256, + /// Total FlashLoan Premium, expressed in bps flash_loan_premium_total: u128, + /// FlashLoan premium paid to protocol treasury, expressed in bps flash_loan_premium_to_protocol: u128, } @@ -95,37 +114,51 @@ module aave_pool::pool { isolation_mode_total_debt: u128, } + /// Map of reserves and their data (underlying_asset_of_reserve => reserveData) struct ReserveList has key { - // SmartTable to store reserve data with asset addresses as keys + /// SmartTable to store reserve data with asset addresses as keys value: SmartTable, - // Count of reserves in the list + /// Maximum number of active reserves there have been in the protocol. It is the upper bound of the reserves list count: u16, } - // List of reserves as a map (reserveId => reserve). + /// List of reserves as a map (reserveId => reserve). + /// It is structured as a mapping for gas savings reasons, using the reserve id as index struct ReserveAddressesList has key { value: SmartTable, } - // Map of users address and their configuration data (userAddress => userConfiguration) + /// Map of users address and their configuration data (user_address => UserConfigurationMap) struct UsersConfig has key { value: SmartTable, } + /// @notice init pool public(friend) fun init_pool(account: &signer) { - assert!((signer::address_of(account) == @aave_pool), - error_config::get_ecaller_not_pool_admin()); - move_to(account, - ReserveList { value: smart_table::new(), count: 0, }); - move_to(account, ReserveAddressesList { value: smart_table::new(), }); - move_to(account, - UsersConfig { value: smart_table::new(), }); - move_to(account, + assert!( + (signer::address_of(account) == @aave_pool), + error_config::get_ecaller_not_pool_admin(), + ); + move_to( + account, + ReserveList { value: smart_table::new(), count: 0, }, + ); + move_to( + account, + ReserveAddressesList { value: smart_table::new(), }, + ); + move_to( + account, + UsersConfig { value: smart_table::new(), }, + ); + move_to( + account, ReserveExtendConfiguration { bridge_protocol_fee: 0, flash_loan_premium_total: 0, flash_loan_premium_to_protocol: 0, - }); + }, + ); } #[test_only] @@ -134,10 +167,24 @@ module aave_pool::pool { } #[view] + /// @notice Returns the revision number of the contract + /// @dev Needs to be defined in the inherited class as a constant. + /// @return The revision number public fun get_revision(): u256 { POOL_REVISION } + /// @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an + /// interest rate strategy + /// @dev Only callable by the pool_configurator contract + /// @param account The address of the caller + /// @param underlying_asset The address of the underlying asset of the reserve + /// @param underlying_asset_decimals The decimals of the underlying asset + /// @param treasury The address of the treasury + /// @param a_token_name The name of the aToken + /// @param a_token_symbol The symbol of the aToken + /// @param variable_debt_token_name The name of the variable debt token + /// @param variable_debt_token_symbol The symbol of the variable debt token public(friend) fun init_reserve( account: &signer, underlying_asset: address, @@ -149,14 +196,21 @@ module aave_pool::pool { variable_debt_token_symbol: String, ) acquires ReserveList, ReserveAddressesList { // Check if underlying_asset exists - underlying_token_factory::assert_token_exists(underlying_asset); + mock_underlying_token_factory::assert_token_exists(underlying_asset); + + // Check whether the asset interest rate parameters are configured + default_reserve_interest_rate_strategy::asset_interest_rate_exists( + underlying_asset + ); // Borrow the ReserveList resource let reserve_data_list = borrow_global_mut(@aave_pool); // Assert that the asset is not already added - assert!(!smart_table::contains(&reserve_data_list.value, underlying_asset), - error_config::get_ereserve_already_added()); + assert!( + !smart_table::contains(&reserve_data_list.value, underlying_asset), + error_config::get_ereserve_already_added(), + ); // Create a token for the underlying asset a_token_factory::create_token( @@ -169,10 +223,11 @@ module aave_pool::pool { underlying_asset, treasury, ); - let a_token_address = a_token_factory::token_address(signer::address_of(account),a_token_symbol); + let a_token_address = + a_token_factory::token_address(signer::address_of(account), a_token_symbol); // Create variable debt token for the underlying asset - variable_token_factory::create_token( + variable_debt_token_factory::create_token( account, variable_debt_token_name, variable_debt_token_symbol, @@ -181,23 +236,26 @@ module aave_pool::pool { utf8(b""), underlying_asset, ); - let variable_debt_token_address = variable_token_factory::token_address(signer::address_of(account), variable_debt_token_symbol); + let variable_debt_token_address = + variable_debt_token_factory::token_address( + signer::address_of(account), variable_debt_token_symbol + ); // Create Pool let reserve_data = ReserveData { - configuration: reserve_config::init(), - liquidity_index: (wad_ray_math::ray() as u128), - current_liquidity_rate: 0, - variable_borrow_index: (wad_ray_math::ray() as u128), - current_variable_borrow_rate: 0, - last_update_timestamp: 0, - id: 0, - a_token_address, - variable_debt_token_address, - accrued_to_treasury: 0, - unbacked: 0, - isolation_mode_total_debt: 0, - }; + configuration: reserve_config::init(), + liquidity_index: (wad_ray_math::ray() as u128), + current_liquidity_rate: 0, + variable_borrow_index: (wad_ray_math::ray() as u128), + current_variable_borrow_rate: 0, + last_update_timestamp: 0, + id: 0, + a_token_address, + variable_debt_token_address, + accrued_to_treasury: 0, + unbacked: 0, + isolation_mode_total_debt: 0, + }; // Add the ReserveData in the smart table smart_table::add(&mut reserve_data_list.value, underlying_asset, reserve_data); @@ -206,25 +264,34 @@ module aave_pool::pool { let reserve_count = reserve_data_list.count; // Reorder assets for (i in 0..reserve_count) { - let reserve_address_list = borrow_global_mut(@aave_pool); + let reserve_address_list = + borrow_global_mut(@aave_pool); if (!smart_table::contains(&reserve_address_list.value, (i as u256))) { // update reserve id - set_reserve_id(reserve_data_list,underlying_asset, (i as u16)); + set_reserve_id(reserve_data_list, underlying_asset, (i as u16)); // update reserve address list - add_reserve_address_list(reserve_address_list, (i as u256), underlying_asset); + add_reserve_address_list( + reserve_address_list, (i as u256), underlying_asset + ); flag = true; }; }; if (!flag) { // Assert that the maximum number of reserves hasn't been reached - assert!(reserve_count < max_number_reserves(), error_config::get_eno_more_reserves_allowed()); + assert!( + reserve_count < max_number_reserves(), + error_config::get_eno_more_reserves_allowed(), + ); // update reserve id set_reserve_id(reserve_data_list, underlying_asset, reserve_count); - let reserve_address_list = borrow_global_mut(@aave_pool); + let reserve_address_list = + borrow_global_mut(@aave_pool); // update reserve address list - add_reserve_address_list(reserve_address_list, (reserve_count as u256), underlying_asset); + add_reserve_address_list( + reserve_address_list, (reserve_count as u256), underlying_asset + ); // Update the reserve count reserve_data_list.count = reserve_data_list.count + 1; @@ -232,18 +299,22 @@ module aave_pool::pool { // Set the reserve configuration let reserve_configuration = reserve_config::init(); - reserve_config::set_decimals(&mut reserve_configuration, (underlying_asset_decimals as u256)); + reserve_config::set_decimals( + &mut reserve_configuration, (underlying_asset_decimals as u256) + ); reserve_config::set_active(&mut reserve_configuration, true); reserve_config::set_paused(&mut reserve_configuration, false); reserve_config::set_frozen(&mut reserve_configuration, false); set_reserve_configuration(underlying_asset, reserve_configuration); // emit the ReserveInitialized event - event::emit(ReserveInitialized { - asset: underlying_asset, - a_token: a_token_address, - variable_debt_token: variable_debt_token_address, - }) + event::emit( + ReserveInitialized { + asset: underlying_asset, + a_token: a_token_address, + variable_debt_token: variable_debt_token_address, + }, + ) } #[test_only] @@ -265,22 +336,30 @@ module aave_pool::pool { a_token_name, a_token_symbol, variable_debt_token_name, - variable_debt_token_symbol + variable_debt_token_symbol, ); } + /// @notice Drop a reserve + /// @dev Only callable by the pool_configurator contract + /// @param asset The address of the underlying asset of the reserve public(friend) fun drop_reserve(asset: address) acquires ReserveList, ReserveAddressesList { assert!(asset != @0x0, error_config::get_ezero_address_not_valid()); // check if the asset is listed let reserve_data = get_reserve_data(asset); - let variable_debt_token_total_supply = scale_variable_token_total_supply(reserve_data.variable_debt_token_address); - assert!(variable_debt_token_total_supply == 0, error_config::get_evariable_debt_supply_not_zero()); + let variable_debt_token_total_supply = + scaled_variable_token_total_supply(reserve_data.variable_debt_token_address); + assert!( + variable_debt_token_total_supply == 0, + error_config::get_evariable_debt_supply_not_zero(), + ); - let a_token_total_supply = scale_a_token_total_supply(reserve_data.a_token_address); + let a_token_total_supply = + scaled_a_token_total_supply(reserve_data.a_token_address); assert!( a_token_total_supply == 0 && reserve_data.accrued_to_treasury == 0, - error_config::get_eunderlying_claimable_rights_not_zero() + error_config::get_eunderlying_claimable_rights_not_zero(), ); // Borrow the ReserveList resource @@ -291,34 +370,46 @@ module aave_pool::pool { // Remove ReserveAddressList let reserve_address_list = borrow_global_mut(@aave_pool); if (smart_table::contains(&reserve_address_list.value, (reserve_data.id as u256))) { - smart_table::remove(&mut reserve_address_list.value, (reserve_data.id as u256)); + smart_table::remove( + &mut reserve_address_list.value, (reserve_data.id as u256) + ); }; // assert assets count in storage - assert!(smart_table::length(&reserve_address_list.value) - == smart_table::length(&reserve_data_list.value), - error_config::get_ereserves_storage_count_mismatch()); + assert!( + smart_table::length(&reserve_address_list.value) + == smart_table::length(&reserve_data_list.value), + error_config::get_ereserves_storage_count_mismatch(), + ); } #[test_only] - public fun test_drop_reserve(asset: address, ) acquires ReserveList, ReserveAddressesList { + public fun test_drop_reserve(asset: address,) acquires ReserveList, ReserveAddressesList { drop_reserve(asset); } #[view] + /// @notice Returns the state and configuration of the reserve + /// @param asset The address of the underlying asset of the reserve + /// @return The state and configuration data of the reserve public fun get_reserve_data(asset: address): ReserveData acquires ReserveList { // Get the signer address let signer_address = @aave_pool; // Assert that the signer has created a list - assert!(exists(signer_address), error_config::get_euser_not_listed()); + assert!( + exists(signer_address), + error_config::get_eaccount_does_not_exist(), + ); // Get the ReserveList resource let reserve_list = borrow_global(signer_address); // Assert that the asset is listed - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); // Borrow the ReserveData for the specified asset let reserve_data = @@ -329,7 +420,7 @@ module aave_pool::pool { } #[view] - public fun get_reserve_data_and_reserves_count(asset: address, ): (ReserveData, u256) acquires ReserveList { + public fun get_reserve_data_and_reserves_count(asset: address,): (ReserveData, u256) acquires ReserveList { // Get the signer address let signer_address = @aave_pool; @@ -340,8 +431,10 @@ module aave_pool::pool { let reserve_list = borrow_global(signer_address); // Assert that the asset is listed - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); // Borrow the ReserveData for the specified asset let reserve_data = @@ -352,10 +445,15 @@ module aave_pool::pool { } #[view] + /// @notice Returns the configuration of the reserve + /// @param asset The address of the underlying asset of the reserve + /// @return The configuration of the reserve public fun get_reserve_configuration(asset: address): ReserveConfigurationMap acquires ReserveList { let reserve_list = borrow_global(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_info = smart_table::borrow(&reserve_list.value, asset); reserve_info.configuration @@ -378,11 +476,10 @@ module aave_pool::pool { } fun set_reserve_id( - reserve_list: &mut ReserveList, - asset:address, - id: u16 - ) { - let reserve_data = smart_table::borrow_mut(&mut reserve_list.value, asset); + reserve_list: &mut ReserveList, asset: address, id: u16 + ) { + let reserve_data = + smart_table::borrow_mut(&mut reserve_list.value, asset); reserve_data.id = id } @@ -390,10 +487,14 @@ module aave_pool::pool { asset: address, last_update_timestamp: u64 ) acquires ReserveList { let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_data = - smart_table::borrow_mut(&mut reserve_list.value, asset); + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); reserve_data.last_update_timestamp = last_update_timestamp } @@ -409,10 +510,14 @@ module aave_pool::pool { asset: address, accrued_to_treasury: u256 ) acquires ReserveList { let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_data = - smart_table::borrow_mut(&mut reserve_list.value, asset); + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); reserve_data.accrued_to_treasury = accrued_to_treasury } @@ -424,10 +529,14 @@ module aave_pool::pool { asset: address, variable_borrow_index: u128 ) acquires ReserveList { let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_data = - smart_table::borrow_mut(&mut reserve_list.value, asset); + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); reserve_data.variable_borrow_index = variable_borrow_index } @@ -435,12 +544,18 @@ module aave_pool::pool { reserve.variable_borrow_index } - fun set_reserve_liquidity_index(asset: address, liquidity_index: u128) acquires ReserveList { + fun set_reserve_liquidity_index( + asset: address, liquidity_index: u128 + ) acquires ReserveList { let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_data = - smart_table::borrow_mut(&mut reserve_list.value, asset); + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); reserve_data.liquidity_index = liquidity_index } @@ -452,10 +567,14 @@ module aave_pool::pool { asset: address, current_liquidity_rate: u128 ) acquires ReserveList { let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_data = - smart_table::borrow_mut(&mut reserve_list.value, asset); + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); reserve_data.current_liquidity_rate = current_liquidity_rate } @@ -467,10 +586,14 @@ module aave_pool::pool { asset: address, current_variable_borrow_rate: u128 ) acquires ReserveList { let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_data = - smart_table::borrow_mut(&mut reserve_list.value, asset); + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); reserve_data.current_variable_borrow_rate = current_variable_borrow_rate } @@ -486,13 +609,20 @@ module aave_pool::pool { reserve.variable_debt_token_address } - public(friend) fun set_reserve_unbacked(asset: address, unbacked: u128) acquires ReserveList { + public(friend) fun set_reserve_unbacked( + asset: address, reserve_data_mut: &mut ReserveData, unbacked: u128 + ) acquires ReserveList { let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_data = - smart_table::borrow_mut(&mut reserve_list.value, asset); - reserve_data.unbacked = unbacked + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); + reserve_data.unbacked = unbacked; + reserve_data_mut.unbacked = unbacked } public fun get_reserve_unbacked(reserve: &ReserveData): u128 { @@ -503,26 +633,40 @@ module aave_pool::pool { asset: address, isolation_mode_total_debt: u128 ) acquires ReserveList { let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_data = - smart_table::borrow_mut(&mut reserve_list.value, asset); + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); reserve_data.isolation_mode_total_debt = isolation_mode_total_debt } - public fun get_reserve_isolation_mode_total_debt(reserve: &ReserveData): u128 { + public fun get_reserve_isolation_mode_total_debt( + reserve: &ReserveData + ): u128 { reserve.isolation_mode_total_debt } + /// @notice Sets the configuration bitmap of the reserve as a whole + /// @dev Only callable by the pool_configurator and pool contract + /// @param asset The address of the underlying asset of the reserve + /// @param reserve_config_map The new configuration bitmap public(friend) fun set_reserve_configuration( asset: address, reserve_config_map: ReserveConfigurationMap ) acquires ReserveList { let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_info = - smart_table::borrow_mut(&mut reserve_list.value, asset); + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); reserve_info.configuration = reserve_config_map; } @@ -552,29 +696,39 @@ module aave_pool::pool { } #[view] + /// @notice Returns the normalized income of the reserve + /// @param asset The address of the underlying asset of the reserve + /// @return The reserve's normalized income public fun get_reserve_normalized_income(asset: address): u256 acquires ReserveList { let reserve_data = get_reserve_data(asset); - let last_update_timestamp = reserve_data.last_update_timestamp; - if (last_update_timestamp == timestamp::now_seconds()) { - return (reserve_data.liquidity_index as u256) - }; - wad_ray_math::ray_mul(math_utils::calculate_linear_interest( - (reserve_data.current_liquidity_rate as u256), last_update_timestamp, ), - (reserve_data.liquidity_index as u256)) + + get_normalized_income_by_reserve_data(&reserve_data) } + /// @notice Returns the ongoing normalized income for the reserve. + /// @dev A value of 1e27 means there is no income. As time passes, the income is accrued + /// @dev A value of 2*1e27 means for each unit of asset one unit of income has been accrued + /// @param reserve_data The reserve object + /// @return The normalized income, expressed in ray public fun get_normalized_income_by_reserve_data( reserve_data: &ReserveData ): u256 { let last_update_timestamp = reserve_data.last_update_timestamp; if (last_update_timestamp == timestamp::now_seconds()) { + //if the index was updated in the same block, no need to perform any calculation return (reserve_data.liquidity_index as u256) }; - wad_ray_math::ray_mul(math_utils::calculate_linear_interest( - (reserve_data.current_liquidity_rate as u256), last_update_timestamp, ), - (reserve_data.liquidity_index as u256)) + wad_ray_math::ray_mul( + math_utils::calculate_linear_interest( + (reserve_data.current_liquidity_rate as u256), last_update_timestamp + ), + (reserve_data.liquidity_index as u256), + ) } + /// @notice Updates the liquidity cumulative index and the variable borrow index. + /// @param asset The address of the underlying asset of the reserve + /// @param reserve_data The reserve data public(friend) fun update_state( asset: address, reserve_data: &mut ReserveData, ) acquires ReserveList { @@ -587,85 +741,126 @@ module aave_pool::pool { set_reserve_last_update_timestamp(asset, reserve_data.last_update_timestamp) } - inline fun update_indexes(asset: address, reserve_data: &mut ReserveData, ) { + /// @notice Updates the reserve indexes and the timestamp of the update. + /// @param asset The address of the underlying asset of the reserve + /// @param reserve_data The reserve data reserve to be updated + inline fun update_indexes( + asset: address, reserve_data: &mut ReserveData, + ) { if (reserve_data.current_liquidity_rate != 0) { let cumulated_liquidity_interest = math_utils::calculate_linear_interest( - (reserve_data.current_liquidity_rate as u256), reserve_data.last_update_timestamp); + (reserve_data.current_liquidity_rate as u256), + reserve_data.last_update_timestamp, + ); let next_liquidity_index = - (wad_ray_math::ray_mul(cumulated_liquidity_interest, (reserve_data.liquidity_index as u256)) as u128); + ( + wad_ray_math::ray_mul( + cumulated_liquidity_interest, + (reserve_data.liquidity_index as u256), + ) as u128 + ); reserve_data.liquidity_index = next_liquidity_index; set_reserve_liquidity_index(asset, next_liquidity_index) }; let curr_scaled_variable_debt = - variable_token_factory::scale_total_supply(reserve_data.variable_debt_token_address); + variable_debt_token_factory::scaled_total_supply( + reserve_data.variable_debt_token_address + ); if (curr_scaled_variable_debt != 0) { let cumulated_variable_borrow_interest = - math_utils::calculate_compounded_interest( + math_utils::calculate_compounded_interest_now( (reserve_data.current_variable_borrow_rate as u256), reserve_data.last_update_timestamp, - timestamp::now_seconds()); + ); let next_variable_borrow_index = - (wad_ray_math::ray_mul( - cumulated_variable_borrow_interest, - (reserve_data.variable_borrow_index as u256) - ) as u128); + ( + wad_ray_math::ray_mul( + cumulated_variable_borrow_interest, + (reserve_data.variable_borrow_index as u256), + ) as u128 + ); reserve_data.variable_borrow_index = next_variable_borrow_index; set_reserve_variable_borrow_index(asset, next_variable_borrow_index) } } + /// @notice Mints part of the repaid interest to the reserve treasury as a function of the reserve factor for the + /// specific asset. + /// @param asset The address of the underlying asset of the reserve + /// @param reserve_data The reserve data to be updated inline fun accrue_to_treasury( asset: address, reserve_data: &mut ReserveData, ) { - let reserve_factor = reserve_config::get_reserve_factor(&reserve_data.configuration); + let reserve_factor = + reserve_config::get_reserve_factor(&reserve_data.configuration); if (reserve_factor != 0) { let curr_scaled_variable_debt = - variable_token_factory::scale_total_supply(reserve_data.variable_debt_token_address); + variable_debt_token_factory::scaled_total_supply( + reserve_data.variable_debt_token_address + ); let prev_total_variable_debt = - wad_ray_math::ray_mul(curr_scaled_variable_debt, (reserve_data.variable_borrow_index as u256)); + wad_ray_math::ray_mul( + curr_scaled_variable_debt, + (reserve_data.variable_borrow_index as u256), + ); let curr_total_variable_debt = - wad_ray_math::ray_mul(curr_scaled_variable_debt, (reserve_data.variable_borrow_index as u256), ); + wad_ray_math::ray_mul( + curr_scaled_variable_debt, + (reserve_data.variable_borrow_index as u256), + ); let total_debt_accrued = curr_total_variable_debt - prev_total_variable_debt; - let amount_to_mint = math_utils::percent_mul(total_debt_accrued, reserve_factor); + let amount_to_mint = + math_utils::percent_mul(total_debt_accrued, reserve_factor); if (amount_to_mint != 0) { - reserve_data.accrued_to_treasury = reserve_data.accrued_to_treasury + wad_ray_math::ray_div( - amount_to_mint, (reserve_data.liquidity_index as u256)); + reserve_data.accrued_to_treasury = reserve_data.accrued_to_treasury + + wad_ray_math::ray_div( + amount_to_mint, (reserve_data.liquidity_index as u256) + ); set_reserve_accrued_to_treasury(asset, reserve_data.accrued_to_treasury) } } } #[view] + /// @notice Returns the normalized variable debt per unit of asset + /// @dev WARNING: This function is intended to be used primarily by the protocol itself to get a + /// "dynamic" variable index based on time, current stored index and virtual rate at the current + /// moment (approx. a borrower would get if opening a position). This means that is always used in + /// combination with variable debt supply/balances. + /// If using this function externally, consider that is possible to have an increasing normalized + /// variable debt that is not equivalent to how the variable debt index would be updated in storage + /// (e.g. only updates with non-zero variable debt supply) + /// @param asset The address of the underlying asset of the reserve + /// @return The reserve normalized variable debt public fun get_reserve_normalized_variable_debt(asset: address): u256 acquires ReserveList { let reserve_data = get_reserve_data(asset); - let last_update_timestamp = reserve_data.last_update_timestamp; - if (last_update_timestamp == timestamp::now_seconds()) { - return (reserve_data.variable_borrow_index as u256) - }; - wad_ray_math::ray_mul(math_utils::calculate_compounded_interest( - (reserve_data.current_variable_borrow_rate as u256), - last_update_timestamp, - timestamp::now_seconds()), - (reserve_data.variable_borrow_index as u256)) + get_normalized_debt_by_reserve_data(&reserve_data) } + /// @notice Returns the ongoing normalized variable debt for the reserve. + /// @dev A value of 1e27 means there is no debt. As time passes, the debt is accrued + /// @dev A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated + /// @param reserve_data The reserve object + /// @return The normalized variable debt, expressed in ray public fun get_normalized_debt_by_reserve_data( reserve_data: &ReserveData ): u256 { let last_update_timestamp = reserve_data.last_update_timestamp; if (last_update_timestamp == timestamp::now_seconds()) { + //if the index was updated in the same block, no need to perform any calculation return (reserve_data.variable_borrow_index as u256) }; - wad_ray_math::ray_mul(math_utils::calculate_compounded_interest( - (reserve_data.current_variable_borrow_rate as u256), - last_update_timestamp, - timestamp::now_seconds()), - (reserve_data.variable_borrow_index as u256)) + wad_ray_math::ray_mul( + math_utils::calculate_compounded_interest_now( + (reserve_data.current_variable_borrow_rate as u256), last_update_timestamp + ), + (reserve_data.variable_borrow_index as u256), + ) } fun add_reserve_address_list( @@ -674,13 +869,18 @@ module aave_pool::pool { if (smart_table::length(&reserve_address_list.value) == 0) { smart_table::add(&mut reserve_address_list.value, index, asset); } else { - assert!(!smart_table::contains(&mut reserve_address_list.value, index), - error_config::get_ereserve_already_added()); + assert!( + !smart_table::contains(&mut reserve_address_list.value, index), + error_config::get_ereserve_already_added(), + ); smart_table::add(&mut reserve_address_list.value, index, asset); } } #[view] + /// @notice Returns the list of the underlying assets of all the initialized reserves + /// @dev It does not include dropped reserves + /// @return The addresses of the underlying assets of the initialized reserves public fun get_reserves_list(): vector
acquires ReserveAddressesList, ReserveList { let reserves_list_count = get_reserves_count(); let dropped_reserves_count = 0; @@ -691,10 +891,13 @@ module aave_pool::pool { let reserve_address_list = borrow_global(@aave_pool); for (i in 0..reserves_list_count) { - if(smart_table::contains(&reserve_address_list.value, i)){ + if (smart_table::contains(&reserve_address_list.value, i)) { let reserve_address = *smart_table::borrow(&reserve_address_list.value, i); - vector::insert(&mut address_list, ((i - dropped_reserves_count) as u64), - reserve_address); + vector::insert( + &mut address_list, + ((i - dropped_reserves_count) as u64), + reserve_address, + ); } else { dropped_reserves_count = dropped_reserves_count + 1; }; @@ -703,6 +906,9 @@ module aave_pool::pool { } #[view] + /// @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the ReserveData struct + /// @param id The id of the reserve as stored in the ReserveData struct + /// @return The address of the reserve associated with id public fun get_reserve_address_by_id(id: u256): address acquires ReserveAddressesList { let reserve_address_list = borrow_global(@aave_pool); if (!smart_table::contains(&reserve_address_list.value, id)) { @@ -712,80 +918,119 @@ module aave_pool::pool { *smart_table::borrow(&reserve_address_list.value, id) } + /// @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens + /// @param assets The list of reserves for which the minting needs to be executed public entry fun mint_to_treasury(assets: vector
) acquires ReserveList { for (i in 0..vector::length(&assets)) { let asset_address = *vector::borrow(&assets, i); let reserve_data = &mut get_reserve_data(asset_address); - let reserve_config_map = get_reserve_configuration_by_reserve_data(reserve_data); - if (!reserve_config::get_active(&reserve_config_map)) { continue }; + let reserve_config_map = + get_reserve_configuration_by_reserve_data(reserve_data); + + // this cover both inactive reserves and invalid reserves since the flag will be 0 for both + if (!reserve_config::get_active(&reserve_config_map)) { + continue + }; let accrued_to_treasury = reserve_data.accrued_to_treasury; if (accrued_to_treasury != 0) { set_reserve_accrued_to_treasury(asset_address, 0); let normalized_income = get_reserve_normalized_income(asset_address); - let amount_to_mint = wad_ray_math::ray_mul(accrued_to_treasury, - normalized_income); - a_token_factory::mint_to_treasury(amount_to_mint, normalized_income, - reserve_data.a_token_address); - event::emit(MintedToTreasury { - reserve: asset_address, - amountMinted: accrued_to_treasury - }); + let amount_to_mint = + wad_ray_math::ray_mul(accrued_to_treasury, normalized_income); + a_token_factory::mint_to_treasury( + amount_to_mint, normalized_income, reserve_data.a_token_address + ); + event::emit( + MintedToTreasury { + reserve: asset_address, + amount_minted: amount_to_mint + }, + ); }; } } #[view] public fun get_bridge_protocol_fee(): u256 acquires ReserveExtendConfiguration { - let reserve_extend_configuration = borrow_global( - @aave_pool); + let reserve_extend_configuration = + borrow_global(@aave_pool); reserve_extend_configuration.bridge_protocol_fee } public(friend) fun set_bridge_protocol_fee(protocol_fee: u256) acquires ReserveExtendConfiguration { - let reserve_extend_configuration = borrow_global_mut( - @aave_pool); + let reserve_extend_configuration = + borrow_global_mut(@aave_pool); reserve_extend_configuration.bridge_protocol_fee = protocol_fee } #[view] public fun get_flashloan_premium_total(): u128 acquires ReserveExtendConfiguration { - let reserve_extend_configuration = borrow_global( - @aave_pool); + let reserve_extend_configuration = + borrow_global(@aave_pool); reserve_extend_configuration.flash_loan_premium_total } - public(friend) fun set_flashloan_premiums( + #[test_only] + public fun set_flashloan_premiums_test( + flash_loan_premium_total: u128, flash_loan_premium_to_protocol: u128 + ) acquires ReserveExtendConfiguration { + update_flashloan_premiums( + flash_loan_premium_total, flash_loan_premium_to_protocol + ) + } + + /// @notice Updates flash loan premiums. Flash loan premium consists of two parts: + /// - A part is sent to aToken holders as extra, one time accumulated interest + /// - A part is collected by the protocol treasury + /// @dev The total premium is calculated on the total borrowed amount + /// @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal` + /// @dev Only callable by the pool_configurator contract + /// @param flash_loan_premium_total The total premium, expressed in bps + /// @param flash_loan_premium_to_protocol The part of the premium sent to the protocol treasury, expressed in bps + public(friend) fun update_flashloan_premiums( flash_loan_premium_total: u128, flash_loan_premium_to_protocol: u128 ) acquires ReserveExtendConfiguration { - let reserve_extend_configuration = borrow_global_mut( - @aave_pool); + let reserve_extend_configuration = + borrow_global_mut(@aave_pool); reserve_extend_configuration.flash_loan_premium_total = flash_loan_premium_total; reserve_extend_configuration.flash_loan_premium_to_protocol = flash_loan_premium_to_protocol } #[view] public fun get_flashloan_premium_to_protocol(): u128 acquires ReserveExtendConfiguration { - let reserve_extend_configuration = borrow_global( - @aave_pool); + let reserve_extend_configuration = + borrow_global(@aave_pool); reserve_extend_configuration.flash_loan_premium_to_protocol } #[view] + /// @notice Returns the maximum number of reserves supported to be listed in this Pool + /// @return The maximum number of reserves supported public fun max_number_reserves(): u16 { reserve_config::get_max_reserves_count() } + /// @notice Updates the reserve the current variable borrow rate and the current liquidity rate. + /// @param reserve_data The reserve data reserve to be updated + /// @param reserve_address The address of the reserve to be updated + /// @param liquidity_added The amount of liquidity added to the protocol (supply or repay) in the previous action + /// @param liquidity_taken The amount of liquidity taken from the protocol (redeem or borrow) public(friend) fun update_interest_rates( reserve_data: &mut ReserveData, reserve_address: address, liquidity_added: u256, liquidity_taken: u256 ) acquires ReserveList { - let variable_token_scale_total_supply = - variable_token_factory::scale_total_supply(reserve_data.variable_debt_token_address); + let variable_token_scaled_total_supply = + variable_debt_token_factory::scaled_total_supply( + reserve_data.variable_debt_token_address + ); let total_variable_debt = - wad_ray_math::ray_mul(variable_token_scale_total_supply, (reserve_data.variable_borrow_index as u256)); + wad_ray_math::ray_mul( + variable_token_scaled_total_supply, + (reserve_data.variable_borrow_index as u256), + ); let (next_liquidity_rate, next_variable_rate) = default_reserve_interest_rate_strategy::calculate_interest_rates( @@ -795,29 +1040,40 @@ module aave_pool::pool { total_variable_debt, reserve_config::get_reserve_factor(&reserve_data.configuration), reserve_address, - reserve_data.a_token_address); + reserve_data.a_token_address, + ); reserve_data.current_liquidity_rate = (next_liquidity_rate as u128); reserve_data.current_variable_borrow_rate = (next_variable_rate as u128); set_reserve_current_liquidity_rate(reserve_address, (next_liquidity_rate as u128)); - set_reserve_current_variable_borrow_rate(reserve_address, (next_variable_rate as u128)); - - event::emit(ReserveDataUpdated { - reserve: reserve_address, - liquidity_rate: next_liquidity_rate, - variable_borrow_rate: next_variable_rate, - liquidity_index: (reserve_data.liquidity_index as u256), - variable_borrow_index: (reserve_data.variable_borrow_index as u256), - }) - } + set_reserve_current_variable_borrow_rate( + reserve_address, (next_variable_rate as u128) + ); + event::emit( + ReserveDataUpdated { + reserve: reserve_address, + liquidity_rate: next_liquidity_rate, + variable_borrow_rate: next_variable_rate, + liquidity_index: (reserve_data.liquidity_index as u256), + variable_borrow_index: (reserve_data.variable_borrow_index as u256), + }, + ) + } + + /// @notice Returns the Isolation Mode state of the user + /// @param user_config_map The configuration of the user + /// @return True if the user is in isolation mode, false otherwise + /// @return The address of the only asset used as collateral + /// @return The debt ceiling of the reserve public fun get_isolation_mode_state( user_config_map: &UserConfigurationMap ): (bool, address, u256) acquires ReserveAddressesList, ReserveList { if (user_config::is_using_as_collateral_one(user_config_map)) { let asset_id: u256 = - user_config::get_first_asset_id_by_mask(user_config_map, - user_config::get_collateral_mask()); + user_config::get_first_asset_id_by_mask( + user_config_map, user_config::get_collateral_mask() + ); let asset_address = get_reserve_address_by_id(asset_id); let reserves_config_map = get_reserve_configuration(asset_address); let ceiling: u256 = reserve_config::get_debt_ceiling(&reserves_config_map); @@ -828,14 +1084,17 @@ module aave_pool::pool { (false, @0x0, 0) } - public fun get_siloed_borrowing_state( - account: address - ): (bool, address) acquires ReserveAddressesList, ReserveList, UsersConfig { + /// @notice Returns the siloed borrowing state for the user + /// @param account The address of the user + /// @return True if the user has borrowed a siloed asset, false otherwise + /// @return The address of the only borrowed asset + public fun get_siloed_borrowing_state(account: address): (bool, address) acquires ReserveAddressesList, ReserveList, UsersConfig { let user_configuration = get_user_configuration(account); if (user_config::is_borrowing_one(&user_configuration)) { let asset_id: u256 = - user_config::get_first_asset_id_by_mask(&user_configuration, - user_config::get_borrowing_mask()); + user_config::get_first_asset_id_by_mask( + &user_configuration, user_config::get_borrowing_mask() + ); let asset_address = get_reserve_address_by_id(asset_id); let reserves_config_map = get_reserve_configuration(asset_address); @@ -850,76 +1109,129 @@ module aave_pool::pool { asset: address, reserve_data: &mut ReserveData, total_liquidity: u256, amount: u256 ): u256 acquires ReserveList { let result = - wad_ray_math::ray_div(wad_ray_math::wad_to_ray(amount), - wad_ray_math::wad_to_ray(total_liquidity)) + wad_ray_math::ray_mul( - wad_ray_math::ray(), (reserve_data.liquidity_index as u256)); + wad_ray_math::ray_mul( + ( + wad_ray_math::ray_div( + wad_ray_math::wad_to_ray(amount), + wad_ray_math::wad_to_ray(total_liquidity), + ) + wad_ray_math::ray() + ), + (reserve_data.liquidity_index as u256), + ); reserve_data.liquidity_index = (result as u128); set_reserve_liquidity_index(asset, reserve_data.liquidity_index); result } + /// @notice Resets the isolation mode total debt of the given asset to zero + /// @dev It requires the given asset has zero debt ceiling + /// @param asset The address of the underlying asset to reset the isolation_mode_total_debt public(friend) fun reset_isolation_mode_total_debt(asset: address) acquires ReserveList { let reserve_config_map = get_reserve_configuration(asset); - assert!(reserve_config::get_debt_ceiling(&reserve_config_map) == 0, - error_config::get_edebt_ceiling_not_zero()); + assert!( + reserve_config::get_debt_ceiling(&reserve_config_map) == 0, + error_config::get_edebt_ceiling_not_zero(), + ); let reserve_list = borrow_global_mut(@aave_pool); - assert!(smart_table::contains(&reserve_list.value, asset), - error_config::get_easset_not_listed()); + assert!( + smart_table::contains(&reserve_list.value, asset), + error_config::get_easset_not_listed(), + ); let reserve_data = - smart_table::borrow_mut(&mut reserve_list.value, asset); + smart_table::borrow_mut( + &mut reserve_list.value, asset + ); reserve_data.isolation_mode_total_debt = 0; event::emit(IsolationModeTotalDebtUpdated { asset, total_debt: 0 }) } + /// @notice Rescue and transfer tokens locked in this contract + /// @param token The address of the token + /// @param to The address of the recipient + /// @param amount The amount of token to transfer public entry fun rescue_tokens( account: &signer, token: address, to: address, amount: u256 ) { - assert!(only_pool_admin(signer::address_of(account)), - error_config::get_ecaller_not_pool_admin()); - underlying_token_factory::transfer_from(signer::address_of(account), to, (amount as u64), - token); + assert!( + only_pool_admin(signer::address_of(account)), + error_config::get_ecaller_not_pool_admin(), + ); + mock_underlying_token_factory::transfer_from( + signer::address_of(account), to, (amount as u64), token + ); } #[view] - public fun scale_a_token_total_supply(a_token_address: address): u256 acquires ReserveList { - let current_supply_scaled = a_token_factory::scale_total_supply(a_token_address); + public fun scaled_a_token_total_supply(a_token_address: address): u256 acquires ReserveList { + let current_supply_scaled = a_token_factory::scaled_total_supply(a_token_address); if (current_supply_scaled == 0) { return 0 }; - let underlying_token_address = a_token_factory::get_underlying_asset_address(a_token_address); - wad_ray_math::ray_mul(current_supply_scaled, get_reserve_normalized_income(underlying_token_address)) + let underlying_token_address = + a_token_factory::get_underlying_asset_address(a_token_address); + wad_ray_math::ray_mul( + current_supply_scaled, + get_reserve_normalized_income(underlying_token_address), + ) } #[view] - public fun scale_a_token_balance_of(owner: address, a_token_address: address): u256 acquires ReserveList { - let current_balance_scale = a_token_factory::scale_balance_of(owner, a_token_address); + public fun scaled_a_token_balance_of( + owner: address, a_token_address: address + ): u256 acquires ReserveList { + let current_balance_scale = + a_token_factory::scaled_balance_of(owner, a_token_address); if (current_balance_scale == 0) { return 0 }; - let underlying_token_address = a_token_factory::get_underlying_asset_address(a_token_address); - wad_ray_math::ray_mul(current_balance_scale, get_reserve_normalized_income(underlying_token_address)) + let underlying_token_address = + a_token_factory::get_underlying_asset_address(a_token_address); + wad_ray_math::ray_mul( + current_balance_scale, + get_reserve_normalized_income(underlying_token_address), + ) } #[view] - public fun scale_variable_token_total_supply(variable_debt_token_address: address): u256 acquires ReserveList{ - let current_supply_scaled = variable_token_factory::scale_total_supply(variable_debt_token_address); + public fun scaled_variable_token_total_supply( + variable_debt_token_address: address + ): u256 acquires ReserveList { + let current_supply_scaled = + variable_debt_token_factory::scaled_total_supply(variable_debt_token_address); if (current_supply_scaled == 0) { return 0 }; - let underlying_token_address = variable_token_factory::get_underlying_asset_address(variable_debt_token_address); + let underlying_token_address = + variable_debt_token_factory::get_underlying_asset_address( + variable_debt_token_address + ); - wad_ray_math::ray_mul(current_supply_scaled, get_reserve_normalized_variable_debt(underlying_token_address)) + wad_ray_math::ray_mul( + current_supply_scaled, + get_reserve_normalized_variable_debt(underlying_token_address), + ) } #[view] - public fun scale_variable_token_balance_of(owner: address, variable_debt_token_address: address): u256 acquires ReserveList { - let current_balance_scale = variable_token_factory::scale_balance_of(owner, variable_debt_token_address); + public fun scaled_variable_token_balance_of( + owner: address, variable_debt_token_address: address + ): u256 acquires ReserveList { + let current_balance_scale = + variable_debt_token_factory::scaled_balance_of( + owner, variable_debt_token_address + ); if (current_balance_scale == 0) { return 0 }; - let underlying_token_address = variable_token_factory::get_underlying_asset_address(variable_debt_token_address); - wad_ray_math::ray_mul(current_balance_scale, get_reserve_normalized_variable_debt(underlying_token_address)) + let underlying_token_address = + variable_debt_token_factory::get_underlying_asset_address( + variable_debt_token_address + ); + wad_ray_math::ray_mul( + current_balance_scale, + get_reserve_normalized_variable_debt(underlying_token_address), + ) } fun only_pool_admin(admin: address): bool { diff --git a/aave-core/sources/aave-pool/pool_addresses_provider.move b/aave-core/sources/aave-pool/pool_addresses_provider.move index 51d011c..68c9874 100644 --- a/aave-core/sources/aave-pool/pool_addresses_provider.move +++ b/aave-core/sources/aave-pool/pool_addresses_provider.move @@ -81,11 +81,13 @@ module aave_pool::pool_addresses_provider { fun init_module(account: &signer) { assert!(signer::address_of(account) == @aave_pool, ENOT_MANAGEMENT); - move_to(account, + move_to( + account, Provider { market_id: option::none(), addresses: smart_table::new() - }) + }, + ) } fun check_admin(account: address) { @@ -130,7 +132,9 @@ module aave_pool::pool_addresses_provider { option::some(*address) } - public entry fun set_address(account: &signer, id: String, addr: address) acquires Provider { + public entry fun set_address( + account: &signer, id: String, addr: address + ) acquires Provider { check_admin(signer::address_of(account)); let provider = borrow_global_mut(@aave_pool); smart_table::upsert(&mut provider.addresses, id, addr); @@ -141,7 +145,9 @@ module aave_pool::pool_addresses_provider { get_address(string::utf8(POOL)) } - public entry fun set_pool_impl(account: &signer, new_pool_impl: address) acquires Provider { + public entry fun set_pool_impl( + account: &signer, new_pool_impl: address + ) acquires Provider { check_admin(signer::address_of(account)); let old_pool_impl = get_address(string::utf8(POOL)); update_impl(string::utf8(POOL), new_pool_impl); @@ -159,10 +165,12 @@ module aave_pool::pool_addresses_provider { check_admin(signer::address_of(account)); let old_pool_configurator_impl = get_address(string::utf8(POOL_CONFIGURATOR)); update_impl(string::utf8(POOL_CONFIGURATOR), new_pool_configurator_impl); - event::emit(PoolConfiguratorUpdated { + event::emit( + PoolConfiguratorUpdated { old_pool_configurator_impl, new_pool_configurator_impl - }); + }, + ); } #[view] @@ -216,12 +224,15 @@ module aave_pool::pool_addresses_provider { account: &signer, new_price_oracle_sentinel_impl: address ) acquires Provider { check_admin(signer::address_of(account)); - let old_price_oracle_sentinel_impl = get_address(string::utf8(PRICE_ORACLE_SENTINEL)); + let old_price_oracle_sentinel_impl = + get_address(string::utf8(PRICE_ORACLE_SENTINEL)); update_impl(string::utf8(PRICE_ORACLE_SENTINEL), new_price_oracle_sentinel_impl); - event::emit(PriceOracleSentinelUpdated { + event::emit( + PriceOracleSentinelUpdated { old_price_oracle_sentinel_impl, new_price_oracle_sentinel_impl - }); + }, + ); } #[view] @@ -235,9 +246,11 @@ module aave_pool::pool_addresses_provider { check_admin(signer::address_of(account)); let old_pool_data_provider_impl = get_address(string::utf8(DATA_PROVIDER)); update_impl(string::utf8(DATA_PROVIDER), new_pool_data_provider_impl); - event::emit(PoolDataProviderUpdated { + event::emit( + PoolDataProviderUpdated { old_pool_data_provider_impl, new_pool_data_provider_impl - }); + }, + ); } } diff --git a/aave-core/sources/aave-pool/pool_configurator.move b/aave-core/sources/aave-pool/pool_configurator.move index a8000fb..8384110 100644 --- a/aave-core/sources/aave-pool/pool_configurator.move +++ b/aave-core/sources/aave-pool/pool_configurator.move @@ -16,18 +16,29 @@ module aave_pool::pool_configurator { const CONFIGURATOR_REVISION: u256 = 0x1; #[event] + /// @dev Emitted when borrowing is enabled or disabled on a reserve. + /// @param asset The address of the underlying asset of the reserve + /// @param enabled True if borrowing is enabled, false otherwise struct ReserveBorrowing has store, drop { asset: address, enabled: bool } #[event] + /// @dev Emitted when flashloans are enabled or disabled on a reserve. + /// @param asset The address of the underlying asset of the reserve + /// @param enabled True if flashloans are enabled, false otherwise struct ReserveFlashLoaning has store, drop { asset: address, enabled: bool } #[event] + /// @dev Emitted when the collateralization risk parameters for the specified asset are updated. + /// @param asset The address of the underlying asset of the reserve + /// @param ltv The loan to value of the asset when used as collateral + /// @param liquidation_threshold The threshold at which loans using this asset as collateral will be considered undercollateralized + /// @param liquidation_bonus The bonus liquidators receive to liquidate this asset struct CollateralConfigurationChanged has store, drop { asset: address, ltv: u256, @@ -36,29 +47,44 @@ module aave_pool::pool_configurator { } #[event] + /// @dev Emitted when a reserve is activated or deactivated + /// @param asset The address of the underlying asset of the reserve + /// @param active True if reserve is active, false otherwise struct ReserveActive has store, drop { asset: address, active: bool } #[event] + /// @dev Emitted when a reserve is frozen or unfrozen + /// @param asset The address of the underlying asset of the reserve + /// @param frozen True if reserve is frozen, false otherwise struct ReserveFrozen has store, drop { asset: address, frozen: bool } #[event] + /// @dev Emitted when a reserve is paused or unpaused + /// @param asset The address of the underlying asset of the reserve + /// @param paused True if reserve is paused, false otherwise struct ReservePaused has store, drop { asset: address, paused: bool } #[event] + /// @dev Emitted when a reserve is dropped. + /// @param asset The address of the underlying asset of the reserve struct ReserveDropped has store, drop { asset: address, } #[event] + /// @dev Emitted when a reserve factor is updated. + /// @param asset The address of the underlying asset of the reserve + /// @param old_reserve_factor The old reserve factor, expressed in bps + /// @param new_reserve_factor The new reserve factor, expressed in bps struct ReserveFactorChanged has store, drop { asset: address, old_reserve_factor: u256, @@ -66,6 +92,10 @@ module aave_pool::pool_configurator { } #[event] + /// @dev Emitted when the borrow cap of a reserve is updated. + /// @param asset The address of the underlying asset of the reserve + /// @param old_borrow_cap The old borrow cap + /// @param new_borrow_cap The new borrow cap struct BorrowCapChanged has store, drop { asset: address, old_borrow_cap: u256, @@ -73,6 +103,10 @@ module aave_pool::pool_configurator { } #[event] + /// @dev Emitted when the supply cap of a reserve is updated. + /// @param asset The address of the underlying asset of the reserve + /// @param old_supply_cap The old supply cap + /// @param new_supply_cap The new supply cap struct SupplyCapChanged has store, drop { asset: address, old_supply_cap: u256, @@ -80,6 +114,10 @@ module aave_pool::pool_configurator { } #[event] + /// @dev Emitted when the liquidation protocol fee of a reserve is updated. + /// @param asset The address of the underlying asset of the reserve + /// @param old_fee The old liquidation protocol fee, expressed in bps + /// @param new_fee The new liquidation protocol fee, expressed in bps struct LiquidationProtocolFeeChanged has store, drop { asset: address, old_fee: u256, @@ -87,6 +125,10 @@ module aave_pool::pool_configurator { } #[event] + /// @dev Emitted when the unbacked mint cap of a reserve is updated. + /// @param asset The address of the underlying asset of the reserve + /// @param old_unbacked_mint_cap The old unbacked mint cap + /// @param new_unbacked_mint_cap The new unbacked mint cap struct UnbackedMintCapChanged has store, drop { asset: address, old_unbacked_mint_cap: u256, @@ -94,6 +136,10 @@ module aave_pool::pool_configurator { } #[event] + /// @dev Emitted when the category of an asset in eMode is changed. + /// @param asset The address of the underlying asset of the reserve + /// @param old_category_id The old eMode asset category + /// @param new_category_id The new eMode asset category struct EModeAssetCategoryChanged has store, drop { asset: address, old_category_id: u256, @@ -101,6 +147,13 @@ module aave_pool::pool_configurator { } #[event] + /// @dev Emitted when a new eMode category is added. + /// @param category_id The new eMode category id + /// @param ltv The ltv for the asset category in eMode + /// @param liquidation_threshold The liquidationThreshold for the asset category in eMode + /// @param liquidation_bonus The liquidationBonus for the asset category in eMode + /// @param oracle The optional address of the price oracle specific for this category + /// @param label A human readable identifier for the category struct EModeCategoryAdded has store, drop { category_id: u8, ltv: u16, @@ -111,13 +164,10 @@ module aave_pool::pool_configurator { } #[event] - struct ReserveInterestRateStrategyChanged has store, drop { - asset: address, - old_rate_strategy: address, - new_rate_strategy: address - } - - #[event] + /// @dev Emitted when the debt ceiling of an asset is set. + /// @param asset The address of the underlying asset of the reserve + /// @param old_debt_ceiling The old debt ceiling + /// @param new_debt_ceiling The new debt ceiling struct DebtCeilingChanged has store, drop { asset: address, old_debt_ceiling: u256, @@ -125,6 +175,10 @@ module aave_pool::pool_configurator { } #[event] + /// @dev Emitted when the the siloed borrowing state for an asset is changed. + /// @param asset The address of the underlying asset of the reserve + /// @param old_state The old siloed borrowing state + /// @param new_state The new siloed borrowing state struct SiloedBorrowingChanged has store, drop { asset: address, old_state: bool, @@ -132,30 +186,43 @@ module aave_pool::pool_configurator { } #[event] + /// @dev Emitted when the bridge protocol fee is updated. + /// @param old_bridge_protocol_fee The old protocol fee, expressed in bps + /// @param new_bridge_protocol_fee The new protocol fee, expressed in bps struct BridgeProtocolFeeUpdated has store, drop { old_bridge_protocol_fee: u256, new_bridge_protocol_fee: u256 } #[event] + /// @dev Emitted when the total premium on flashloans is updated. + /// @param old_flashloan_premium_total The old premium, expressed in bps + /// @param new_flashloan_premium_total The new premium, expressed in bps struct FlashloanPremiumTotalUpdated has store, drop { old_flashloan_premium_total: u128, new_flashloan_premium_total: u128 } #[event] + /// @dev Emitted when the part of the premium that goes to protocol is updated. + /// @param old_flashloan_premium_to_protocol The old premium, expressed in bps + /// @param new_flashloan_premium_to_protocol The new premium, expressed in bps struct FlashloanPremiumToProtocolUpdated has store, drop { old_flashloan_premium_to_protocol: u128, new_flashloan_premium_to_protocol: u128 } #[event] + /// @dev Emitted when the reserve is set as borrowable/non borrowable in isolation mode. + /// @param asset The address of the underlying asset of the reserve + /// @param borrowable True if the reserve is borrowable in isolation, false otherwise struct BorrowableInIsolationChanged has store, drop { asset: address, borrowable: bool } #[view] + /// @notice Returns the revision of the configurator public fun get_revision(): u256 { CONFIGURATOR_REVISION } @@ -165,16 +232,27 @@ module aave_pool::pool_configurator { init_module(account) } - // initialize reserves + /// @notice Initializes the pool configurator fun init_module(account: &signer) { - assert!((signer::address_of(account) == @aave_pool), - error_config::get_ecaller_not_pool_admin()); + assert!( + (signer::address_of(account) == @aave_pool), + error_config::get_ecaller_not_pool_admin(), + ); pool::init_pool(account); emode_logic::init_emode(account); default_reserve_interest_rate_strategy::init_interest_rate_strategy(account); } - // Entry function to init reserves + /// @notice Initializes multiple reserves. + /// @param account The address of the caller + /// @param underlying_asset The list of the underlying assets of the reserves + /// @param underlying_asset_decimals The list of the decimals of the underlying assets + /// @param treasury The list of the treasury addresses of the reserves + /// @param a_token_name The list of the aToken names of the reserves + /// @param a_token_symbol The list of the aToken symbols of the reserves + /// @param variable_debt_token_name The list of the variable debt token names of the reserves + /// @param variable_debt_token_symbol The list of the variable debt token symbols of the reserves + /// @dev The caller needs to be an asset listing or pool admin public entry fun init_reserves( account: &signer, underlying_asset: vector
, @@ -185,8 +263,10 @@ module aave_pool::pool_configurator { variable_debt_token_name: vector, variable_debt_token_symbol: vector, ) { - assert!(only_asset_listing_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_asset_listing_or_pool_admin()); + assert!( + only_asset_listing_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_asset_listing_or_pool_admin(), + ); for (i in 0..vector::length(&underlying_asset)) { pool::init_reserve( account, @@ -196,25 +276,35 @@ module aave_pool::pool_configurator { *vector::borrow(&a_token_name, i), *vector::borrow(&a_token_symbol, i), *vector::borrow(&variable_debt_token_name, i), - *vector::borrow(&variable_debt_token_symbol, i) + *vector::borrow(&variable_debt_token_symbol, i), ); }; } - // Entry function to drop reserves + /// @notice Drops a reserve entirely. + /// @param account The address of the caller + /// @param asset The address of the reserve to drop public entry fun drop_reserve(account: &signer, asset: address,) { - assert!(only_pool_admin(signer::address_of(account)), - error_config::get_ecaller_not_pool_admin()); + assert!( + only_pool_admin(signer::address_of(account)), + error_config::get_ecaller_not_pool_admin(), + ); // Call the `drop_reserve` function in the `pool` module pool::drop_reserve(asset); event::emit(ReserveDropped { asset }); } + /// @notice Configures borrowing on a reserve. + /// @dev Can only be disabled (set to false) + /// @param asset The address of the underlying asset of the reserve + /// @param enabled True if borrowing needs to be enabled, false otherwise public entry fun set_reserve_borrowing( account: &signer, asset: address, enabled: bool ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); reserve_config::set_borrowing_enabled(&mut reserve_config_map, enabled); pool::set_reserve_configuration(asset, reserve_config_map); @@ -222,6 +312,13 @@ module aave_pool::pool_configurator { event::emit(ReserveBorrowing { asset, enabled }) } + /// @notice Configures the reserve collateralization parameters. + /// @dev All the values are expressed in bps. A value of 10000, results in 100.00% + /// @dev The `liquidation_bonus` is always above 100%. A value of 105% means the liquidator will receive a 5% bonus + /// @param asset The address of the underlying asset of the reserve + /// @param ltv The loan to value of the asset when used as collateral + /// @param liquidation_threshold The threshold at which loans using this asset as collateral will be considered undercollateralized + /// @param liquidation_bonus The bonus liquidators receive to liquidate this asset public entry fun configure_reserve_as_collateral( account: &signer, asset: address, @@ -229,20 +326,27 @@ module aave_pool::pool_configurator { liquidation_threshold: u256, liquidation_bonus: u256 ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); assert!(ltv <= liquidation_threshold, error_config::get_einvalid_reserve_params()); let reserve_config_map = pool::get_reserve_configuration(asset); if (liquidation_threshold != 0) { //liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less //collateral than needed to cover the debt - assert!(liquidation_bonus > math_utils::get_percentage_factor(), - error_config::get_einvalid_reserve_params()); + assert!( + liquidation_bonus > math_utils::get_percentage_factor(), + error_config::get_einvalid_reserve_params(), + ); //if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment //a loan is taken there is enough collateral available to cover the liquidation bonus - assert!(math_utils::percent_mul(liquidation_threshold, liquidation_bonus) <= math_utils::get_percentage_factor(), - error_config::get_einvalid_reserve_params()); + assert!( + math_utils::percent_mul(liquidation_threshold, liquidation_bonus) + <= math_utils::get_percentage_factor(), + error_config::get_einvalid_reserve_params(), + ); } else { assert!(liquidation_bonus == 0, error_config::get_einvalid_reserve_params()); //if the liquidation threshold is being set to 0, @@ -252,25 +356,33 @@ module aave_pool::pool_configurator { }; reserve_config::set_ltv(&mut reserve_config_map, ltv); - reserve_config::set_liquidation_threshold(&mut reserve_config_map, - liquidation_threshold); + reserve_config::set_liquidation_threshold( + &mut reserve_config_map, liquidation_threshold + ); reserve_config::set_liquidation_bonus(&mut reserve_config_map, liquidation_bonus); pool::set_reserve_configuration(asset, reserve_config_map); - event::emit(CollateralConfigurationChanged { + event::emit( + CollateralConfigurationChanged { asset, ltv, liquidation_threshold, liquidation_bonus - }) + }, + ) } + /// @notice Enable or disable flashloans on a reserve + /// @param asset The address of the underlying asset of the reserve + /// @param enabled True if flashloans need to be enabled, false otherwise public entry fun set_reserve_flash_loaning( account: &signer, asset: address, enabled: bool ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); reserve_config::set_flash_loan_enabled(&mut reserve_config_map, enabled); @@ -279,11 +391,16 @@ module aave_pool::pool_configurator { event::emit(ReserveFlashLoaning { asset, enabled }) } + /// @notice Activate or deactivate a reserve + /// @param asset The address of the underlying asset of the reserve + /// @param active True if the reserve needs to be active, false otherwise public entry fun set_reserve_active( account: &signer, asset: address, active: bool ) { - assert!(only_pool_admin(signer::address_of(account)), - error_config::get_ecaller_not_pool_admin()); + assert!( + only_pool_admin(signer::address_of(account)), + error_config::get_ecaller_not_pool_admin(), + ); if (!active) { check_no_suppliers(asset); }; @@ -295,11 +412,17 @@ module aave_pool::pool_configurator { event::emit(ReserveActive { asset, active }) } + /// @notice Freeze or unfreeze a reserve. A frozen reserve doesn't allow any new supply, borrow + /// or rate swap but allows repayments, liquidations, rate rebalances and withdrawals. + /// @param asset The address of the underlying asset of the reserve + /// @param freeze True if the reserve needs to be frozen, false otherwise public entry fun set_reserve_freeze( account: &signer, asset: address, freeze: bool ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); reserve_config::set_frozen(&mut reserve_config_map, freeze); @@ -308,11 +431,20 @@ module aave_pool::pool_configurator { event::emit(ReserveFrozen { asset, frozen: freeze }) } + /// @notice Sets the borrowable in isolation flag for the reserve. + /// @dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the + /// borrowed amount will be accumulated in the isolated collateral's total debt exposure + /// @dev Only assets of the same family (e.g. USD stablecoins) should be borrowable in isolation mode to keep + /// consistency in the debt ceiling calculations + /// @param asset The address of the underlying asset of the reserve + /// @param borrowable True if the asset should be borrowable in isolation, false otherwise public entry fun set_borrowable_in_isolation( account: &signer, asset: address, borrowable: bool ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); reserve_config::set_borrowable_in_isolation(&mut reserve_config_map, borrowable); @@ -321,11 +453,17 @@ module aave_pool::pool_configurator { event::emit(BorrowableInIsolationChanged { asset, borrowable }) } + /// @notice Pauses a reserve. A paused reserve does not allow any interaction (supply, borrow, repay, + /// swap interest rate, liquidate, atoken transfers). + /// @param asset The address of the underlying asset of the reserve + /// @param paused True if pausing the reserve, false if unpausing public entry fun set_reserve_pause( account: &signer, asset: address, paused: bool ) { - assert!(only_pool_or_emergency_admin(signer::address_of(account)), - error_config::get_ecaller_not_pool_or_emergency_admin()); + assert!( + only_pool_or_emergency_admin(signer::address_of(account)), + error_config::get_ecaller_not_pool_or_emergency_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); reserve_config::set_paused(&mut reserve_config_map, paused); @@ -334,16 +472,24 @@ module aave_pool::pool_configurator { event::emit(ReservePaused { asset, paused }) } + /// @notice Updates the reserve factor of a reserve. + /// @param asset The address of the underlying asset of the reserve + /// @param new_reserve_factor The new reserve factor of the reserve public entry fun set_reserve_factor( account: &signer, asset: address, new_reserve_factor: u256 ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); - assert!(new_reserve_factor <= math_utils::get_percentage_factor(), - error_config::get_einvalid_reserve_factor()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); + assert!( + new_reserve_factor <= math_utils::get_percentage_factor(), + error_config::get_einvalid_reserve_factor(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); - let old_reserve_factor: u256 = reserve_config::get_reserve_factor(&reserve_config_map); + let old_reserve_factor: u256 = + reserve_config::get_reserve_factor(&reserve_config_map); reserve_config::set_reserve_factor(&mut reserve_config_map, new_reserve_factor); pool::set_reserve_configuration(asset, reserve_config_map); @@ -351,13 +497,18 @@ module aave_pool::pool_configurator { event::emit(ReserveFactorChanged { asset, old_reserve_factor, new_reserve_factor }) } + /// @notice Sets the debt ceiling for an asset. + /// @param new_debt_ceiling The new debt ceiling public entry fun set_debt_ceiling( account: &signer, asset: address, new_debt_ceiling: u256 ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); - let old_debt_ceiling: u256 = reserve_config::get_debt_ceiling(&reserve_config_map); + let old_debt_ceiling: u256 = + reserve_config::get_debt_ceiling(&reserve_config_map); if (old_debt_ceiling == 0) { check_no_suppliers(asset); }; @@ -370,11 +521,15 @@ module aave_pool::pool_configurator { event::emit(DebtCeilingChanged { asset, old_debt_ceiling, new_debt_ceiling }) } + /// @notice Sets siloed borrowing for an asset + /// @param new_siloed The new siloed borrowing state public entry fun set_siloed_borrowing( account: &signer, asset: address, new_siloed: bool ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); if (new_siloed) { check_no_borrowers(asset); }; @@ -383,14 +538,21 @@ module aave_pool::pool_configurator { reserve_config::set_siloed_borrowing(&mut reserve_config_map, new_siloed); pool::set_reserve_configuration(asset, reserve_config_map); - event::emit(SiloedBorrowingChanged { asset, old_state: old_siloed, new_state: new_siloed }) + event::emit( + SiloedBorrowingChanged { asset, old_state: old_siloed, new_state: new_siloed } + ) } + /// @notice Updates the borrow cap of a reserve. + /// @param asset The address of the underlying asset of the reserve + /// @param new_borrow_cap The new borrow cap of the reserve public entry fun set_borrow_cap( account: &signer, asset: address, new_borrow_cap: u256 ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); let old_borrow_cap: u256 = reserve_config::get_borrow_cap(&reserve_config_map); @@ -401,11 +563,16 @@ module aave_pool::pool_configurator { event::emit(BorrowCapChanged { asset, old_borrow_cap, new_borrow_cap }) } + /// @notice Updates the supply cap of a reserve. + /// @param asset The address of the underlying asset of the reserve + /// @param new_supply_cap The new supply cap of the reserve public entry fun set_supply_cap( account: &signer, asset: address, new_supply_cap: u256 ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); let old_supply_cap: u256 = reserve_config::get_supply_cap(&reserve_config_map); @@ -416,13 +583,20 @@ module aave_pool::pool_configurator { event::emit(SupplyCapChanged { asset, old_supply_cap, new_supply_cap }) } + /// @notice Updates the liquidation protocol fee of reserve. + /// @param asset The address of the underlying asset of the reserve + /// @param new_fee The new liquidation protocol fee of the reserve, expressed in bps public entry fun set_liquidation_protocol_fee( account: &signer, asset: address, new_fee: u256 ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); - assert!(new_fee <= math_utils::get_percentage_factor(), - error_config::get_einvalid_liquidation_protocol_fee()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); + assert!( + new_fee <= math_utils::get_percentage_factor(), + error_config::get_einvalid_liquidation_protocol_fee(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); let old_fee: u256 = @@ -434,6 +608,17 @@ module aave_pool::pool_configurator { event::emit(LiquidationProtocolFeeChanged { asset, old_fee, new_fee }) } + /// @notice Adds a new efficiency mode (eMode) category. + /// @dev If zero is provided as oracle address, the default asset oracles will be used to compute the overall debt and + /// overcollateralization of the users using this category. + /// @dev The new ltv and liquidation threshold must be greater than the base + /// ltvs and liquidation thresholds of all assets within the eMode category + /// @param category_id The id of the category to be configured + /// @param ltv The ltv associated with the category + /// @param liquidation_threshold The liquidation threshold associated with the category + /// @param liquidation_bonus The liquidation bonus associated with the category + /// @param oracle The oracle associated with the category + /// @param label A label identifying the category public entry fun set_emode_category( account: &signer, category_id: u8, @@ -443,171 +628,255 @@ module aave_pool::pool_configurator { oracle: address, label: String ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); assert!(ltv != 0, error_config::get_einvalid_emode_category_params()); - assert!(liquidation_threshold != 0, - error_config::get_einvalid_emode_category_params()); + assert!( + liquidation_threshold != 0, error_config::get_einvalid_emode_category_params() + ); // validation of the parameters: the LTV can // only be lower or equal than the liquidation threshold // (otherwise a loan against the asset would cause instantaneous liquidation) - assert!(ltv <= liquidation_threshold, - error_config::get_einvalid_emode_category_params()); + assert!( + ltv <= liquidation_threshold, + error_config::get_einvalid_emode_category_params(), + ); - assert!(liquidation_bonus > (math_utils::get_percentage_factor() as u16), - error_config::get_einvalid_emode_category_params()); + assert!( + liquidation_bonus > (math_utils::get_percentage_factor() as u16), + error_config::get_einvalid_emode_category_params(), + ); // if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment // a loan is taken there is enough collateral available to cover the liquidation bonus - assert!(math_utils::percent_mul((liquidation_threshold as u256), (liquidation_bonus as u256)) - <= math_utils::get_percentage_factor(), - error_config::get_einvalid_emode_category_params()); + assert!( + math_utils::percent_mul( + (liquidation_threshold as u256), (liquidation_bonus as u256) + ) <= math_utils::get_percentage_factor(), + error_config::get_einvalid_emode_category_params(), + ); let reserves = pool::get_reserves_list(); for (i in 0..vector::length(&reserves)) { - let reserve_config_map = pool::get_reserve_configuration(*vector::borrow(&reserves, i)); - if ((category_id as u256) == reserve_config::get_emode_category(&reserve_config_map)) { - assert!((ltv as u256) > reserve_config::get_ltv(&reserve_config_map), - error_config::get_einvalid_emode_category_params()); - assert!((liquidation_threshold as u256) > reserve_config::get_liquidation_threshold(&reserve_config_map), - error_config::get_einvalid_emode_category_params()); + let reserve_config_map = + pool::get_reserve_configuration(*vector::borrow(&reserves, i)); + if ((category_id as u256) + == reserve_config::get_emode_category(&reserve_config_map)) { + assert!( + (ltv as u256) > reserve_config::get_ltv(&reserve_config_map), + error_config::get_einvalid_emode_category_params(), + ); + assert!( + (liquidation_threshold as u256) + > reserve_config::get_liquidation_threshold( + &reserve_config_map + ), + error_config::get_einvalid_emode_category_params(), + ); }; }; - emode_logic::configure_emode_category(category_id, + emode_logic::configure_emode_category( + category_id, ltv, liquidation_threshold, liquidation_bonus, oracle, - label); + label, + ); - event::emit(EModeCategoryAdded { + event::emit( + EModeCategoryAdded { category_id, ltv, liquidation_threshold, liquidation_bonus, oracle, label - }) + }, + ) } + /// @notice Assign an efficiency mode (eMode) category to asset. + /// @param asset The address of the underlying asset of the reserve + /// @param new_category_id The new category id of the asset public entry fun set_asset_emode_category( account: &signer, asset: address, new_category_id: u8 ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); if (new_category_id != 0) { let emode_category = emode_logic::get_emode_category_data(new_category_id); let liquidation_threshold = emode_logic::get_emode_category_liquidation_threshold(&emode_category); - assert!(liquidation_threshold > (reserve_config::get_liquidation_threshold(&reserve_config_map) as u16), - error_config::get_einvalid_emode_category_assignment()); + assert!( + liquidation_threshold + > ( + reserve_config::get_liquidation_threshold(&reserve_config_map) as u16 + ), + error_config::get_einvalid_emode_category_assignment(), + ); }; let old_category_id = reserve_config::get_emode_category(&reserve_config_map); - reserve_config::set_emode_category(&mut reserve_config_map, (new_category_id as u256)); + reserve_config::set_emode_category( + &mut reserve_config_map, (new_category_id as u256) + ); pool::set_reserve_configuration(asset, reserve_config_map); - event::emit(EModeAssetCategoryChanged { + event::emit( + EModeAssetCategoryChanged { asset, old_category_id, new_category_id: (new_category_id as u256) - }) + }, + ) } + /// @notice Updates the unbacked mint cap of reserve. + /// @param asset The address of the underlying asset of the reserve + /// @param new_unbacked_mint_cap The new unbacked mint cap of the reserve public entry fun set_unbacked_mint_cap( account: &signer, asset: address, new_unbacked_mint_cap: u256 ) { - assert!(only_risk_or_pool_admins(signer::address_of(account)), - error_config::get_ecaller_not_risk_or_pool_admin()); + assert!( + only_risk_or_pool_admins(signer::address_of(account)), + error_config::get_ecaller_not_risk_or_pool_admin(), + ); let reserve_config_map = pool::get_reserve_configuration(asset); - let old_unbacked_mint_cap: u256 = reserve_config::get_unbacked_mint_cap(&reserve_config_map); + let old_unbacked_mint_cap: u256 = + reserve_config::get_unbacked_mint_cap(&reserve_config_map); - reserve_config::set_unbacked_mint_cap(&mut reserve_config_map, new_unbacked_mint_cap); + reserve_config::set_unbacked_mint_cap( + &mut reserve_config_map, new_unbacked_mint_cap + ); pool::set_reserve_configuration(asset, reserve_config_map); - event::emit(UnbackedMintCapChanged { - asset, - old_unbacked_mint_cap, - new_unbacked_mint_cap - }) + event::emit( + UnbackedMintCapChanged { asset, old_unbacked_mint_cap, new_unbacked_mint_cap }, + ) } + /// @notice Pauses or unpauses all the protocol reserves. In the paused state all the protocol interactions + /// are suspended. + /// @param paused True if protocol needs to be paused, false otherwise public entry fun set_pool_pause(account: &signer, paused: bool) { - assert!(only_emergency_admin(signer::address_of(account)), - error_config::get_ecaller_not_emergency_admin()); + assert!( + only_emergency_admin(signer::address_of(account)), + error_config::get_ecaller_not_emergency_admin(), + ); let reserves_address = pool::get_reserves_list(); for (i in 0..vector::length(&reserves_address)) { set_reserve_pause(account, *vector::borrow(&reserves_address, i), paused); }; } + /// @notice Updates the protocol fee on the bridging + /// @param new_bridge_protocol_fee The part of the premium sent to the protocol treasury public entry fun update_bridge_protocol_fee( account: &signer, new_bridge_protocol_fee: u256 ) { - assert!(only_pool_admin(signer::address_of(account)), - error_config::get_ecaller_not_pool_admin()); - - assert!(new_bridge_protocol_fee <= math_utils::get_percentage_factor(), - error_config::get_ebridge_protocol_fee_invalid()); + assert!( + only_pool_admin(signer::address_of(account)), + error_config::get_ecaller_not_pool_admin(), + ); + + assert!( + new_bridge_protocol_fee <= math_utils::get_percentage_factor(), + error_config::get_ebridge_protocol_fee_invalid(), + ); let old_bridge_protocol_fee = pool::get_bridge_protocol_fee(); pool::set_bridge_protocol_fee(new_bridge_protocol_fee); - event::emit(BridgeProtocolFeeUpdated { - old_bridge_protocol_fee, - new_bridge_protocol_fee - }); + event::emit( + BridgeProtocolFeeUpdated { old_bridge_protocol_fee, new_bridge_protocol_fee } + ); } + /// @notice Updates the total flash loan premium. + /// Total flash loan premium consists of two parts: + /// - A part is sent to aToken holders as extra balance + /// - A part is collected by the protocol reserves + /// @dev Expressed in bps + /// @dev The premium is calculated on the total amount borrowed + /// @param new_flashloan_premium_total The total flashloan premium public entry fun update_flashloan_premium_total( account: &signer, new_flashloan_premium_total: u128 ) { - assert!(only_pool_admin(signer::address_of(account)), - error_config::get_ecaller_not_pool_admin()); + assert!( + only_pool_admin(signer::address_of(account)), + error_config::get_ecaller_not_pool_admin(), + ); - assert!(new_flashloan_premium_total <= (math_utils::get_percentage_factor() as u128), - error_config::get_eflashloan_premium_invalid()); + assert!( + new_flashloan_premium_total <= (math_utils::get_percentage_factor() as u128), + error_config::get_eflashloan_premium_invalid(), + ); let old_flashloan_premium_total = pool::get_flashloan_premium_total(); - pool::set_flashloan_premiums(new_flashloan_premium_total, - pool::get_flashloan_premium_to_protocol()); - event::emit(FlashloanPremiumTotalUpdated { + pool::update_flashloan_premiums( + new_flashloan_premium_total, pool::get_flashloan_premium_to_protocol() + ); + event::emit( + FlashloanPremiumTotalUpdated { old_flashloan_premium_total, new_flashloan_premium_total - }); + }, + ); } + /// @notice Updates the flash loan premium collected by protocol reserves + /// @dev Expressed in bps + /// @dev The premium to protocol is calculated on the total flashloan premium + /// @param new_flashloan_premium_to_protocol The part of the flashloan premium sent to the protocol treasury public entry fun update_flashloan_premium_to_protocol( account: &signer, new_flashloan_premium_to_protocol: u128 ) { - assert!(only_pool_admin(signer::address_of(account)), - error_config::get_ecaller_not_pool_admin()); - assert!(new_flashloan_premium_to_protocol <= (math_utils::get_percentage_factor() as u128), - error_config::get_eflashloan_premium_invalid()); + assert!( + only_pool_admin(signer::address_of(account)), + error_config::get_ecaller_not_pool_admin(), + ); + assert!( + new_flashloan_premium_to_protocol + <= (math_utils::get_percentage_factor() as u128), + error_config::get_eflashloan_premium_invalid(), + ); let old_flashloan_premium_to_protocol = pool::get_flashloan_premium_to_protocol(); - pool::set_flashloan_premiums(pool::get_flashloan_premium_total(), - new_flashloan_premium_to_protocol); - event::emit(FlashloanPremiumToProtocolUpdated { + pool::update_flashloan_premiums( + pool::get_flashloan_premium_total(), new_flashloan_premium_to_protocol + ); + event::emit( + FlashloanPremiumToProtocolUpdated { old_flashloan_premium_to_protocol, new_flashloan_premium_to_protocol - }) + }, + ) } fun check_no_suppliers(asset: address) { let reserve_data = pool::get_reserve_data(asset); let a_token_address = pool::get_reserve_a_token_address(&reserve_data); - let reserve_accrued_to_treasury = pool::get_reserve_accrued_to_treasury(&reserve_data); - let a_token_total_supply = pool::scale_a_token_total_supply(a_token_address); - assert!(a_token_total_supply == 0 && reserve_accrued_to_treasury == 0, - error_config::get_ereserve_liquidity_not_zero()); + let reserve_accrued_to_treasury = + pool::get_reserve_accrued_to_treasury(&reserve_data); + let a_token_total_supply = pool::scaled_a_token_total_supply(a_token_address); + assert!( + a_token_total_supply == 0 && reserve_accrued_to_treasury == 0, + error_config::get_ereserve_liquidity_not_zero(), + ); } fun check_no_borrowers(asset: address) { let reserve_data = pool::get_reserve_data(asset); - let variable_debt_token_address = pool::get_reserve_variable_debt_token_address(&reserve_data); - let total_debt = pool::scale_variable_token_total_supply(variable_debt_token_address); + let variable_debt_token_address = + pool::get_reserve_variable_debt_token_address(&reserve_data); + let total_debt = + pool::scaled_variable_token_total_supply(variable_debt_token_address); assert!(total_debt == 0, error_config::get_ereserve_debt_not_zero()) } @@ -656,9 +925,17 @@ module aave_pool::pool_configurator { set_borrow_cap(account, asset_address, *vector::borrow(&borrow_cap, i)); }; - set_reserve_flash_loaning(account, asset_address, *vector::borrow(&flash_loan_enabled, i)); + set_reserve_flash_loaning( + account, + asset_address, + *vector::borrow(&flash_loan_enabled, i), + ); set_supply_cap(account, asset_address, *vector::borrow(&supply_cap, i)); - set_reserve_factor(account, asset_address, *vector::borrow(&reserve_factor, i)); + set_reserve_factor( + account, + asset_address, + *vector::borrow(&reserve_factor, i), + ); } } } diff --git a/aave-core/sources/aave-pool/pool_data_provider.move b/aave-core/sources/aave-pool/pool_data_provider.move index 44b480a..97a8c95 100644 --- a/aave-core/sources/aave-pool/pool_data_provider.move +++ b/aave-core/sources/aave-pool/pool_data_provider.move @@ -6,26 +6,38 @@ module aave_pool::pool_data_provider { use aave_config::user as user_config; use aave_pool::a_token_factory; + use aave_pool::mock_underlying_token_factory; use aave_pool::pool; - use aave_pool::underlying_token_factory; - use aave_pool::variable_token_factory; + use aave_pool::variable_debt_token_factory; - struct TokenData { + struct TokenData has drop { symbol: String, token_address: address } + #[test_only] + public fun get_reserve_token_symbol(token_data: &TokenData): String { + token_data.symbol + } + + #[test_only] + public fun get_reserve_token_address(token_data: &TokenData): address { + token_data.token_address + } + #[view] public fun get_all_reserves_tokens(): vector { let reserves = pool::get_reserves_list(); let reserves_tokens = vector::empty(); for (i in 0..vector::length(&reserves)) { let reserve_address = *vector::borrow(&reserves, i); - vector::push_back(&mut reserves_tokens, + vector::push_back( + &mut reserves_tokens, TokenData { - symbol: underlying_token_factory::symbol(reserve_address), + symbol: mock_underlying_token_factory::symbol(reserve_address), token_address: reserve_address - }); + }, + ); }; reserves_tokens } @@ -38,11 +50,13 @@ module aave_pool::pool_data_provider { let reserve_address = *vector::borrow(&reserves, i); let reserve_data = pool::get_reserve_data(reserve_address); let a_token_address = pool::get_reserve_a_token_address(&reserve_data); - vector::push_back(&mut a_tokens, + vector::push_back( + &mut a_tokens, TokenData { symbol: a_token_factory::symbol(a_token_address), token_address: a_token_address - }); + }, + ); }; a_tokens } @@ -55,12 +69,15 @@ module aave_pool::pool_data_provider { while (i < vector::length(&reserves)) { let reserve_address = *vector::borrow(&reserves, i); let reserve_data = pool::get_reserve_data(reserve_address); - let var_token_address = pool::get_reserve_variable_debt_token_address(&reserve_data); - vector::push_back(&mut var_tokens, + let var_token_address = + pool::get_reserve_variable_debt_token_address(&reserve_data); + vector::push_back( + &mut var_tokens, TokenData { - symbol: variable_token_factory::symbol(var_token_address), + symbol: variable_debt_token_factory::symbol(var_token_address), token_address: var_token_address - }); + }, + ); i = i + 1 }; @@ -69,15 +86,19 @@ module aave_pool::pool_data_provider { #[view] public fun get_reserve_configuration_data(asset: address) - : (u256, u256, u256, u256, u256, bool, bool, bool, bool) { + : ( + u256, u256, u256, u256, u256, bool, bool, bool, bool + ) { let reserve_configuration = pool::get_reserve_configuration(asset); - let (ltv, liquidation_threshold, liquidation_bonus, decimals, reserve_factor, _) = reserve_config::get_params( - &reserve_configuration); - let (is_active, is_frozen, borrowing_enabled, _) = reserve_config::get_flags(&reserve_configuration); + let (ltv, liquidation_threshold, liquidation_bonus, decimals, reserve_factor, _) = + reserve_config::get_params(&reserve_configuration); + let (is_active, is_frozen, borrowing_enabled, _) = + reserve_config::get_flags(&reserve_configuration); let usage_as_collateral_enabled = liquidation_threshold != 0; - (decimals, + ( + decimals, ltv, liquidation_threshold, liquidation_bonus, @@ -85,7 +106,8 @@ module aave_pool::pool_data_provider { usage_as_collateral_enabled, borrowing_enabled, is_active, - is_frozen) + is_frozen + ) } #[view] @@ -137,15 +159,18 @@ module aave_pool::pool_data_provider { #[view] public fun get_reserve_data(asset: address) - : (u256, u256, u256, u256, u256, u256, u256, u256, u64) { + : ( + u256, u256, u256, u256, u256, u256, u256, u256, u64 + ) { let reserve_data = pool::get_reserve_data(asset); let a_token_address = pool::get_reserve_a_token_address(&reserve_data); - let variable_token_address = pool::get_reserve_variable_debt_token_address(&reserve_data); + let variable_token_address = + pool::get_reserve_variable_debt_token_address(&reserve_data); ( (pool::get_reserve_unbacked(&reserve_data) as u256), pool::get_reserve_accrued_to_treasury(&reserve_data), - pool::scale_a_token_total_supply(a_token_address), - pool::scale_variable_token_total_supply(variable_token_address), + pool::scaled_a_token_total_supply(a_token_address), + pool::scaled_variable_token_total_supply(variable_token_address), (pool::get_reserve_current_liquidity_rate(&reserve_data) as u256), (pool::get_reserve_current_variable_borrow_rate(&reserve_data) as u256), (pool::get_reserve_liquidity_index(&reserve_data) as u256), @@ -159,15 +184,16 @@ module aave_pool::pool_data_provider { let reserve_data = pool::get_reserve_data(asset); let a_token_address = pool::get_reserve_a_token_address(&reserve_data); - pool::scale_a_token_total_supply(a_token_address) + pool::scaled_a_token_total_supply(a_token_address) } #[view] public fun get_total_debt(asset: address): u256 { let reserve_data = pool::get_reserve_data(asset); - let variable_token_address = pool::get_reserve_variable_debt_token_address(&reserve_data); + let variable_token_address = + pool::get_reserve_variable_debt_token_address(&reserve_data); - pool::scale_variable_token_total_supply(variable_token_address) + pool::scaled_variable_token_total_supply(variable_token_address) } #[view] @@ -175,16 +201,23 @@ module aave_pool::pool_data_provider { : (u256, u256, u256, u256, bool) { let reserve_data = pool::get_reserve_data(asset); let a_token_address = pool::get_reserve_a_token_address(&reserve_data); - let variable_token_address = pool::get_reserve_variable_debt_token_address(&reserve_data); - - let current_a_token_balance = pool::scale_a_token_balance_of(user, a_token_address); - let current_variable_debt = pool::scale_variable_token_balance_of(user, variable_token_address); - let scaled_variable_debt = variable_token_factory::scale_balance_of(user, variable_token_address); - let liquidity_rate = (pool::get_reserve_current_liquidity_rate(&reserve_data) as u256); + let variable_token_address = + pool::get_reserve_variable_debt_token_address(&reserve_data); + + let current_a_token_balance = + pool::scaled_a_token_balance_of(user, a_token_address); + let current_variable_debt = + pool::scaled_variable_token_balance_of(user, variable_token_address); + let scaled_variable_debt = + variable_debt_token_factory::scaled_balance_of(user, variable_token_address); + let liquidity_rate = + (pool::get_reserve_current_liquidity_rate(&reserve_data) as u256); let user_configuration = pool::get_user_configuration(user); let usage_as_collateral_enabled = - user_config::is_using_as_collateral(&user_configuration, (pool::get_reserve_id(&reserve_data) as u256)); + user_config::is_using_as_collateral( + &user_configuration, (pool::get_reserve_id(&reserve_data) as u256) + ); ( current_a_token_balance, @@ -198,7 +231,8 @@ module aave_pool::pool_data_provider { #[view] public fun get_reserve_tokens_addresses(asset: address): (address, address) { let reserve_data = pool::get_reserve_data(asset); - (pool::get_reserve_a_token_address(&reserve_data), + ( + pool::get_reserve_a_token_address(&reserve_data), pool::get_reserve_variable_debt_token_address(&reserve_data), ) } diff --git a/aave-core/sources/aave-pool/validation_logic.move b/aave-core/sources/aave-pool/validation_logic.move index 95cf9e9..9fd2d31 100644 --- a/aave-core/sources/aave-pool/validation_logic.move +++ b/aave-core/sources/aave-pool/validation_logic.move @@ -10,6 +10,15 @@ module aave_pool::pool_validation { use aave_pool::generic_logic; use aave_pool::pool::{Self, ReserveData}; + /// @notice Validates the health factor of a user and the ltv of the asset being withdrawn. + /// @param reserves_data The reserve data of reserve + /// @param reserves_count The number of available reserves + /// @param user_config_map the user configuration map + /// @param from The user from which the aTokens are being transferred + /// @param user_emode_category The users active efficiency mode category + /// @param emode_ltv The ltv of the efficiency mode category + /// @param emode_liq_threshold The liquidation threshold of the efficiency mode category + /// @param emode_asset_price The price of the efficiency mode category public fun validate_hf_and_ltv( reserve_data: &mut ReserveData, reserves_count: u256, @@ -21,34 +30,52 @@ module aave_pool::pool_validation { emode_asset_price: u256, ) { let (_, has_zero_ltv_collateral) = - validate_health_factor(reserves_count, + validate_health_factor( + reserves_count, user_config_map, from, user_emode_category, emode_ltv, emode_liq_threshold, - emode_asset_price); - let reserve_configuration = pool::get_reserve_configuration_by_reserve_data( - reserve_data); - assert!(!has_zero_ltv_collateral || reserve_config::get_ltv(&reserve_configuration) == - 0, - error_config::get_eltv_validation_failed()); + emode_asset_price, + ); + let reserve_configuration = + pool::get_reserve_configuration_by_reserve_data(reserve_data); + assert!( + !has_zero_ltv_collateral || reserve_config::get_ltv(&reserve_configuration) == + 0, + error_config::get_eltv_validation_failed(), + ); } + /// @notice Validates if an asset should be automatically activated as collateral in the following actions: supply, + /// transfer, mint unbacked, and liquidate + /// @dev This is used to ensure that isolated assets are not enabled as collateral automatically + /// @param user_config_map the user configuration map + /// @param reserve_config_map The reserve configuration map + /// @return True if the asset can be activated as collateral, false otherwise public fun validate_automatic_use_as_collateral( account: address, user_config_map: &UserConfigurationMap, reserve_config_map: &ReserveConfigurationMap ): bool { if (reserve_config::get_debt_ceiling(reserve_config_map) != 0) { - if (!acl_manage::has_role(string::utf8(user_config::get_isolated_collateral_supplier_role()), - account)) { + // ensures only the ISOLATED_COLLATERAL_SUPPLIER_ROLE can enable collateral as side-effect of an action + if (!acl_manage::has_role( + string::utf8(user_config::get_isolated_collateral_supplier_role()), + account, + )) { return false }; }; return validate_use_as_collateral(user_config_map, reserve_config_map) } + /// @notice Validates the action of activating the asset as collateral. + /// @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode + /// @param user_config_map the user configuration map + /// @param reserve_config_map The reserve configuration map + /// @return True if the asset can be activated as collateral, false otherwise public fun validate_use_as_collateral( user_config_map: &UserConfigurationMap, reserve_config_map: &ReserveConfigurationMap @@ -59,11 +86,22 @@ module aave_pool::pool_validation { if (!user_config::is_using_as_collateral_any(user_config_map)) { return true }; - let (isolation_mode_active, _, _) = pool::get_isolation_mode_state(user_config_map); - (!isolation_mode_active && reserve_config::get_debt_ceiling(reserve_config_map) == - 0) + let (isolation_mode_active, _, _) = + pool::get_isolation_mode_state(user_config_map); + ( + !isolation_mode_active + && reserve_config::get_debt_ceiling(reserve_config_map) == 0 + ) } + /// notice Validates the health factor of a user. + /// @param reserves_count The number of available reserves + /// @param user_config_map the user configuration map + /// @param user The user to validate health factor of + /// @param user_emode_category The users active efficiency mode category + /// @param emode_ltv The ltv of the efficiency mode category + /// @param emode_liq_threshold The liquidation threshold of the efficiency mode category + /// @param emode_asset_price The price of the efficiency mode category public fun validate_health_factor( reserves_count: u256, user_config_map: &UserConfigurationMap, @@ -74,37 +112,55 @@ module aave_pool::pool_validation { emode_asset_price: u256, ): (u256, bool) { let (_, _, _, _, health_factor, has_zero_ltv_collateral) = - generic_logic::calculate_user_account_data(reserves_count, + generic_logic::calculate_user_account_data( + reserves_count, user_config_map, user, user_emode_category, emode_ltv, emode_liq_threshold, - emode_asset_price); - assert!(health_factor >= user_config::get_health_factor_liquidation_threshold(), - error_config::get_ehealth_factor_lower_than_liquidation_threshold()); + emode_asset_price, + ); + assert!( + health_factor >= user_config::get_health_factor_liquidation_threshold(), + error_config::get_ehealth_factor_lower_than_liquidation_threshold(), + ); (health_factor, has_zero_ltv_collateral) } + /// @notice Validates the action of setting efficiency mode. + /// @param user_config_map the user configuration map + /// @param reserves_count The total number of valid reserves + /// @param category_id The id of the category + /// @param liquidation_threshold The liquidation threshold public fun validate_set_user_emode( user_config_map: &UserConfigurationMap, reserves_count: u256, category_id: u8, liquidation_threshold: u16 ) { - assert!(category_id != 0 || liquidation_threshold != 0, - error_config::get_einvalid_emode_category_assignment()); + // category is invalid if the liq threshold is not set + assert!( + category_id != 0 || liquidation_threshold != 0, + error_config::get_einconsistent_emode_category(), + ); + + // eMode can always be enabled if the user hasn't supplied anything if (!user_config::is_empty(user_config_map)) { + // if user is trying to set another category than default we require that + // either the user is not borrowing, or it's borrowing assets of category_id if (category_id != 0) { for (i in 0..reserves_count) { if (user_config::is_borrowing(user_config_map, i)) { let reserve_address = pool::get_reserve_address_by_id(i); - let reserve_configuration = pool::get_reserve_configuration( - reserve_address); - assert!(reserve_config::get_emode_category(&reserve_configuration) - == (category_id as u256), - error_config::get_einconsistent_emode_category()); + let reserve_configuration = + pool::get_reserve_configuration(reserve_address); + assert!( + reserve_config::get_emode_category(&reserve_configuration) + == (category_id as u256), + error_config::get_einconsistent_emode_category(), + ); }; } } diff --git a/aave-core/sources/aave-supply-borrow/borrow_logic.move b/aave-core/sources/aave-supply-borrow/borrow_logic.move index 3625800..b4cb661 100644 --- a/aave-core/sources/aave-supply-borrow/borrow_logic.move +++ b/aave-core/sources/aave-supply-borrow/borrow_logic.move @@ -1,3 +1,6 @@ +/// @title borrow_logic module +/// @author Aave +/// @notice Implements the base logic for all the actions related to borrowing module aave_pool::borrow_logic { use std::signer; use aptos_framework::event; @@ -10,14 +13,23 @@ module aave_pool::borrow_logic { use aave_pool::a_token_factory; use aave_pool::emode_logic; use aave_pool::isolation_mode_logic; + use aave_pool::mock_underlying_token_factory; use aave_pool::pool; - use aave_pool::underlying_token_factory; use aave_pool::validation_logic; - use aave_pool::variable_token_factory; + use aave_pool::variable_debt_token_factory; friend aave_pool::flashloan_logic; #[event] + /// @dev Emitted on borrow() and flashLoan() when debt needs to be opened + /// @param reserve The address of the underlying asset being borrowed + /// @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just + /// initiator of the transaction on flashLoan() + /// @param on_behalf_of The address that will be getting the debt + /// @param amount The amount borrowed out + /// @param interest_rate_mode The rate mode: 2 for Variable + /// @param borrow_rate The numeric rate at which the user has borrowed, expressed in ray + /// @param referral_code The referral code used struct Borrow has store, copy, drop { reserve: address, user: address, @@ -29,6 +41,12 @@ module aave_pool::borrow_logic { } #[event] + /// @dev Emitted on repay() + /// @param reserve The address of the underlying asset of the reserve + /// @param user The beneficiary of the repayment, getting his debt reduced + /// @param repayer The address of the user initiating the repay(), providing the funds + /// @param amount The amount repaid + /// @param use_a_tokens True if the repayment is done using aTokens, `false` if done with underlying asset directly struct Repay has store, drop { reserve: address, user: address, @@ -38,45 +56,89 @@ module aave_pool::borrow_logic { } #[event] + /// @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets + /// @param asset The address of the underlying asset of the reserve + /// @param totalDebt The total isolation mode debt for the reserve struct IsolationModeTotalDebtUpdated has store, drop { asset: address, total_debt: u256, } - // Function to execute borrowing of assets + /// @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower + /// already supplied enough collateral, or he was given enough allowance by a credit delegator on the + /// corresponding debt token VariableDebtToken + /// - E.g. User borrows 100 USDC passing as `on_behalf_of` his own address, receiving the 100 USDC in his wallet + /// and 100 stable/variable debt tokens, depending on the `interest_rate_mode` + /// @param asset The address of the underlying asset to borrow + /// @param amount The amount to be borrowed + /// @param interest_rate_mode The interest rate mode at which the user wants to borrow: 2 for Variable + /// @param referral_code The code used to register the integrator originating the operation, for potential rewards. + /// 0 if the action is executed directly by the user, without any middle-man + /// @param on_behalf_of The address of the user who will receive the debt. Should be the address of the borrower itself + /// calling the function if he wants to borrow against his own collateral, or the address of the credit delegator + /// if he has been given credit delegation allowance public entry fun borrow( account: &signer, asset: address, - on_behalf_of: address, amount: u256, interest_rate_mode: u8, referral_code: u16, + on_behalf_of: address, ) { - internal_borrow(account, asset, on_behalf_of, amount, interest_rate_mode, referral_code, true); + internal_borrow( + account, + asset, + amount, + interest_rate_mode, + referral_code, + on_behalf_of, + true, + ); } + /// @notice Implements the borrow feature. Borrowing allows users that provided collateral to draw liquidity from the + /// Aave protocol proportionally to their collateralization power. For isolated positions, it also increases the + /// isolated debt. + /// @dev Emits the `Borrow()` event + /// @param account The signer account + /// @param asset The address of the underlying asset to borrow + /// @param amount The amount to be borrowed + /// @param interest_rate_mode The interest rate mode at which the user wants to borrow: 2 for Variable + /// @param referral_code The code used to register the integrator originating the operation, for potential rewards. + /// 0 if the action is executed directly by the user, without any middle + /// @param on_behalf_of The address of the user who will receive the debt. Should be the address of the borrower itself + /// calling the function if he wants to borrow against his own collateral, or the address of the credit delegator + /// if he has been given credit delegation allowance + /// @param release_underlying If true, the underlying asset will be transferred to the user, otherwise it will stay public(friend) fun internal_borrow( account: &signer, asset: address, - on_behalf_of: address, amount: u256, interest_rate_mode: u8, referral_code: u16, + on_behalf_of: address, release_underlying: bool, ) { let user = signer::address_of(account); - assert!(user == on_behalf_of, error_config::get_esigner_and_on_behalf_of_no_same()); + assert!( + user == on_behalf_of, error_config::get_esigner_and_on_behalf_of_no_same() + ); - let (reserve_data, reserves_count) = pool::get_reserve_data_and_reserves_count(asset); + let (reserve_data, reserves_count) = + pool::get_reserve_data_and_reserves_count(asset); // update pool state pool::update_state(asset, &mut reserve_data); let user_config_map = pool::get_user_configuration(on_behalf_of); - let (isolation_mode_active, isolation_mode_collateral_address, - isolation_mode_debt_ceiling) = pool::get_isolation_mode_state(&user_config_map); + let ( + isolation_mode_active, + isolation_mode_collateral_address, + isolation_mode_debt_ceiling + ) = pool::get_isolation_mode_state(&user_config_map); // validate borrow - validation_logic::validate_borrow(&reserve_data, + validation_logic::validate_borrow( + &reserve_data, &user_config_map, asset, on_behalf_of, @@ -86,18 +148,23 @@ module aave_pool::borrow_logic { (emode_logic::get_user_emode(on_behalf_of) as u8), isolation_mode_active, isolation_mode_collateral_address, - isolation_mode_debt_ceiling); + isolation_mode_debt_ceiling, + ); - let variable_token_address = pool::get_reserve_variable_debt_token_address(&reserve_data); + let variable_token_address = + pool::get_reserve_variable_debt_token_address(&reserve_data); let is_first_borrowing: bool = - variable_token_factory::scale_balance_of(on_behalf_of, variable_token_address) == - 0; + variable_debt_token_factory::scaled_balance_of( + on_behalf_of, variable_token_address + ) == 0; - variable_token_factory::mint(user, + variable_debt_token_factory::mint( + user, on_behalf_of, amount, (pool::get_reserve_variable_borrow_index(&reserve_data) as u256), - variable_token_address); + variable_token_address, + ); if (is_first_borrowing) { let reserve_id = pool::get_reserve_id(&reserve_data); @@ -106,24 +173,33 @@ module aave_pool::borrow_logic { }; if (isolation_mode_active) { - let isolation_mode_collateral_reserve_data = pool::get_reserve_data( - isolation_mode_collateral_address); + let isolation_mode_collateral_reserve_data = + pool::get_reserve_data(isolation_mode_collateral_address); let isolation_mode_total_debt = - pool::get_reserve_isolation_mode_total_debt(&isolation_mode_collateral_reserve_data); - let reserve_configuration_map = pool::get_reserve_configuration_by_reserve_data( - &reserve_data); + pool::get_reserve_isolation_mode_total_debt( + &isolation_mode_collateral_reserve_data + ); + let reserve_configuration_map = + pool::get_reserve_configuration_by_reserve_data(&reserve_data); let decimals = - reserve_config::get_decimals(&reserve_configuration_map) - reserve_config::get_debt_ceiling_decimals(); + reserve_config::get_decimals(&reserve_configuration_map) + - reserve_config::get_debt_ceiling_decimals(); let next_isolation_mode_total_debt = - (isolation_mode_total_debt as u256) + (amount / math_utils::pow(10, decimals)); + (isolation_mode_total_debt as u256) + ( + amount / math_utils::pow(10, decimals) + ); // update isolation_mode_total_debt - pool::set_reserve_isolation_mode_total_debt(isolation_mode_collateral_address, - (next_isolation_mode_total_debt as u128)); + pool::set_reserve_isolation_mode_total_debt( + isolation_mode_collateral_address, + (next_isolation_mode_total_debt as u128), + ); - event::emit(IsolationModeTotalDebtUpdated { - asset: isolation_mode_collateral_address, - total_debt: next_isolation_mode_total_debt - }); + event::emit( + IsolationModeTotalDebtUpdated { + asset: isolation_mode_collateral_address, + total_debt: next_isolation_mode_total_debt + }, + ); }; // update pool interest rate @@ -131,23 +207,36 @@ module aave_pool::borrow_logic { else { 0 }; pool::update_interest_rates(&mut reserve_data, asset, 0, liquidity_taken); if (release_underlying) { - a_token_factory::transfer_underlying_to(user, amount, - pool::get_reserve_a_token_address(&reserve_data)); + a_token_factory::transfer_underlying_to( + user, amount, pool::get_reserve_a_token_address(&reserve_data) + ); }; // Emit a borrow event - event::emit(Borrow { - reserve: asset, - user, - on_behalf_of, - amount, - interest_rate_mode, - borrow_rate: (pool::get_reserve_current_variable_borrow_rate(&reserve_data) as u256), - referral_code, - }); + event::emit( + Borrow { + reserve: asset, + user, + on_behalf_of, + amount, + interest_rate_mode, + borrow_rate: ( + pool::get_reserve_current_variable_borrow_rate(&reserve_data) as u256 + ), + referral_code, + }, + ); } - // Function to execute repayment of borrowed assets + /// @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned + /// - E.g. User repays 100 USDC, burning 100 variable debt tokens of the `on_behalf_of` address + /// @param asset The address of the borrowed underlying asset previously borrowed + /// @param amount The amount to repay + /// - Send the value math_utils::u256_max() in order to repay the whole debt for `asset` on the specific `debtMode` + /// @param interest_rate_mode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable + /// @param on_behalf_of The address of the user who will get his debt reduced/removed. Should be the address of the + /// user calling the function if he wants to reduce/remove his own debt, or the address of any other + /// other borrower whose debt should be removed public entry fun repay( account: &signer, asset: address, @@ -158,6 +247,18 @@ module aave_pool::borrow_logic { internal_repay(account, asset, amount, interest_rate_mode, on_behalf_of, false) } + /// @notice Implements the repay feature. Repaying transfers the underlying back to the aToken and clears the + /// equivalent amount of debt for the user by burning the corresponding debt token. For isolated positions, it also + /// reduces the isolated debt. + /// @dev Emits the `Repay()` event + /// @param account The signer account + /// @param asset The address of the underlying asset to repay + /// @param amount The amount to be repaid. Can be `math_utils::u256_max()` to repay the whole debt + /// @param interest_rate_mode The interest rate mode at which the user wants to repay: 2 for Variable + /// @param on_behalf_of The address of the user who will repay the debt. Should be the address of the borrower itself + /// calling the function if he wants to repay his own debt, or the address of the credit delegator + /// if he wants to repay the debt of a borrower to whom he has given credit delegation allowance + /// @param use_a_tokens If true, the user wants to repay using aTokens, otherwise he wants to repay using the underlying fun internal_repay( account: &signer, asset: address, @@ -167,83 +268,115 @@ module aave_pool::borrow_logic { use_a_tokens: bool ) { let account_address = signer::address_of(account); - assert!(account_address == on_behalf_of, error_config::get_esigner_and_on_behalf_of_no_same()); + assert!( + account_address == on_behalf_of, + error_config::get_esigner_and_on_behalf_of_no_same(), + ); let reserve_data = pool::get_reserve_data(asset); // update pool state pool::update_state(asset, &mut reserve_data); - let variable_debt_token_address = pool::get_reserve_variable_debt_token_address(&reserve_data); - let variable_debt = pool::scale_variable_token_balance_of(on_behalf_of, variable_debt_token_address); + let variable_debt_token_address = + pool::get_reserve_variable_debt_token_address(&reserve_data); + let variable_debt = + pool::scaled_variable_token_balance_of( + on_behalf_of, variable_debt_token_address + ); // validate repay - validation_logic::validate_repay(account, + validation_logic::validate_repay( + account, &reserve_data, amount, interest_rate_mode, on_behalf_of, - variable_debt); + variable_debt, + ); let payback_amount = variable_debt; + // Allows a user to repay with aTokens without leaving dust from interest. let a_token_address = pool::get_reserve_a_token_address(&reserve_data); if (use_a_tokens && amount == math_utils::u256_max()) { - amount = pool::scale_a_token_balance_of(account_address, a_token_address) + amount = pool::scaled_a_token_balance_of(account_address, a_token_address) }; if (amount < payback_amount) { payback_amount = amount; }; - variable_token_factory::burn( + variable_debt_token_factory::burn( on_behalf_of, payback_amount, (pool::get_reserve_variable_borrow_index(&reserve_data) as u256), - pool::get_reserve_variable_debt_token_address(&reserve_data) + pool::get_reserve_variable_debt_token_address(&reserve_data), ); // update pool interest rate let liquidity_added = if (use_a_tokens) { 0 } - else { payback_amount }; + else { + payback_amount + }; pool::update_interest_rates(&mut reserve_data, asset, liquidity_added, 0); let user_config_map = pool::get_user_configuration(on_behalf_of); // set borrowing if (variable_debt - payback_amount == 0) { - user_config::set_borrowing(&mut user_config_map, (pool::get_reserve_id(&reserve_data) as u256), true); + user_config::set_borrowing( + &mut user_config_map, (pool::get_reserve_id(&reserve_data) as u256), true + ); pool::set_user_configuration(on_behalf_of, user_config_map); }; // update reserve_data.isolation_mode_total_debt field - isolation_mode_logic::update_isolated_debt_if_isolated(&user_config_map, &reserve_data, - payback_amount); + isolation_mode_logic::update_isolated_debt_if_isolated( + &user_config_map, &reserve_data, payback_amount + ); // If you choose to repay with AToken, burn Atoken if (use_a_tokens) { - a_token_factory::burn(account_address, + a_token_factory::burn( + account_address, a_token_factory::get_token_account_address(a_token_address), payback_amount, (pool::get_reserve_liquidity_index(&reserve_data) as u256), - a_token_address); + a_token_address, + ); } else { - underlying_token_factory::transfer_from(account_address, + mock_underlying_token_factory::transfer_from( + account_address, a_token_factory::get_token_account_address(a_token_address), (payback_amount as u64), - asset); - a_token_factory::handle_repayment(account_address, + asset, + ); + a_token_factory::handle_repayment( + account_address, on_behalf_of, payback_amount, - pool::get_reserve_a_token_address(&reserve_data)); + pool::get_reserve_a_token_address(&reserve_data), + ); }; // Emit a Repay event - event::emit(Repay { - reserve: asset, - user: on_behalf_of, - repayer: account_address, - amount: payback_amount, - use_a_tokens, - }); + event::emit( + Repay { + reserve: asset, + user: on_behalf_of, + repayer: account_address, + amount: payback_amount, + use_a_tokens, + }, + ); } + /// @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the + /// equivalent debt tokens + /// - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable debt tokens + /// @dev Passing math_utils::u256_max() as amount will clean up any residual aToken dust balance, if the user aToken + /// balance is not enough to cover the whole debt + /// @param account The signer account + /// @param asset The address of the borrowed underlying asset previously borrowed + /// @param amount The amount to repay + /// @param interest_rate_mode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable public entry fun repay_with_a_tokens( account: &signer, asset: address, amount: u256, interest_rate_mode: u8 ) { diff --git a/aave-core/sources/aave-supply-borrow/liquidation_logic.move b/aave-core/sources/aave-supply-borrow/liquidation_logic.move index ddad9b1..6bb7811 100644 --- a/aave-core/sources/aave-supply-borrow/liquidation_logic.move +++ b/aave-core/sources/aave-supply-borrow/liquidation_logic.move @@ -1,3 +1,6 @@ +/// @title liquidation_logic module +/// @author Aave +/// @notice Implements actions involving management of collateral in the protocol, the main one being the liquidations module aave_pool::liquidation_logic { use std::signer; use aptos_framework::event; @@ -12,25 +15,40 @@ module aave_pool::liquidation_logic { use aave_pool::emode_logic; use aave_pool::generic_logic; use aave_pool::isolation_mode_logic; + use aave_pool::mock_underlying_token_factory; use aave_pool::pool::{Self, ReserveData}; use aave_pool::pool_validation; - use aave_pool::underlying_token_factory; use aave_pool::validation_logic; - use aave_pool::variable_token_factory; + use aave_pool::variable_debt_token_factory; #[event] + /// @dev Emitted on setUserUseReserveAsCollateral() + /// @param reserve The address of the underlying asset of the reserve + /// @param user The address of the user enabling the usage as collateral struct ReserveUsedAsCollateralEnabled has store, drop { reserve: address, user: address } #[event] + /// @dev Emitted on setUserUseReserveAsCollateral() + /// @param reserve The address of the underlying asset of the reserve + /// @param user The address of the user enabling the usage as collateral struct ReserveUsedAsCollateralDisabled has store, drop { reserve: address, user: address } #[event] + /// @dev Emitted when a borrower is liquidated. + /// @param collateral_asset The address of the underlying asset used as collateral, to receive as result of the liquidation + /// @param debt_asset The address of the underlying borrowed asset to be repaid with the liquidation + /// @param user The address of the borrower getting liquidated + /// @param debt_to_cover The debt amount of borrowed `asset` the liquidator wants to cover + /// @param liquidated_collateral_amount The amount of collateral received by the liquidator + /// @param liquidator The address of the liquidator + /// @param receive_a_token True if the liquidators wants to receive the collateral aTokens, `false` if he wants + /// to receive the underlying collateral asset directly struct LiquidationCall has store, drop { collateral_asset: address, debt_asset: address, @@ -41,27 +59,22 @@ module aave_pool::liquidation_logic { receive_a_token: bool } - /** - * @dev Default percentage of borrower's debt to be repaid in a liquidation. - * @dev Percentage applied when the users health factor is above `CLOSE_FACTOR_HF_THRESHOLD` - * Expressed in bps, a value of 0.5e4 results in 50.00% - */ - // 5 * 10 ** 3 + /// @dev Default percentage of borrower's debt to be repaid in a liquidation. + /// @dev Percentage applied when the users health factor is above `CLOSE_FACTOR_HF_THRESHOLD` + /// Expressed in bps, a value of 0.5e4 results in 50.00% + /// 5 * 10 ** 3 const DEFAULT_LIQUIDATION_CLOSE_FACTOR: u256 = 5000; - /** - * @dev Maximum percentage of borrower's debt to be repaid in a liquidation - * @dev Percentage applied when the users health factor is below `CLOSE_FACTOR_HF_THRESHOLD` - * Expressed in bps, a value of 1e4 results in 100.00% - */ - // 1 * 10 ** 4 + + /// @dev Maximum percentage of borrower's debt to be repaid in a liquidation + /// @dev Percentage applied when the users health factor is below `CLOSE_FACTOR_HF_THRESHOLD` + /// Expressed in bps, a value of 1e4 results in 100.00% + /// 1 * 10 ** 4 const MAX_LIQUIDATION_CLOSE_FACTOR: u256 = 10000; - /** - * @dev This constant represents below which health factor value it is possible to liquidate - * an amount of debt corresponding to `MAX_LIQUIDATION_CLOSE_FACTOR`. - * A value of 0.95e18 results in 0.95 - */ - // 0.95 * 10 ** 18 + /// @dev This constant represents below which health factor value it is possible to liquidate + /// an amount of debt corresponding to `MAX_LIQUIDATION_CLOSE_FACTOR`. + /// A value of 0.95e18 results in 0.95 + /// 0.95 * 10 ** 18 const CLOSE_FACTOR_HF_THRESHOLD: u256 = 950000000000000000; struct LiquidationCallLocalVars has drop { @@ -123,6 +136,16 @@ module aave_pool::liquidation_logic { } } + /// @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 + /// - The caller (liquidator) covers `debt_to_cover` amount of debt of the user getting liquidated, and receives + /// a proportionally amount of the `collateral_asset` plus a bonus to cover market risk + /// @dev Emits the `LiquidationCall()` event + /// @param collateral_asset The address of the underlying asset used as collateral, to receive as result of the liquidation + /// @param debt_asset The address of the underlying borrowed asset to be repaid with the liquidation + /// @param user The address of the borrower getting liquidated + /// @param debt_to_cover The debt amount of borrowed `asset` the liquidator wants to cover + /// @param receive_a_token True if the liquidators wants to receive the collateral aTokens, `false` if he wants + /// to receive the underlying collateral asset directly public entry fun liquidation_call( account: &signer, collateral_asset: address, @@ -135,12 +158,14 @@ module aave_pool::liquidation_logic { let account_address = signer::address_of(account); let vars = create_liquidation_call_local_vars(); let params = - create_execute_liquidation_call_params(reserves_count, + create_execute_liquidation_call_params( + reserves_count, collateral_asset, debt_asset, user, debt_to_cover, - receive_a_token); + receive_a_token, + ); let collateral_reserve = pool::get_reserve_data(collateral_asset); let debt_reserve = pool::get_reserve_data(debt_asset); let user_config_map = pool::get_user_configuration(user); @@ -149,13 +174,15 @@ module aave_pool::liquidation_logic { let (emode_ltv, emode_liq_threshold, emode_asset_price) = emode_logic::get_emode_configuration(params.user_emode_category); let (_, _, _, _, health_factor, _) = - generic_logic::calculate_user_account_data(reserves_count, + generic_logic::calculate_user_account_data( + reserves_count, &user_config_map, user, params.user_emode_category, emode_ltv, emode_liq_threshold, - emode_asset_price); + emode_asset_price, + ); vars.health_factor = health_factor; let (user_variable_debt, user_total_debt, actual_debt_to_liquidate) = @@ -165,24 +192,33 @@ module aave_pool::liquidation_logic { vars.actual_debt_to_liquidate = actual_debt_to_liquidate; // validate liquidation call - validation_logic::validate_liquidation_call(&user_config_map, + validation_logic::validate_liquidation_call( + &user_config_map, &collateral_reserve, &debt_reserve, vars.user_total_debt, - vars.health_factor); + vars.health_factor, + ); // get configuration data - let (collateral_a_token, collateral_price_source, debt_price_source, - liquidation_bonus) = get_configuration_data(&collateral_reserve, ¶ms); + let ( + collateral_a_token, collateral_price_source, debt_price_source, + liquidation_bonus + ) = get_configuration_data(&collateral_reserve, ¶ms); vars.collateral_a_token = collateral_a_token; vars.collateral_price_source = collateral_price_source; vars.debt_price_source = debt_price_source; - vars.user_collateral_balance = pool::scale_a_token_balance_of(params.user, collateral_a_token); + vars.user_collateral_balance = pool::scaled_a_token_balance_of( + params.user, collateral_a_token + ); - let (actual_collateral_to_liquidate, actual_debt_to_liquidate, - liquidation_protocol_fee_amount) = + let ( + actual_collateral_to_liquidate, + actual_debt_to_liquidate, + liquidation_protocol_fee_amount + ) = calculate_available_collateral_to_liquidate( &collateral_reserve, &debt_reserve, @@ -190,55 +226,73 @@ module aave_pool::liquidation_logic { vars.debt_price_source, vars.actual_debt_to_liquidate, vars.user_collateral_balance, - liquidation_bonus); + liquidation_bonus, + ); vars.actual_collateral_to_liquidate = actual_collateral_to_liquidate; vars.actual_debt_to_liquidate = actual_debt_to_liquidate; vars.liquidation_protocol_fee_amount = liquidation_protocol_fee_amount; if (vars.user_total_debt == vars.actual_debt_to_liquidate) { let debt_reserve_id = pool::get_reserve_id(&debt_reserve); - user_config::set_borrowing(&mut user_config_map, (debt_reserve_id as u256), - false); + user_config::set_borrowing( + &mut user_config_map, (debt_reserve_id as u256), false + ); pool::set_user_configuration(params.user, user_config_map); }; + // If the collateral being liquidated is equal to the user balance, + // we set the currency as not being used as collateral anymore if (vars.actual_collateral_to_liquidate + vars.liquidation_protocol_fee_amount - == vars.user_collateral_balance) { + == vars.user_collateral_balance) { let collateral_reserve_id = pool::get_reserve_id(&collateral_reserve); - user_config::set_using_as_collateral(&mut user_config_map, ( - collateral_reserve_id as u256 - ), false); + user_config::set_using_as_collateral( + &mut user_config_map, (collateral_reserve_id as u256), false + ); pool::set_user_configuration(params.user, user_config_map); - event::emit(ReserveUsedAsCollateralDisabled { + event::emit( + ReserveUsedAsCollateralDisabled { reserve: params.collateral_asset, user: params.user - }); + }, + ); }; // burn debt tokens burn_debt_tokens(&debt_reserve, ¶ms, &vars); // update pool interest rates - pool::update_interest_rates(&mut debt_reserve, params.debt_asset, vars.actual_debt_to_liquidate, - 0); + pool::update_interest_rates( + &mut debt_reserve, + params.debt_asset, + vars.actual_debt_to_liquidate, + 0, + ); - isolation_mode_logic::update_isolated_debt_if_isolated(&user_config_map, &debt_reserve, vars - .actual_debt_to_liquidate); + isolation_mode_logic::update_isolated_debt_if_isolated( + &user_config_map, &debt_reserve, vars.actual_debt_to_liquidate + ); if (params.receive_a_token) { liquidate_a_tokens(account, &collateral_reserve, ¶ms, &vars); } else { burn_collateral_a_tokens(account, collateral_reserve, ¶ms, &vars) }; + // Transfer fee to treasury if it is non-zero if (vars.liquidation_protocol_fee_amount != 0) { - let liquidity_index = pool::get_normalized_income_by_reserve_data(&collateral_reserve); + let liquidity_index = + pool::get_normalized_income_by_reserve_data(&collateral_reserve); let scaled_down_liquidation_protocol_fee = - wad_ray_math::ray_div(vars.liquidation_protocol_fee_amount, liquidity_index); + wad_ray_math::ray_div( + vars.liquidation_protocol_fee_amount, liquidity_index + ); - let scaled_down_user_balance = a_token_factory::scale_balance_of(params.user, vars.collateral_a_token); + let scaled_down_user_balance = + a_token_factory::scaled_balance_of(params.user, vars.collateral_a_token); + // To avoid trying to send more aTokens than available on balance, due to 1 wei imprecision if (scaled_down_liquidation_protocol_fee > scaled_down_user_balance) { vars.liquidation_protocol_fee_amount = wad_ray_math::ray_mul( - scaled_down_user_balance, liquidity_index) + scaled_down_user_balance, liquidity_index + ) }; let underlying_asset_address = @@ -251,21 +305,28 @@ module aave_pool::liquidation_logic { a_token_treasury, vars.liquidation_protocol_fee_amount, index, - vars.collateral_a_token + vars.collateral_a_token, ); }; // Transfers the debt asset being repaid to the aToken, where the liquidity is kept let a_token_address = pool::get_reserve_a_token_address(&debt_reserve); - underlying_token_factory::transfer_from(account_address, + mock_underlying_token_factory::transfer_from( + account_address, a_token_factory::get_token_account_address(a_token_address), (vars.actual_debt_to_liquidate as u64), - debt_asset); + debt_asset, + ); - a_token_factory::handle_repayment(account_address, params.user, vars.actual_debt_to_liquidate, - a_token_address); + a_token_factory::handle_repayment( + account_address, + params.user, + vars.actual_debt_to_liquidate, + a_token_address, + ); - event::emit(LiquidationCall { + event::emit( + LiquidationCall { collateral_asset, debt_asset, user, @@ -273,64 +334,49 @@ module aave_pool::liquidation_logic { liquidated_collateral_amount: vars.actual_collateral_to_liquidate, liquidator: account_address, receive_a_token - }); - } - - fun calculate_debt( - reserve_data: &ReserveData, params: &ExecuteLiquidationCallParams, health_factor: u256 - ): (u256, u256, u256) { - let user_variable_debt = pool::scale_variable_token_balance_of( - params.user, - pool::get_reserve_variable_debt_token_address(reserve_data) + }, ); - let user_total_debt = user_variable_debt; - - let close_factor = - if (health_factor > CLOSE_FACTOR_HF_THRESHOLD) { DEFAULT_LIQUIDATION_CLOSE_FACTOR } - else { MAX_LIQUIDATION_CLOSE_FACTOR }; - let max_liquidatable_debt = math_utils::percent_mul(user_total_debt, close_factor); - - let actual_debt_to_liquidate = - if (params.debt_to_cover > max_liquidatable_debt) { max_liquidatable_debt } - else { - params.debt_to_cover - }; - (user_variable_debt, user_total_debt, actual_debt_to_liquidate) } - fun get_configuration_data( - reserve_data: &ReserveData, params: &ExecuteLiquidationCallParams - ): (address, address, address, u256) { - let collateral_a_token = pool::get_reserve_a_token_address(reserve_data); - let collateral_config_map = pool::get_reserve_configuration_by_reserve_data( - reserve_data); - let liquidation_bonus = - reserve_config::get_liquidation_bonus(&collateral_config_map); - - let collateral_price_source = params.collateral_asset; - let debt_price_source = params.debt_asset; - - if (params.user_emode_category != 0) { - let emode_category_data = emode_logic::get_emode_category_data(params.user_emode_category); - let emode_price_source = - emode_logic::get_emode_category_price_source(&emode_category_data); + /// @notice Burns the collateral aTokens and transfers the underlying to the liquidator. + /// @dev The function also updates the state and the interest rate of the collateral reserve. + /// @param collateral_reserve The data of the collateral reserve + /// @param params The additional parameters needed to execute the liquidation function + /// @param vars The executeLiquidationCall() function local vars + fun burn_collateral_a_tokens( + account: &signer, + collateral_reserve: ReserveData, + params: &ExecuteLiquidationCallParams, + vars: &LiquidationCallLocalVars + ) { + // update pool state + pool::update_state(params.collateral_asset, &mut collateral_reserve); - if (emode_logic::is_in_emode_category((params.user_emode_category as u256), - reserve_config::get_emode_category(&collateral_config_map))) { - liquidation_bonus = (emode_logic::get_emode_category_liquidation_bonus(&emode_category_data) as u256); - if (emode_price_source != @0x0) { - collateral_price_source = emode_price_source; - }; - }; + // update pool interest rates + pool::update_interest_rates( + &mut collateral_reserve, + params.collateral_asset, + 0, + vars.actual_collateral_to_liquidate, + ); - // when in eMode, debt will always be in the same eMode category, can skip matching category check - if (emode_price_source != @0x0) { - debt_price_source = emode_price_source; - }; - }; - (collateral_a_token, collateral_price_source, debt_price_source, liquidation_bonus) + // Burn the equivalent amount of aToken, sending the underlying to the liquidator + a_token_factory::burn( + params.user, + signer::address_of(account), + vars.actual_collateral_to_liquidate, + (pool::get_reserve_liquidity_index(&collateral_reserve) as u256), + pool::get_reserve_a_token_address(&collateral_reserve), + ) } + /// @notice Liquidates the user aTokens by transferring them to the liquidator. + /// @dev The function also checks the state of the liquidator and activates the aToken as collateral + /// as in standard transfers if the isolation mode constraints are respected. + /// @param account The liquidator account + /// @param collateral_reserve The data of the collateral reserve + /// @param params The additional parameters needed to execute the liquidation function + /// @param vars The liquidation_call() function local vars fun liquidate_a_tokens( account: &signer, collateral_reserve: &ReserveData, @@ -338,7 +384,8 @@ module aave_pool::liquidation_logic { vars: &LiquidationCallLocalVars ) { let account_address = signer::address_of(account); - let liquidator_previous_a_token_balance = pool::scale_a_token_balance_of(account_address, vars.collateral_a_token); + let liquidator_previous_a_token_balance = + pool::scaled_a_token_balance_of(account_address, vars.collateral_a_token); let underlying_asset_address = a_token_factory::get_underlying_asset_address(vars.collateral_a_token); @@ -348,63 +395,143 @@ module aave_pool::liquidation_logic { account_address, vars.actual_collateral_to_liquidate, index, - vars.collateral_a_token + vars.collateral_a_token, ); if (liquidator_previous_a_token_balance == 0) { let liquidator_config = pool::get_user_configuration(account_address); - let reserve_config_map = pool::get_reserve_configuration_by_reserve_data(collateral_reserve); - if (pool_validation::validate_automatic_use_as_collateral(account_address, &liquidator_config, &reserve_config_map)) { - user_config::set_using_as_collateral(&mut liquidator_config, - (pool::get_reserve_id(collateral_reserve) as u256), true); + let reserve_config_map = + pool::get_reserve_configuration_by_reserve_data(collateral_reserve); + if (pool_validation::validate_automatic_use_as_collateral( + account_address, &liquidator_config, &reserve_config_map + )) { + user_config::set_using_as_collateral( + &mut liquidator_config, + (pool::get_reserve_id(collateral_reserve) as u256), + true, + ); pool::set_user_configuration(account_address, liquidator_config); - event::emit(ReserveUsedAsCollateralEnabled { + event::emit( + ReserveUsedAsCollateralEnabled { reserve: params.collateral_asset, user: account_address - }); + }, + ); }; } } + /// @notice Burns the debt tokens of the user up to the amount being repaid by the liquidator. + /// @dev The function alters the `debt_reserve` state in `vars` to update the debt related data. + /// @param params The additional parameters needed to execute the liquidation function + /// @param vars the liquidation_call() function local vars fun burn_debt_tokens( debt_reserve: &ReserveData, params: &ExecuteLiquidationCallParams, vars: &LiquidationCallLocalVars ) { if (vars.user_variable_debt >= vars.actual_debt_to_liquidate) { - variable_token_factory::burn(params.user, + variable_debt_token_factory::burn( + params.user, vars.actual_debt_to_liquidate, (pool::get_reserve_variable_borrow_index(debt_reserve) as u256), - pool::get_reserve_variable_debt_token_address(debt_reserve)) + pool::get_reserve_variable_debt_token_address(debt_reserve), + ) } else { + // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.user_variable_debt != 0) { - variable_token_factory::burn(params.user, + variable_debt_token_factory::burn( + params.user, vars.user_variable_debt, (pool::get_reserve_variable_borrow_index(debt_reserve) as u256), - pool::get_reserve_variable_debt_token_address(debt_reserve)) + pool::get_reserve_variable_debt_token_address(debt_reserve), + ) } } } - fun burn_collateral_a_tokens( - account: &signer, - collateral_reserve: ReserveData, + /// @notice Calculates the total debt of the user and the actual amount to liquidate depending on the health factor + /// and corresponding close factor. + /// @dev If the Health Factor is below CLOSE_FACTOR_HF_THRESHOLD, the close factor is increased to MAX_LIQUIDATION_CLOSE_FACTOR + /// @param debt_reserve The reserve data object of the debt reserve + /// @param params The additional parameters needed to execute the liquidation function + /// @param health_factor The health factor of the position + /// @return The variable debt of the user + /// @return The total debt of the user + /// @return The actual debt to liquidate as a function of the closeFactor + fun calculate_debt( + debt_reserve: &ReserveData, params: &ExecuteLiquidationCallParams, - vars: &LiquidationCallLocalVars - ) { - // update pool state - pool::update_state(params.collateral_asset, &mut collateral_reserve); + health_factor: u256 + ): (u256, u256, u256) { + let user_variable_debt = + pool::scaled_variable_token_balance_of( + params.user, pool::get_reserve_variable_debt_token_address(debt_reserve) + ); + let user_total_debt = user_variable_debt; - // update pool interest rates - pool::update_interest_rates(&mut collateral_reserve, params.collateral_asset, 0, vars - .actual_collateral_to_liquidate); + let close_factor = + if (health_factor > CLOSE_FACTOR_HF_THRESHOLD) { + DEFAULT_LIQUIDATION_CLOSE_FACTOR + } else { + MAX_LIQUIDATION_CLOSE_FACTOR + }; + let max_liquidatable_debt = math_utils::percent_mul(user_total_debt, close_factor); - // Burn the equivalent amount of aToken, sending the underlying to the liquidator - a_token_factory::burn(params.user, - signer::address_of(account), - vars.actual_collateral_to_liquidate, - (pool::get_reserve_liquidity_index(&collateral_reserve) as u256), - pool::get_reserve_a_token_address(&collateral_reserve),) + let actual_debt_to_liquidate = + if (params.debt_to_cover > max_liquidatable_debt) { + max_liquidatable_debt + } else { + params.debt_to_cover + }; + (user_variable_debt, user_total_debt, actual_debt_to_liquidate) + } + + /// @notice Returns the configuration data for the debt and the collateral reserves. + /// @param collateral_reserve The data of the collateral reserve + /// @param params The additional parameters needed to execute the liquidation function + /// @return The collateral aToken + /// @return The address to use as price source for the collateral + /// @return The address to use as price source for the debt + /// @return The liquidation bonus to apply to the collateral + fun get_configuration_data( + collateral_reserve: &ReserveData, params: &ExecuteLiquidationCallParams + ): (address, address, address, u256) { + let collateral_a_token = pool::get_reserve_a_token_address(collateral_reserve); + let collateral_config_map = + pool::get_reserve_configuration_by_reserve_data(collateral_reserve); + let liquidation_bonus = + reserve_config::get_liquidation_bonus(&collateral_config_map); + + let collateral_price_source = params.collateral_asset; + let debt_price_source = params.debt_asset; + + if (params.user_emode_category != 0) { + let emode_category_data = + emode_logic::get_emode_category_data(params.user_emode_category); + let emode_price_source = + emode_logic::get_emode_category_price_source(&emode_category_data); + + if (emode_logic::is_in_emode_category( + (params.user_emode_category as u256), + reserve_config::get_emode_category(&collateral_config_map), + )) { + liquidation_bonus = ( + emode_logic::get_emode_category_liquidation_bonus( + &emode_category_data + ) as u256 + ); + if (emode_price_source != @0x0) { + collateral_price_source = emode_price_source; + }; + }; + + // when in eMode, debt will always be in the same eMode category, can skip matching category check + if (emode_price_source != @0x0) { + debt_price_source = emode_price_source; + }; + }; + (collateral_a_token, collateral_price_source, debt_price_source, liquidation_bonus) } struct AvailableCollateralToLiquidateLocalVars has drop { @@ -442,6 +569,20 @@ module aave_pool::liquidation_logic { } } + /// @notice Calculates how much of a specific collateral can be liquidated, given + /// a certain amount of debt asset. + /// @dev This function needs to be called after all the checks to validate the liquidation have been performed, + /// otherwise it might fail. + /// @param collateral_reserve The data of the collateral reserve + /// @param debt_reserve The data of the debt reserve + /// @param collateral_asset The address of the underlying asset used as collateral, to receive as result of the liquidation + /// @param debt_asset The address of the underlying borrowed asset to be repaid with the liquidation + /// @param debt_to_cover The debt amount of borrowed `asset` the liquidator wants to cover + /// @param user_collateral_balance The collateral balance for the specific `collateralAsset` of the user being liquidated + /// @param liquidation_bonus The collateral bonus percentage to receive as result of the liquidation + /// @return The maximum amount that is possible to liquidate given all the liquidation constraints (user balance, close factor) + /// @return The amount to repay with the liquidation + /// @return The fee taken from the liquidation bonus amount to be paid to the protocol fun calculate_available_collateral_to_liquidate( collateral_reserve: &ReserveData, debt_reserve: &ReserveData, @@ -457,42 +598,56 @@ module aave_pool::liquidation_logic { let collateral_reserve_config = pool::get_reserve_configuration_by_reserve_data(collateral_reserve); - vars.collateral_decimals = reserve_config::get_decimals(&collateral_reserve_config); - let debt_reserve_config = pool::get_reserve_configuration_by_reserve_data( - debt_reserve); + vars.collateral_decimals = reserve_config::get_decimals( + &collateral_reserve_config + ); + let debt_reserve_config = + pool::get_reserve_configuration_by_reserve_data(debt_reserve); vars.debt_asset_decimals = reserve_config::get_decimals(&debt_reserve_config); vars.collateral_asset_unit = math_utils::pow(10, vars.collateral_decimals); vars.debt_asset_unit = math_utils::pow(10, vars.debt_asset_decimals); vars.liquidation_protocol_fee_percentage = reserve_config::get_liquidation_protocol_fee( - &collateral_reserve_config); - vars.base_collateral = (vars.debt_asset_price * debt_to_cover * vars.collateral_asset_unit) - / (vars.collateral_price * vars.debt_asset_unit); + &collateral_reserve_config + ); + + // This is the base collateral to liquidate based on the given debt to cover + vars.base_collateral = ( + vars.debt_asset_price * debt_to_cover * vars.collateral_asset_unit + ) / (vars.collateral_price * vars.debt_asset_unit); - vars.max_collateral_to_liquidate = math_utils::percent_mul(vars.base_collateral, - liquidation_bonus); + vars.max_collateral_to_liquidate = math_utils::percent_mul( + vars.base_collateral, liquidation_bonus + ); if (vars.max_collateral_to_liquidate > user_collateral_balance) { vars.collateral_amount = user_collateral_balance; vars.debt_amount_needed = math_utils::percent_div( - ((vars.collateral_price * vars.collateral_amount * vars.debt_asset_unit) / ( - vars.debt_asset_price * vars.collateral_asset_unit - )), - liquidation_bonus); + ( + (vars.collateral_price * vars.collateral_amount * vars.debt_asset_unit) + / (vars.debt_asset_price * vars.collateral_asset_unit) + ), + liquidation_bonus, + ); } else { vars.collateral_amount = vars.max_collateral_to_liquidate; vars.debt_amount_needed = debt_to_cover; }; if (vars.liquidation_protocol_fee_percentage != 0) { - vars.bonus_collateral = vars.collateral_amount - math_utils::percent_div(vars.collateral_amount, - liquidation_bonus); - vars.liquidation_protocol_fee = math_utils::percent_mul(vars.bonus_collateral, vars - .liquidation_protocol_fee_percentage); - (vars.collateral_amount - vars.liquidation_protocol_fee, + vars.bonus_collateral = vars.collateral_amount + - math_utils::percent_div(vars.collateral_amount, liquidation_bonus); + vars.liquidation_protocol_fee = math_utils::percent_mul( + vars.bonus_collateral, vars.liquidation_protocol_fee_percentage + ); + ( + vars.collateral_amount - vars.liquidation_protocol_fee, vars.debt_amount_needed, - vars.liquidation_protocol_fee) - } else { (vars.collateral_amount, vars.debt_amount_needed, 0) } + vars.liquidation_protocol_fee + ) + } else { + (vars.collateral_amount, vars.debt_amount_needed, 0) + } } } diff --git a/aave-core/sources/aave-supply-borrow/supply_logic.move b/aave-core/sources/aave-supply-borrow/supply_logic.move index 7e9f373..b8a2dbc 100644 --- a/aave-core/sources/aave-supply-borrow/supply_logic.move +++ b/aave-core/sources/aave-supply-borrow/supply_logic.move @@ -9,12 +9,18 @@ module aave_pool::supply_logic { use aave_pool::a_token_factory; use aave_pool::emode_logic; + use aave_pool::mock_underlying_token_factory; use aave_pool::pool; use aave_pool::pool_validation; - use aave_pool::underlying_token_factory; use aave_pool::validation_logic; #[event] + /// @dev Emitted on supply() + /// @param reserve The address of the underlying asset of the reserve + /// @param user The address initiating the supply + /// @param on_behalf_of The beneficiary of the supply, receiving the aTokens + /// @param amount The amount supplied + /// @param referral_code The referral code used struct Supply has drop, copy, store { reserve: address, user: address, @@ -24,6 +30,11 @@ module aave_pool::supply_logic { } #[event] + /// @dev Emitted on withdraw() + /// @param reserve The address of the underlying asset being withdrawn + /// @param user The address initiating the withdrawal, owner of aTokens + /// @param to The address that will receive the underlying + /// @param amount The amount to be withdrawn struct Withdraw has drop, store { reserve: address, user: address, @@ -32,18 +43,33 @@ module aave_pool::supply_logic { } #[event] + /// @dev Emitted on setUserUseReserveAsCollateral() + /// @param reserve The address of the underlying asset of the reserve + /// @param user The address of the user enabling the usage as collateral struct ReserveUsedAsCollateralEnabled has store, drop { reserve: address, user: address } #[event] + /// @dev Emitted on setUserUseReserveAsCollateral() + /// @param reserve The address of the underlying asset of the reserve + /// @param user The address of the user enabling the usage as collateral struct ReserveUsedAsCollateralDisabled has store, drop { reserve: address, user: address } - // Function to execute supply of assets + /// @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. + /// - E.g. User supplies 100 USDC and gets in return 100 aUSDC + /// @param account The account that will supply the asset + /// @param asset The address of the underlying asset to supply + /// @param amount The amount to be supplied + /// @param on_behalf_of The address that will receive the aTokens, same as msg.sender if the user + /// wants to receive them on his own wallet, or a different address if the beneficiary of aTokens + /// is a different wallet + /// @param referral_code Code used to register the integrator originating the operation, for potential rewards. + /// 0 if the action is executed directly by the user, without any middle-man public entry fun supply( account: &signer, asset: address, @@ -52,7 +78,10 @@ module aave_pool::supply_logic { referral_code: u16 ) { let account_address = signer::address_of(account); - assert!(account_address == on_behalf_of, error_config::get_esigner_and_on_behalf_of_no_same()); + assert!( + account_address == on_behalf_of, + error_config::get_esigner_and_on_behalf_of_no_same(), + ); let reserve_data = pool::get_reserve_data(asset); pool::update_state(asset, &mut reserve_data); validation_logic::validate_supply(&reserve_data, amount); @@ -61,61 +90,86 @@ module aave_pool::supply_logic { let token_a_address = pool::get_reserve_a_token_address(&reserve_data); let a_token_account = a_token_factory::get_token_account_address(token_a_address); // transfer the asset to the a_token address - underlying_token_factory::transfer_from(account_address, a_token_account, - (amount as u64), asset); + mock_underlying_token_factory::transfer_from( + account_address, a_token_account, (amount as u64), asset + ); let is_first_supply: bool = - a_token_factory::scale_balance_of(on_behalf_of, token_a_address) == 0; - a_token_factory::mint(account_address, + a_token_factory::scaled_balance_of(on_behalf_of, token_a_address) == 0; + a_token_factory::mint( + account_address, on_behalf_of, amount, (pool::get_reserve_liquidity_index(&reserve_data) as u256), - token_a_address); + token_a_address, + ); if (is_first_supply) { let user_config_map = pool::get_user_configuration(on_behalf_of); - let reserve_config_map = pool::get_reserve_configuration_by_reserve_data(&reserve_data); - if (pool_validation::validate_automatic_use_as_collateral(account_address, &user_config_map, &reserve_config_map)) { - user_config::set_using_as_collateral(&mut user_config_map, - (pool::get_reserve_id(&reserve_data) as u256), true); + let reserve_config_map = + pool::get_reserve_configuration_by_reserve_data(&reserve_data); + if (pool_validation::validate_automatic_use_as_collateral( + account_address, &user_config_map, &reserve_config_map + )) { + user_config::set_using_as_collateral( + &mut user_config_map, + (pool::get_reserve_id(&reserve_data) as u256), + true, + ); pool::set_user_configuration(on_behalf_of, user_config_map); - event::emit(ReserveUsedAsCollateralEnabled { - reserve: asset, - user: on_behalf_of - }); + event::emit( + ReserveUsedAsCollateralEnabled { reserve: asset, user: on_behalf_of } + ); } }; // Emit a supply event - event::emit(Supply { + event::emit( + Supply { reserve: asset, user: account_address, on_behalf_of, amount, referral_code, - }); + }, + ); } - // Function to execute withdrawal of assets + /// @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned + /// E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC + /// @param asset The address of the underlying asset to withdraw + /// @param amount The underlying amount to be withdrawn + /// - Send the value type(uint256).max in order to withdraw the whole aToken balance + /// @param to The address that will receive the underlying, same as msg.sender if the user + /// wants to receive it on his own wallet, or a different address if the beneficiary is a + /// different wallet public entry fun withdraw( - account: &signer, asset: address, amount: u256, to: address, + account: &signer, + asset: address, + amount: u256, + to: address, ) { let account_address = signer::address_of(account); - assert!(account_address == to, error_config::get_esigner_and_on_behalf_of_no_same()); - - let user_emode_category = (emode_logic::get_user_emode(account_address) as u8); - - let (reserve_data, reserves_count) = pool::get_reserve_data_and_reserves_count(asset); + assert!( + account_address == to, error_config::get_esigner_and_on_behalf_of_no_same() + ); + let (reserve_data, reserves_count) = + pool::get_reserve_data_and_reserves_count(asset); // update pool state pool::update_state(asset, &mut reserve_data); let user_balance = - wad_ray_math::ray_mul(a_token_factory::scale_balance_of(account_address, - pool::get_reserve_a_token_address(&reserve_data)), - (pool::get_reserve_liquidity_index(&reserve_data) as u256)); + wad_ray_math::ray_mul( + a_token_factory::scaled_balance_of( + account_address, pool::get_reserve_a_token_address(&reserve_data) + ), + (pool::get_reserve_liquidity_index(&reserve_data) as u256), + ); let amount_to_withdraw = amount; if (amount == math_utils::u256_max()) { amount_to_withdraw = user_balance; }; // validate withdraw - validation_logic::validate_withdraw(&reserve_data, amount_to_withdraw, user_balance); + validation_logic::validate_withdraw( + &reserve_data, amount_to_withdraw, user_balance + ); // update interest rates pool::update_interest_rates(&mut reserve_data, asset, 0, amount_to_withdraw); @@ -126,35 +180,58 @@ module aave_pool::supply_logic { user_config::is_using_as_collateral(&user_config_map, (reserve_id as u256)); if (is_collateral && amount_to_withdraw == user_balance) { - user_config::set_using_as_collateral(&mut user_config_map, (reserve_id as u256), - false); + user_config::set_using_as_collateral( + &mut user_config_map, (reserve_id as u256), false + ); pool::set_user_configuration(account_address, user_config_map); - event::emit(ReserveUsedAsCollateralDisabled { reserve: asset, user: account_address }); + event::emit( + ReserveUsedAsCollateralDisabled { reserve: asset, user: account_address } + ); }; // burn a token - a_token_factory::burn(account_address, + a_token_factory::burn( + account_address, to, amount_to_withdraw, (pool::get_reserve_liquidity_index(&reserve_data) as u256), - pool::get_reserve_a_token_address(&reserve_data)); + pool::get_reserve_a_token_address(&reserve_data), + ); if (is_collateral && user_config::is_borrowing_any(&user_config_map)) { + let user_emode_category = (emode_logic::get_user_emode(account_address) as u8); let (emode_ltv, emode_liq_threshold, emode_asset_price) = emode_logic::get_emode_configuration(user_emode_category); - pool_validation::validate_hf_and_ltv(&mut reserve_data, + pool_validation::validate_hf_and_ltv( + &mut reserve_data, reserves_count, &user_config_map, account_address, user_emode_category, emode_ltv, emode_liq_threshold, - emode_asset_price); + emode_asset_price, + ); }; // Emit a withdraw event - event::emit(Withdraw { reserve: asset, user: account_address, to, amount, }); + event::emit( + Withdraw { + reserve: asset, + user: account_address, + to, + amount: amount_to_withdraw + }, + ); } + /// @notice Validates and finalizes an aToken transfer + /// @dev Only callable by the overlying aToken of the `asset` + /// @param asset The address of the underlying asset of the aToken + /// @param from The user from which the aTokens are transferred + /// @param to The user receiving the aTokens + /// @param amount The amount being transferred/withdrawn + /// @param balance_from_before The aToken balance of the `from` user before the transfer + /// @param balance_to_before The aToken balance of the `to` user before the transfer public entry fun finalize_transfer( account: &signer, asset: address, @@ -165,11 +242,15 @@ module aave_pool::supply_logic { balance_to_before: u256, ) { let account_address = signer::address_of(account); - let (reserve_data, reserves_count) = pool::get_reserve_data_and_reserves_count(asset); + let (reserve_data, reserves_count) = + pool::get_reserve_data_and_reserves_count(asset); let a_token_address = pool::get_reserve_a_token_address(&reserve_data); - assert!(account_address - == a_token_factory::get_token_account_address(a_token_address), - error_config::get_ecaller_not_atoken()); + assert!( + account_address == a_token_factory::get_token_account_address( + a_token_address + ), + error_config::get_ecaller_not_atoken(), + ); // validate transfer validation_logic::validate_transfer(&reserve_data); @@ -181,92 +262,112 @@ module aave_pool::supply_logic { let user_emode_category = (emode_logic::get_user_emode(from) as u8); let (emode_ltv, emode_liq_threshold, emode_asset_price) = emode_logic::get_emode_configuration(user_emode_category); - pool_validation::validate_hf_and_ltv(&mut reserve_data, + pool_validation::validate_hf_and_ltv( + &mut reserve_data, reserves_count, &from_config, from, user_emode_category, emode_ltv, emode_liq_threshold, - emode_asset_price); + emode_asset_price, + ); }; if (balance_from_before == amount) { - user_config::set_using_as_collateral(&mut from_config, reserve_id, false); + user_config::set_using_as_collateral( + &mut from_config, reserve_id, false + ); pool::set_user_configuration(from, from_config); - event::emit(ReserveUsedAsCollateralDisabled { reserve: asset, user: from }); + event::emit( + ReserveUsedAsCollateralDisabled { reserve: asset, user: from } + ); } }; if (balance_to_before == 0) { let to_config = pool::get_user_configuration(to); - let reserve_config_map = pool::get_reserve_configuration_by_reserve_data(&reserve_data); - if (pool_validation::validate_automatic_use_as_collateral(account_address,&to_config, &reserve_config_map)) { + let reserve_config_map = + pool::get_reserve_configuration_by_reserve_data(&reserve_data); + if (pool_validation::validate_automatic_use_as_collateral( + account_address, &to_config, &reserve_config_map + )) { user_config::set_using_as_collateral(&mut to_config, reserve_id, true); pool::set_user_configuration(to, to_config); - event::emit(ReserveUsedAsCollateralEnabled { reserve: asset, user: to }); + event::emit( + ReserveUsedAsCollateralEnabled { reserve: asset, user: to } + ); } } } } + /// @notice Allows suppliers to enable/disable a specific supplied asset as collateral + /// @param asset The address of the underlying asset supplied + /// @param use_as_collateral True if the user wants to use the supply as collateral, false otherwise public entry fun set_user_use_reserve_as_collateral( account: &signer, asset: address, use_as_collateral: bool ) { let account_address = signer::address_of(account); - let (reserve_data, reserves_count) = pool::get_reserve_data_and_reserves_count(asset); - let user_balance = pool::scale_a_token_balance_of( - account_address, - pool::get_reserve_a_token_address(&reserve_data) - ); + let (reserve_data, reserves_count) = + pool::get_reserve_data_and_reserves_count(asset); + let user_balance = + pool::scaled_a_token_balance_of( + account_address, pool::get_reserve_a_token_address(&reserve_data) + ); // validate set use reserve as collateral - validation_logic::validate_set_use_reserve_as_collateral(&reserve_data, user_balance); + validation_logic::validate_set_use_reserve_as_collateral( + &reserve_data, user_balance + ); let user_config_map = pool::get_user_configuration(account_address); let reserve_id = (pool::get_reserve_id(&reserve_data) as u256); if (use_as_collateral - != user_config::is_using_as_collateral(&user_config_map, reserve_id)) { + != user_config::is_using_as_collateral(&user_config_map, reserve_id)) { if (use_as_collateral) { - let reserve_config_map = pool::get_reserve_configuration_by_reserve_data(&reserve_data); - assert!(pool_validation::validate_use_as_collateral(&user_config_map, &reserve_config_map), - error_config::get_euser_in_isolation_mode_or_ltv_zero()); - user_config::set_using_as_collateral(&mut user_config_map, reserve_id, true); + let reserve_config_map = + pool::get_reserve_configuration_by_reserve_data(&reserve_data); + assert!( + pool_validation::validate_use_as_collateral( + &user_config_map, &reserve_config_map + ), + error_config::get_euser_in_isolation_mode_or_ltv_zero(), + ); + user_config::set_using_as_collateral( + &mut user_config_map, reserve_id, true + ); pool::set_user_configuration(account_address, user_config_map); - event::emit(ReserveUsedAsCollateralEnabled { - reserve: asset, - user: account_address - }); + event::emit( + ReserveUsedAsCollateralEnabled { reserve: asset, user: account_address } + ); } else { - user_config::set_using_as_collateral(&mut user_config_map, reserve_id, false); + user_config::set_using_as_collateral( + &mut user_config_map, reserve_id, false + ); pool::set_user_configuration(account_address, user_config_map); - let user_emode_category = (emode_logic::get_user_emode(account_address) as u8); + let user_emode_category = + (emode_logic::get_user_emode(account_address) as u8); let (emode_ltv, emode_liq_threshold, emode_asset_price) = emode_logic::get_emode_configuration(user_emode_category); - pool_validation::validate_hf_and_ltv(&mut reserve_data, + pool_validation::validate_hf_and_ltv( + &mut reserve_data, reserves_count, &user_config_map, account_address, user_emode_category, emode_ltv, emode_liq_threshold, - emode_asset_price,); + emode_asset_price, + ); - event::emit(ReserveUsedAsCollateralDisabled { + event::emit( + ReserveUsedAsCollateralDisabled { reserve: asset, user: account_address - }); + }, + ); } } } - - public entry fun deposit( - account: &signer, - asset: address, - amount: u256, - on_behalf_of: address, - referral_code: u16 - ) { - supply(account, asset, amount, on_behalf_of, referral_code); - } } diff --git a/aave-core/sources/aave-supply-borrow/user_logic.move b/aave-core/sources/aave-supply-borrow/user_logic.move index 9fe5ab6..06b1115 100644 --- a/aave-core/sources/aave-supply-borrow/user_logic.move +++ b/aave-core/sources/aave-supply-borrow/user_logic.move @@ -5,31 +5,50 @@ module aave_pool::user_logic { use aave_pool::pool; #[view] + /// @notice Returns the user account data across all the reserves + /// @param user The address of the user + /// @return total_collateral_base The total collateral of the user in the base currency used by the price feed + /// @return total_debt_base The total debt of the user in the base currency used by the price feed + /// @return available_borrows_base The borrowing power left of the user in the base currency used by the price feed + /// @return current_liquidation_threshold The liquidation threshold of the user + /// @return ltv The loan to value of The user + /// @return health_factor The current health factor of the user public fun get_user_account_data(user: address): (u256, u256, u256, u256, u256, u256) { let user_config_map = pool::get_user_configuration(user); let reserves_count = pool::get_reserves_count(); let user_emode_category = (emode_logic::get_user_emode(user) as u8); let (emode_ltv, emode_liq_threshold, emode_asset_price) = emode_logic::get_emode_configuration(user_emode_category); - let (total_collateral_base, total_debt_base, ltv, current_liquidation_threshold, - health_factor, _) = - generic_logic::calculate_user_account_data(reserves_count, + let ( + total_collateral_base, + total_debt_base, + ltv, + current_liquidation_threshold, + health_factor, + _ + ) = + generic_logic::calculate_user_account_data( + reserves_count, &user_config_map, user, user_emode_category, emode_ltv, emode_liq_threshold, - emode_asset_price); + emode_asset_price, + ); let available_borrows_base = - generic_logic::calculate_available_borrows(total_collateral_base, - total_debt_base, ltv); + generic_logic::calculate_available_borrows( + total_collateral_base, total_debt_base, ltv + ); - (total_collateral_base, + ( + total_collateral_base, total_debt_base, available_borrows_base, current_liquidation_threshold, ltv, - health_factor) + health_factor + ) } } diff --git a/aave-core/sources/aave-supply-borrow/validation_logic.move b/aave-core/sources/aave-supply-borrow/validation_logic.move index a748aaf..c8d1deb 100644 --- a/aave-core/sources/aave-supply-borrow/validation_logic.move +++ b/aave-core/sources/aave-supply-borrow/validation_logic.move @@ -14,84 +14,120 @@ module aave_pool::validation_logic { use aave_pool::emode_logic; use aave_pool::generic_logic; use aave_pool::pool::{Self, ReserveData}; - use aave_pool::variable_token_factory; + use aave_pool::variable_debt_token_factory; - // Flashloan Validate + /// @notice Validates a flashloan action. + /// @param reserves_data The data of all the reserves + /// @param assets The assets being flash-borrowed + /// @param amounts The amounts for each asset being borrowed public fun validate_flashloan_complex( - reserve_data: &vector, assets: &vector
, amounts: &vector, + reserves_data: &vector, + assets: &vector
, + amounts: &vector, ) { - assert!(vector::length(assets) == vector::length(amounts), - error_config::get_einconsistent_flashloan_params()); + assert!( + vector::length(assets) == vector::length(amounts), + error_config::get_einconsistent_flashloan_params(), + ); for (i in 0..vector::length(assets)) { - validate_flashloan_simple(vector::borrow(reserve_data, i)); + validate_flashloan_simple(vector::borrow(reserves_data, i)); } } - // Simple Flashloan Validation + /// @notice Validates a flashloan action. + /// @param reserve_data The reserve data the reserve public fun validate_flashloan_simple(reserve_data: &ReserveData) { - let reserve_configuration = pool::get_reserve_configuration_by_reserve_data( - reserve_data); - let (is_active, _, _, is_paused) = reserve_config::get_flags(&reserve_configuration); + let reserve_configuration = + pool::get_reserve_configuration_by_reserve_data(reserve_data); + let (is_active, _, _, is_paused) = + reserve_config::get_flags(&reserve_configuration); assert!(!is_paused, error_config::get_ereserve_paused()); assert!(is_active, error_config::get_ereserve_inactive()); - let is_flashloan_enabled = reserve_config::get_flash_loan_enabled(&reserve_configuration); + let is_flashloan_enabled = + reserve_config::get_flash_loan_enabled(&reserve_configuration); assert!(is_flashloan_enabled, error_config::get_eflashloan_disabled()); } - // Supply Validate + /// @notice Validates a supply action. + /// @param reserve_data The reserve data the reserve + /// @param amount The amount to be supplied public fun validate_supply(reserve_data: &ReserveData, amount: u256) { assert!(amount != 0, error_config::get_einvalid_amount()); - let reserve_configuration = pool::get_reserve_configuration_by_reserve_data( - reserve_data); - let (is_active, is_frozen, _, is_paused) = reserve_config::get_flags(&reserve_configuration); + let reserve_configuration = + pool::get_reserve_configuration_by_reserve_data(reserve_data); + let (is_active, is_frozen, _, is_paused) = + reserve_config::get_flags(&reserve_configuration); assert!(is_active, error_config::get_ereserve_inactive()); assert!(!is_paused, error_config::get_ereserve_paused()); assert!(!is_frozen, error_config::get_ereserve_frozen()); let supply_cap = reserve_config::get_supply_cap(&reserve_configuration); - let a_token_supply = a_token_factory::scale_total_supply( - pool::get_reserve_a_token_address(reserve_data) - ); + let a_token_supply = + a_token_factory::scaled_total_supply( + pool::get_reserve_a_token_address(reserve_data) + ); let accrued_to_treasury_liquidity = - wad_ray_math::ray_mul((a_token_supply + pool::get_reserve_accrued_to_treasury(reserve_data)), - (pool::get_reserve_liquidity_index(reserve_data) as u256)); + wad_ray_math::ray_mul( + (a_token_supply + pool::get_reserve_accrued_to_treasury(reserve_data)), + (pool::get_reserve_liquidity_index(reserve_data) as u256), + ); let total_supply = accrued_to_treasury_liquidity + amount; let max_supply = - supply_cap * (math_utils::pow(10, - reserve_config::get_decimals(&reserve_configuration))); + supply_cap + * ( + math_utils::pow( + 10, reserve_config::get_decimals(&reserve_configuration) + ) + ); - assert!(supply_cap == 0 || total_supply <= max_supply, - error_config::get_esupply_cap_exceeded()); + assert!( + supply_cap == 0 || total_supply <= max_supply, + error_config::get_esupply_cap_exceeded(), + ); } + /// @notice Validates a withdraw action. + /// @param reserve_data The reserve data the reserve + /// @param amount The amount to be withdrawn + /// @param user_balance The balance of the user public fun validate_withdraw( reserve_data: &ReserveData, amount: u256, user_balance: u256 ) { assert!(amount != 0, error_config::get_einvalid_amount()); - assert!(amount <= user_balance, - error_config::get_enot_enough_available_user_balance()); - let reserve_configuration = pool::get_reserve_configuration_by_reserve_data( - reserve_data); - let (is_active, _, _, is_paused) = reserve_config::get_flags(&reserve_configuration); + assert!( + amount <= user_balance, error_config::get_enot_enough_available_user_balance() + ); + let reserve_configuration = + pool::get_reserve_configuration_by_reserve_data(reserve_data); + let (is_active, _, _, is_paused) = + reserve_config::get_flags(&reserve_configuration); assert!(is_active, error_config::get_ereserve_inactive()); assert!(!is_paused, error_config::get_ereserve_paused()); } + /// @notice Validates a transfer action. + /// @param reserve_data The reserve data the reserve public fun validate_transfer(reserve_data: &ReserveData) { - let reserve_config_map = pool::get_reserve_configuration_by_reserve_data( - reserve_data); - assert!(!reserve_config::get_paused(&reserve_config_map), - error_config::get_ereserve_paused()) + let reserve_config_map = + pool::get_reserve_configuration_by_reserve_data(reserve_data); + assert!( + !reserve_config::get_paused(&reserve_config_map), + error_config::get_ereserve_paused(), + ) } + /// @notice Validates the action of setting an asset as collateral. + /// @param reserve_data The reserve data the reserve + /// @param user_balance The balance of the user public fun validate_set_use_reserve_as_collateral( reserve_data: &ReserveData, user_balance: u256 ) { assert!(user_balance != 0, error_config::get_eunderlying_balance_zero()); - let reserve_configuration_map = pool::get_reserve_configuration_by_reserve_data( - reserve_data); - let (is_active, _, _, is_paused) = reserve_config::get_flags(&reserve_configuration_map); + let reserve_configuration_map = + pool::get_reserve_configuration_by_reserve_data(reserve_data); + let (is_active, _, _, is_paused) = + reserve_config::get_flags(&reserve_configuration_map); assert!(is_active, error_config::get_ereserve_inactive()); assert!(!is_paused, error_config::get_ereserve_paused()); } @@ -101,7 +137,6 @@ module aave_pool::validation_logic { * Borrow Validate * ---------------------------- */ - struct ValidateBorrowLocalVars has drop { current_ltv: u256, collateral_needed_in_base_currency: u256, @@ -148,6 +183,18 @@ module aave_pool::validation_logic { } } + /// @notice Validates a borrow action. + /// @param reserve_data The reserve data the reserve + /// @param user_config_map The UserConfigurationMap object + /// @param asset The address of the asset to be borrowed + /// @param user_address The address of the user + /// @param amount The amount to be borrowed + /// @param interest_rate_mode The interest rate mode + /// @param reserves_count The number of reserves + /// @param user_emode_category The user's eMode category + /// @param isolation_mode_active The isolation mode state + /// @param isolation_mode_collateral_address The address of the collateral reserve in isolation mode + /// @param isolation_mode_debt_ceiling The debt ceiling in isolation mode public fun validate_borrow( reserve_data: &ReserveData, user_config_map: &UserConfigurationMap, @@ -164,8 +211,8 @@ module aave_pool::validation_logic { assert!(amount != 0, error_config::get_einvalid_amount()); let vars = create_validate_borrow_local_vars(); - let reserve_configuration_map = pool::get_reserve_configuration_by_reserve_data( - reserve_data); + let reserve_configuration_map = + pool::get_reserve_configuration_by_reserve_data(reserve_data); let (is_active, is_frozen, borrowing_enabled, is_paused) = reserve_config::get_flags(&reserve_configuration_map); @@ -174,12 +221,15 @@ module aave_pool::validation_logic { assert!(!is_frozen, error_config::get_ereserve_frozen()); assert!(borrowing_enabled, error_config::get_eborrowing_not_enabled()); - assert!(oracle_sentinel::is_borrow_allowed(), - error_config::get_eprice_oracle_sentinel_check_failed()); + assert!( + oracle_sentinel::is_borrow_allowed(), + error_config::get_eprice_oracle_sentinel_check_failed(), + ); - assert!(interest_rate_mode - == user_config::get_interest_rate_mode_variable(), - error_config::get_einvalid_interest_rate_mode_selected()); + assert!( + interest_rate_mode == user_config::get_interest_rate_mode_variable(), + error_config::get_einvalid_interest_rate_mode_selected(), + ); vars.reserve_decimals = reserve_config::get_decimals(&reserve_configuration_map); vars.borrow_cap = reserve_config::get_borrow_cap(&reserve_configuration_map); @@ -187,64 +237,103 @@ module aave_pool::validation_logic { vars.asset_unit = math_utils::pow(10, vars.reserve_decimals); if (vars.borrow_cap != 0) { - let total_supply_variable_debt = variable_token_factory::scale_total_supply( + let total_supply_variable_debt = + variable_debt_token_factory::scaled_total_supply( pool::get_reserve_variable_debt_token_address(reserve_data) - ); + ); vars.total_supply_variable_debt = wad_ray_math::ray_mul( - total_supply_variable_debt, (pool::get_reserve_variable_borrow_index( - reserve_data) as u256)); + total_supply_variable_debt, + (pool::get_reserve_variable_borrow_index(reserve_data) as u256), + ); vars.total_debt = vars.total_supply_variable_debt + amount; - assert!(vars.total_debt <= vars.borrow_cap * vars.asset_unit, - error_config::get_eborrow_cap_exceeded()) + assert!( + vars.total_debt <= vars.borrow_cap * vars.asset_unit, + error_config::get_eborrow_cap_exceeded(), + ) }; if (isolation_mode_active) { - assert!(reserve_config::get_borrowable_in_isolation(&reserve_configuration_map), - error_config::get_easset_not_borrowable_in_isolation()); + // check that the asset being borrowed is borrowable in isolation mode AND + // the total exposure is no bigger than the collateral debt ceiling + assert!( + reserve_config::get_borrowable_in_isolation(&reserve_configuration_map), + error_config::get_easset_not_borrowable_in_isolation(), + ); - let mode_collateral_reserve_data = pool::get_reserve_data( - isolation_mode_collateral_address); + let mode_collateral_reserve_data = + pool::get_reserve_data(isolation_mode_collateral_address); let isolation_mode_total_debt = - (pool::get_reserve_isolation_mode_total_debt(&mode_collateral_reserve_data) as u256); + ( + pool::get_reserve_isolation_mode_total_debt( + &mode_collateral_reserve_data + ) as u256 + ); let total_debt = - isolation_mode_total_debt + (amount / math_utils::pow(10, - (vars.reserve_decimals - reserve_config::get_debt_ceiling_decimals()))); - assert!(total_debt <= isolation_mode_debt_ceiling, - error_config::get_edebt_ceiling_exceeded()); + isolation_mode_total_debt + + ( + amount + / math_utils::pow( + 10, + ( + vars.reserve_decimals + - reserve_config::get_debt_ceiling_decimals() + ), + ) + ); + assert!( + total_debt <= isolation_mode_debt_ceiling, + error_config::get_edebt_ceiling_exceeded(), + ); }; if (user_emode_category != 0) { - assert!(reserve_config::get_emode_category(&reserve_configuration_map) - == (user_emode_category as u256), - error_config::get_einconsistent_emode_category()); - let emode_category_data = emode_logic::get_emode_category_data(user_emode_category); - vars.emode_price_source = emode_logic::get_emode_category_price_source(&emode_category_data) + assert!( + reserve_config::get_emode_category(&reserve_configuration_map) + == (user_emode_category as u256), + error_config::get_einconsistent_emode_category(), + ); + let emode_category_data = + emode_logic::get_emode_category_data(user_emode_category); + vars.emode_price_source = emode_logic::get_emode_category_price_source( + &emode_category_data + ) }; let (emode_ltv, emode_liq_threshold, emode_asset_price) = emode_logic::get_emode_configuration(user_emode_category); - let (user_collateral_in_base_currency, user_debt_in_base_currency, current_ltv, _, - health_factor, _) = - generic_logic::calculate_user_account_data(reserves_count, + let ( + user_collateral_in_base_currency, + user_debt_in_base_currency, + current_ltv, + _, + health_factor, + _ + ) = + generic_logic::calculate_user_account_data( + reserves_count, user_config_map, user_address, user_emode_category, emode_ltv, emode_liq_threshold, - emode_asset_price); + emode_asset_price, + ); vars.user_collateral_in_base_currency = user_collateral_in_base_currency; vars.user_debt_in_base_currency = user_debt_in_base_currency; vars.current_ltv = current_ltv; vars.health_factor = health_factor; - assert!(vars.user_collateral_in_base_currency != 0, - error_config::get_ecollateral_balance_is_zero()); + assert!( + vars.user_collateral_in_base_currency != 0, + error_config::get_ecollateral_balance_is_zero(), + ); assert!(vars.current_ltv != 0, error_config::get_eltv_validation_failed()); assert!( vars.health_factor > user_config::get_health_factor_liquidation_threshold(), - error_config::get_ehealth_factor_lower_than_liquidation_threshold()); + error_config::get_ehealth_factor_lower_than_liquidation_threshold(), + ); let asset_address = if (vars.emode_price_source != @0x0) { @@ -254,27 +343,42 @@ module aave_pool::validation_logic { vars.amount_in_base_currency = vars.amount_in_base_currency / vars.asset_unit; + //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.collateral_needed_in_base_currency = math_utils::percent_div( - (vars.user_debt_in_base_currency + vars.amount_in_base_currency), vars.current_ltv); - assert!(vars.collateral_needed_in_base_currency <= vars.user_collateral_in_base_currency, - error_config::get_ecollateral_cannot_cover_new_borrow()); + (vars.user_debt_in_base_currency + vars.amount_in_base_currency), + vars.current_ltv, + ); + assert!( + vars.collateral_needed_in_base_currency <= vars.user_collateral_in_base_currency, + error_config::get_ecollateral_cannot_cover_new_borrow(), + ); if (user_config::is_borrowing_any(user_config_map)) { - let (siloed_borrowing_enabled, siloed_borrowing_address) = pool::get_siloed_borrowing_state( - user_address); + let (siloed_borrowing_enabled, siloed_borrowing_address) = + pool::get_siloed_borrowing_state(user_address); vars.siloed_borrowing_enabled = siloed_borrowing_enabled; vars.siloed_borrowing_address = siloed_borrowing_address; if (vars.siloed_borrowing_enabled) { - assert!(vars.siloed_borrowing_address == asset, - error_config::get_esiloed_borrowing_violation()) + assert!( + vars.siloed_borrowing_address == asset, + error_config::get_esiloed_borrowing_violation(), + ) } else { - assert!(!reserve_config::get_siloed_borrowing(&reserve_configuration_map), - error_config::get_esiloed_borrowing_violation()) + assert!( + !reserve_config::get_siloed_borrowing(&reserve_configuration_map), + error_config::get_esiloed_borrowing_violation(), + ) } } } - // Repay Validate + /// @notice Validates a repay action. + /// @param account The address of the user + /// @param reserve_data The reserve data the reserve + /// @param amount_sent The amount sent for the repayment. Can be an actual value or uint(-1) + /// @param interest_rate_mode The interest rate mode of the debt being repaid + /// @param on_behalf_of The address of the user msg.sender is repaying for + /// @param variable_debt The borrow balance of the user public fun validate_repay( account: &signer, reserve_data: &ReserveData, @@ -285,21 +389,32 @@ module aave_pool::validation_logic { ) { let account_address = signer::address_of(account); assert!(amount_sent != 0, error_config::get_einvalid_amount()); - assert!(amount_sent != math_utils::u256_max() || account_address == on_behalf_of, - error_config::get_eno_explicit_amount_to_repay_on_behalf()); + assert!( + amount_sent != math_utils::u256_max() || account_address == on_behalf_of, + error_config::get_eno_explicit_amount_to_repay_on_behalf(), + ); - let reserve_configuration = pool::get_reserve_configuration_by_reserve_data( - reserve_data); - let (is_active, _, _, is_paused) = reserve_config::get_flags(&reserve_configuration); + let reserve_configuration = + pool::get_reserve_configuration_by_reserve_data(reserve_data); + let (is_active, _, _, is_paused) = + reserve_config::get_flags(&reserve_configuration); assert!(is_active, error_config::get_ereserve_inactive()); assert!(!is_paused, error_config::get_ereserve_paused()); // check debt selected type - assert!(variable_debt != 0 && interest_rate_mode - == user_config::get_interest_rate_mode_variable(), - error_config::get_eno_debt_of_selected_type()); + assert!( + variable_debt != 0 + && interest_rate_mode == user_config::get_interest_rate_mode_variable(), + error_config::get_eno_debt_of_selected_type(), + ); } + /// @notice Validates the liquidation action. + /// @param user_config_map The user configuration mapping + /// @param collateral_reserve The reserve data of the collateral + /// @param debt_reserve The reserve data of the debt + /// @param total_debt The total debt of the user + /// @param health_factor The health factor of the user public fun validate_liquidation_call( user_config_map: &UserConfigurationMap, collateral_reserve: &ReserveData, @@ -312,27 +427,42 @@ module aave_pool::validation_logic { let (collateral_reserve_active, _, _, collateral_reserve_paused) = reserve_config::get_flags(&collateral_reserve_config); - let debt_reserve_config = pool::get_reserve_configuration_by_reserve_data( - debt_reserve); - let (principal_reserve_active, _, _, principal_reserve_paused) = reserve_config::get_flags( - &debt_reserve_config); - assert!(collateral_reserve_active && principal_reserve_active, - error_config::get_ereserve_inactive()); - assert!(!collateral_reserve_paused && !principal_reserve_paused, - error_config::get_ereserve_paused()); + let debt_reserve_config = + pool::get_reserve_configuration_by_reserve_data(debt_reserve); + let (principal_reserve_active, _, _, principal_reserve_paused) = + reserve_config::get_flags(&debt_reserve_config); + assert!( + collateral_reserve_active && principal_reserve_active, + error_config::get_ereserve_inactive(), + ); + assert!( + !collateral_reserve_paused && !principal_reserve_paused, + error_config::get_ereserve_paused(), + ); - assert!(health_factor < user_config::get_minimum_health_factor_liquidation_threshold() || oracle_sentinel::is_liquidation_allowed(), - error_config::get_eprice_oracle_sentinel_check_failed()); + assert!( + health_factor < user_config::get_minimum_health_factor_liquidation_threshold() || oracle_sentinel::is_liquidation_allowed(), + error_config::get_eprice_oracle_sentinel_check_failed(), + ); - assert!(health_factor < user_config::get_health_factor_liquidation_threshold(), - error_config::get_ehealth_factor_not_below_threshold()); + assert!( + health_factor < user_config::get_health_factor_liquidation_threshold(), + error_config::get_ehealth_factor_not_below_threshold(), + ); let collateral_reserve_id = pool::get_reserve_id(collateral_reserve); let is_collateral_enabled = - reserve_config::get_liquidation_threshold(&collateral_reserve_config) != 0 && user_config::is_using_as_collateral( - user_config_map, (collateral_reserve_id as u256)); - assert!(is_collateral_enabled, error_config::get_ecollateral_cannot_be_liquidated()); - assert!(total_debt != 0, - error_config::get_especified_currency_not_borrowed_by_user()); + reserve_config::get_liquidation_threshold(&collateral_reserve_config) != 0 + && user_config::is_using_as_collateral( + user_config_map, (collateral_reserve_id as u256) + ); + + // if collateral isn't enabled as collateral by user, it cannot be liquidated + assert!( + is_collateral_enabled, error_config::get_ecollateral_cannot_be_liquidated() + ); + assert!( + total_debt != 0, error_config::get_especified_currency_not_borrowed_by_user() + ); } } diff --git a/aave-core/sources/aave-tokens/a_token_factory.move b/aave-core/sources/aave-tokens/a_token_factory.move index 19c24c9..158c9b7 100644 --- a/aave-core/sources/aave-tokens/a_token_factory.move +++ b/aave-core/sources/aave-tokens/a_token_factory.move @@ -1,6 +1,4 @@ module aave_pool::a_token_factory { - use std::option; - use std::option::Option; use std::signer; use std::string::{Self, String}; use std::vector; @@ -13,8 +11,8 @@ module aave_pool::a_token_factory { use aave_config::error as error_config; use aave_math::wad_ray_math; + use aave_pool::mock_underlying_token_factory::Self; use aave_pool::token_base; - use aave_pool::underlying_token_factory::Self; friend aave_pool::pool; friend aave_pool::flashloan_logic; @@ -33,6 +31,12 @@ module aave_pool::a_token_factory { const E_NOT_A_TOKEN_ADMIN: u64 = 1; #[event] + /// @dev Emitted when an aToken is initialized + /// @param underlyingAsset The address of the underlying asset + /// @param treasury The address of the treasury + /// @param a_token_decimals The decimals of the underlying + /// @param a_token_name The name of the aToken + /// @param a_token_symbol The symbol of the aToken struct Initialized has store, drop { underlying_asset: address, treasury: address, @@ -42,7 +46,12 @@ module aave_pool::a_token_factory { } #[event] - struct BalanceTransfer has store, drop{ + /// @dev Emitted during the transfer action + /// @param from The user whose tokens are being transferred + /// @param to The recipient + /// @param value The scaled amount being transferred + /// @param index The next liquidity index of the reserve + struct BalanceTransfer has store, drop { from: address, to: address, value: u256, @@ -52,6 +61,15 @@ module aave_pool::a_token_factory { // // Entry Functions // + /// @notice Creates a new aToken + /// @param signer The signer of the transaction + /// @param name The name of the aToken + /// @param symbol The symbol of the aToken + /// @param decimals The decimals of the aToken + /// @param icon_uri The icon URI of the aToken + /// @param project_uri The project URI of the aToken + /// @param underlying_asset The address of the underlying asset + /// @param treasury The address of the treasury public(friend) fun create_token( signer: &signer, name: String, @@ -80,23 +98,32 @@ module aave_pool::a_token_factory { project_uri, underlying_asset, treasury, - resource_account); + resource_account, + ); - event::emit(Initialized { + event::emit( + Initialized { underlying_asset, treasury, a_token_decimals: decimals, a_token_name: name, a_token_symbol: symbol, - }) + }, + ) } + /// @notice Rescue and transfer tokens locked in this contract + /// @param token The address of the token + /// @param to The address of the recipient + /// @param amount The amount of token to transfer public entry fun rescue_tokens( account: &signer, token: address, to: address, amount: u256 ) { token_base::only_pool_admin(account); - assert!(token != get_underlying_asset_address(token), - error_config::get_eunderlying_cannot_be_rescued()); + assert!( + token != get_underlying_asset_address(token), + error_config::get_eunderlying_cannot_be_rescued(), + ); let account_address = signer::address_of(account); token_base::transfer_internal(account_address, to, (amount as u64), token); } @@ -105,6 +132,12 @@ module aave_pool::a_token_factory { // Functions Call between contracts // + /// @notice Mints `amount` aTokens to `user` + /// @param caller The address performing the mint + /// @param on_behalf_of The address of the user that will receive the minted aTokens + /// @param amount The amount of tokens getting minted + /// @param index The next liquidity index of the reserve + /// @param metadata_address The address of the aToken public(friend) fun mint( caller: address, on_behalf_of: address, @@ -115,6 +148,14 @@ module aave_pool::a_token_factory { token_base::mint_scaled(caller, on_behalf_of, amount, index, metadata_address); } + /// @notice Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` + /// @dev In some instances, the mint event could be emitted from a burn transaction + /// if the amount to burn is less than the interest that the user accrued + /// @param from The address from which the aTokens will be burned + /// @param receiver_of_underlying The address that will receive the underlying + /// @param amount The amount being burned + /// @param index The next liquidity index of the reserve + /// @param metadata_address The address of the aToken public(friend) fun burn( from: address, receiver_of_underlying: address, @@ -122,39 +163,64 @@ module aave_pool::a_token_factory { index: u256, metadata_address: address ) { - token_base::burn_scaled(from, receiver_of_underlying, amount, index, - metadata_address,); + token_base::burn_scaled( + from, + receiver_of_underlying, + amount, + index, + metadata_address, + ); if (receiver_of_underlying != get_token_account_address(metadata_address)) { - underlying_token_factory::transfer_from(get_token_account_address( - metadata_address), + mock_underlying_token_factory::transfer_from( + get_token_account_address(metadata_address), receiver_of_underlying, (amount as u64), - get_underlying_asset_address(metadata_address)) + get_underlying_asset_address(metadata_address), + ) } } + /// @notice Mints aTokens to the reserve treasury + /// @param amount The amount of tokens getting minted + /// @param index The next liquidity index of the reserve + /// @param metadata_address The address of the aToken public(friend) fun mint_to_treasury( amount: u256, index: u256, metadata_address: address ) { if (amount != 0) { let token_data = token_base::get_token_data(metadata_address); - token_base::mint_scaled(@aave_pool, + token_base::mint_scaled( + @aave_pool, token_base::get_treasury_address(&token_data), amount, index, - metadata_address,) + metadata_address, + ) } } + /// @notice Transfers the underlying asset to `target`. + /// @dev Used by the Pool to transfer assets in borrow(), withdraw() and flashLoan() + /// @param to The recipient of the underlying + /// @param amount The amount getting transferred + /// @param metadata_address The address of the aToken public(friend) fun transfer_underlying_to( to: address, amount: u256, metadata_address: address ) { - underlying_token_factory::transfer_from(get_token_account_address(metadata_address), + mock_underlying_token_factory::transfer_from( + get_token_account_address(metadata_address), to, (amount as u64), - get_underlying_asset_address(metadata_address)) + get_underlying_asset_address(metadata_address), + ) } + /// @notice Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken + /// @param from The address getting liquidated, current owner of the aTokens + /// @param to The recipient + /// @param amount The amount of tokens getting transferred + /// @param index The next liquidity index of the reserve + /// @param metadata_address The address of the aToken public(friend) fun transfer_on_liquidation( from: address, to: address, @@ -164,14 +230,19 @@ module aave_pool::a_token_factory { ) { token_base::transfer(from, to, amount, index, metadata_address); // send balance transfer event - event::emit(BalanceTransfer{ - from, - to, - value: wad_ray_math::ray_div(amount,index), - index - }); + event::emit( + BalanceTransfer { from, to, value: wad_ray_math::ray_div(amount, index), index }, + ); } + /// @notice Handles the underlying received by the aToken after the transfer has been completed. + /// @dev The default implementation is empty as with standard ERC20 tokens, nothing needs to be done after the + /// transfer is concluded. However in the future there may be aTokens that allow for example to stake the underlying + /// to receive LM rewards. In that case, `handleRepayment()` would perform the staking of the underlying asset. + /// @param user The user executing the repayment + /// @param on_behalf_of The address of the user who will get his debt reduced/removed + /// @param amount The amount getting repaid + /// @param metadata_address The address of the aToken public fun handle_repayment( _user: address, _onBehalfOf: address, _amount: u256, _metadata_address: address ) { @@ -188,13 +259,14 @@ module aave_pool::a_token_factory { } #[view] + /// @notice Return the address of the managed fungible asset that's created resource account. + /// @param metadata_address The address of the aToken public fun get_token_account_address(metadata_address: address): address { let token_data = token_base::get_token_data(metadata_address); token_base::get_resource_account(&token_data) } #[view] - /// Return the address of the managed fungible asset that's created when this module is deployed. public fun get_metadata_by_symbol(owner: address, symbol: String): Object { let metadata_address = object::create_object_address(&owner, *string::bytes(&symbol)); @@ -212,23 +284,40 @@ module aave_pool::a_token_factory { } #[view] + /// @notice Returns the address of the Aave treasury, receiving the fees on this aToken. + /// @param metadata_address The address of the aToken + /// @return Address of the Aave treasury public fun get_reserve_treasury_address(metadata_address: address): address { let token_data = token_base::get_token_data(metadata_address); token_base::get_treasury_address(&token_data) } #[view] + /// @notice Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) + /// @param metadata_address The address of the aToken + /// @return The address of the underlying asset public fun get_underlying_asset_address(metadata_address: address): address { let token_data = token_base::get_token_data(metadata_address); token_base::get_underlying_asset(&token_data) } #[view] - public fun get_previous_index(user: address, metadata_address: address): u256 { + /// @notice Returns last index interest was accrued to the user's balance + /// @param user The address of the user + /// @param metadata_address The address of the aToken + /// @return The last index interest was accrued to the user's balance, expressed in ray + public fun get_previous_index( + user: address, metadata_address: address + ): u256 { token_base::get_previous_index(user, metadata_address) } #[view] + /// @notice Returns the scaled balance of the user and the scaled total supply. + /// @param owner The address of the user + /// @param metadata_address The address of the aToken + /// @return The scaled balance of the user + /// @return The scaled total supply public fun get_scaled_user_balance_and_supply( owner: address, metadata_address: address ): (u256, u256) { @@ -236,28 +325,24 @@ module aave_pool::a_token_factory { } #[view] - public fun scale_balance_of(owner: address, metadata_address: address): u256 { - token_base::scale_balance_of(owner, metadata_address) - } - - #[view] - public fun balance_of(owner: address, metadata_address: address): u256 { - token_base::balance_of(owner, metadata_address) - } - - #[view] - public fun scale_total_supply(metadata_address: address): u256 { - token_base::scale_total_supply(metadata_address) - } - - #[view] - public fun supply(metadata_address: address): u256 { - (*option::borrow(&token_base::supply(metadata_address)) as u256) + /// @notice Returns the scaled balance of the user. + /// @dev The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index + /// at the moment of the update + /// @param owner The user whose balance is calculated + /// @param metadata_address The address of the aToken + /// @return The scaled balance of the user + public fun scaled_balance_of( + owner: address, metadata_address: address + ): u256 { + token_base::scaled_balance_of(owner, metadata_address) } #[view] - public fun maximum(metadata_address: address): Option { - token_base::maximum(metadata_address) + /// @notice Returns the scaled total supply of the scaled balance token. Represents sum(debt/index) + /// @param metadata_address The address of the aToken + /// @return The scaled total supply + public fun scaled_total_supply(metadata_address: address): u256 { + token_base::scaled_total_supply(metadata_address) } #[view] diff --git a/aave-core/sources/aave-tokens/underlying_token_factory.move b/aave-core/sources/aave-tokens/mock_underlying_token_factory.move similarity index 82% rename from aave-core/sources/aave-tokens/underlying_token_factory.move rename to aave-core/sources/aave-tokens/mock_underlying_token_factory.move index 2db4a14..b460f05 100644 --- a/aave-core/sources/aave-tokens/underlying_token_factory.move +++ b/aave-core/sources/aave-tokens/mock_underlying_token_factory.move @@ -1,4 +1,4 @@ -module aave_pool::underlying_token_factory { +module aave_pool::mock_underlying_token_factory { use std::error; use std::option::{Self, Option}; use std::signer; @@ -36,18 +36,23 @@ module aave_pool::underlying_token_factory { burn_ref: BurnRef, } - // coin metadata_address set + /// mapping (underlying token address => bool) struct CoinList has key { - /// A smart table used as a set, to prevent execution gas limit errors on O(n) lookup. - value: SmartTable, + value: SmartTable, } fun init_module(signer: &signer) { token_base::only_token_admin(signer); - move_to(signer, CoinList { value: smart_table::new(), }) + move_to(signer, CoinList { value: smart_table::new() }) } - /// Initialize metadata object and store the refs. + /// @notice Creates a new underlying token. + /// @param signer The signer of the transaction + /// @param name The name of the aToken + /// @param symbol The symbol of the aToken + /// @param decimals The decimals of the aToken + /// @param icon_uri The icon URI of the aToken + /// @param project_uri The project URI of the aToken public entry fun create_token( signer: &signer, maximum_supply: u128, @@ -59,11 +64,15 @@ module aave_pool::underlying_token_factory { ) acquires CoinList { only_token_admin(signer); let token_metadata_address = - object::create_object_address(&signer::address_of(signer), *string::bytes(&symbol)); + object::create_object_address( + &signer::address_of(signer), *string::bytes(&symbol) + ); let coin_list = borrow_global_mut(@aave_pool); - assert!(!smart_table::contains(&coin_list.value, token_metadata_address), - E_TOKEN_ALREADY_EXISTS); - smart_table::add(&mut coin_list.value, token_metadata_address, 0); + assert!( + !smart_table::contains(&coin_list.value, token_metadata_address), + E_TOKEN_ALREADY_EXISTS, + ); + smart_table::add(&mut coin_list.value, token_metadata_address, true); let max_supply = if (maximum_supply != 0) { @@ -71,35 +80,38 @@ module aave_pool::underlying_token_factory { } else { option::none() }; - let constructor_ref = &object::create_named_object(signer, *string::bytes(&symbol)); - primary_fungible_store::create_primary_store_enabled_fungible_asset(constructor_ref, + let constructor_ref = + &object::create_named_object(signer, *string::bytes(&symbol)); + primary_fungible_store::create_primary_store_enabled_fungible_asset( + constructor_ref, max_supply, name, symbol, decimals, icon_uri, - project_uri,); + project_uri, + ); // Create mint/burn/transfer refs to allow creator to manage the fungible asset. let mint_ref = fungible_asset::generate_mint_ref(constructor_ref); let burn_ref = fungible_asset::generate_burn_ref(constructor_ref); let transfer_ref = fungible_asset::generate_transfer_ref(constructor_ref); let metadata_object_signer = object::generate_signer(constructor_ref); - move_to(&metadata_object_signer, ManagedFungibleAsset { - mint_ref, - transfer_ref, - burn_ref - }); + move_to( + &metadata_object_signer, + ManagedFungibleAsset { mint_ref, transfer_ref, burn_ref }, + ); } public fun assert_token_exists(token_metadata_address: address) acquires CoinList { let coin_list = borrow_global(@aave_pool); - assert!(smart_table::contains(&coin_list.value, token_metadata_address), - E_TOKEN_ALREADY_EXISTS); + assert!( + smart_table::contains(&coin_list.value, token_metadata_address), + E_TOKEN_ALREADY_EXISTS, + ); } - + #[view] - /// Return the address of the managed fungible asset that's created when this module is deployed. public fun get_metadata_by_symbol(symbol: String): Object { let metadata_address = object::create_object_address(&@underlying_tokens, *string::bytes(&symbol)); @@ -124,10 +136,12 @@ module aave_pool::underlying_token_factory { let managed_fungible_asset = authorized_borrow_refs(admin, asset); let to_wallet = primary_fungible_store::ensure_primary_store_exists(to, asset); let fa = fungible_asset::mint(&managed_fungible_asset.mint_ref, amount); - fungible_asset::deposit_with_ref(&managed_fungible_asset.transfer_ref, to_wallet, fa); + fungible_asset::deposit_with_ref( + &managed_fungible_asset.transfer_ref, to_wallet, fa + ); } - // <:!:mint + // Internal transfer from public(friend) fun transfer_from( from: address, to: address, amount: u64, metadata_address: address ) acquires ManagedFungibleAsset { @@ -200,8 +214,10 @@ module aave_pool::underlying_token_factory { inline fun authorized_borrow_refs( owner: &signer, asset: Object, ): &ManagedFungibleAsset acquires ManagedFungibleAsset { - assert!(object::is_owner(asset, signer::address_of(owner)), - error::permission_denied(ENOT_OWNER)); + assert!( + object::is_owner(asset, signer::address_of(owner)), + error::permission_denied(ENOT_OWNER), + ); borrow_global(object::object_address(&asset)) } diff --git a/aave-core/sources/aave-tokens/standard_token.move b/aave-core/sources/aave-tokens/standard_token.move index e72f27c..8e3468b 100644 --- a/aave-core/sources/aave-tokens/standard_token.move +++ b/aave-core/sources/aave-tokens/standard_token.move @@ -69,17 +69,28 @@ module aave_pool::standard_token { is_coin_underlying: bool, ) { only_token_admin(creator); - assert!(vector::length(&ref_flags) == 3, - error::invalid_argument(ERR_INVALID_REF_FLAGS_LENGTH)); - let supply = if (maximum_supply != 0) { - option::some(maximum_supply) - } else { - option::none() - }; + assert!( + vector::length(&ref_flags) == 3, + error::invalid_argument(ERR_INVALID_REF_FLAGS_LENGTH), + ); + let supply = + if (maximum_supply != 0) { + option::some(maximum_supply) + } else { + option::none() + }; - let constructor_ref = &object::create_named_object(creator, *string::bytes(&symbol)); - primary_fungible_store::create_primary_store_enabled_fungible_asset(constructor_ref, - supply, name, symbol, decimals, icon_uri, project_uri,); + let constructor_ref = + &object::create_named_object(creator, *string::bytes(&symbol)); + primary_fungible_store::create_primary_store_enabled_fungible_asset( + constructor_ref, + supply, + name, + symbol, + decimals, + icon_uri, + project_uri, + ); // Optionally create mint/burn/transfer refs to allow creator to manage the fungible asset. let mint_ref = @@ -103,9 +114,13 @@ module aave_pool::standard_token { let metadata_object_signer = object::generate_signer(constructor_ref); // save the managing refs - move_to(&metadata_object_signer, ManagingRefs { mint_ref, transfer_ref, burn_ref }); + move_to( + &metadata_object_signer, + ManagingRefs { mint_ref, transfer_ref, burn_ref }, + ); - event::emit(AaveTokenInitialized { + event::emit( + AaveTokenInitialized { supply, name, symbol, @@ -114,7 +129,8 @@ module aave_pool::standard_token { project_uri, underlying_asset_address, is_coin_underlying, - }) + }, + ) } #[view] @@ -127,8 +143,9 @@ module aave_pool::standard_token { public entry fun mint_to_primary_stores( admin: &signer, asset: Object, to: vector
, amounts: vector ) acquires ManagingRefs { - let receiver_primary_stores = vector::map(to, |addr| primary_fungible_store::ensure_primary_store_exists( - addr, asset)); + let receiver_primary_stores = vector::map( + to, |addr| primary_fungible_store::ensure_primary_store_exists(addr, asset) + ); mint(admin, asset, receiver_primary_stores, amounts); } @@ -140,11 +157,17 @@ module aave_pool::standard_token { amounts: vector, ) acquires ManagingRefs { let length = vector::length(&stores); - assert!(length == vector::length(&amounts), - error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH)); + assert!( + length == vector::length(&amounts), + error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH), + ); let mint_ref = authorized_borrow_mint_ref(admin, asset); for (i in 0..length) { - fungible_asset::mint_to(mint_ref, *vector::borrow(&stores, i), *vector::borrow(&amounts, i)); + fungible_asset::mint_to( + mint_ref, + *vector::borrow(&stores, i), + *vector::borrow(&amounts, i), + ); } } @@ -157,11 +180,19 @@ module aave_pool::standard_token { to: vector
, amounts: vector ) acquires ManagingRefs { - let sender_primary_stores = vector::map(from, |addr| primary_fungible_store::primary_store( - addr, asset)); - let receiver_primary_stores = vector::map(to, |addr| primary_fungible_store::ensure_primary_store_exists( - addr, asset)); - transfer(admin, asset, sender_primary_stores, receiver_primary_stores, amounts); + let sender_primary_stores = vector::map( + from, |addr| primary_fungible_store::primary_store(addr, asset) + ); + let receiver_primary_stores = vector::map( + to, |addr| primary_fungible_store::ensure_primary_store_exists(addr, asset) + ); + transfer( + admin, + asset, + sender_primary_stores, + receiver_primary_stores, + amounts, + ); } /// Transfer as the owner of metadata object ignoring `frozen` field between fungible stores. @@ -173,25 +204,35 @@ module aave_pool::standard_token { amounts: vector, ) acquires ManagingRefs { let length = vector::length(&sender_stores); - assert!(length == vector::length(&receiver_stores), - error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH)); - assert!(length == vector::length(&amounts), - error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH)); + assert!( + length == vector::length(&receiver_stores), + error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH), + ); + assert!( + length == vector::length(&amounts), + error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH), + ); let transfer_ref = authorized_borrow_transfer_ref(admin, asset); for (i in 0..length) { - fungible_asset::transfer_with_ref(transfer_ref, + fungible_asset::transfer_with_ref( + transfer_ref, *vector::borrow(&sender_stores, i), *vector::borrow(&receiver_stores, i), - *vector::borrow(&amounts, i)); + *vector::borrow(&amounts, i), + ); } } /// Burn fungible assets as the owner of metadata object from the primary stores of accounts. public entry fun burn_from_primary_stores( - admin: &signer, asset: Object, from: vector
, amounts: vector + admin: &signer, + asset: Object, + from: vector
, + amounts: vector ) acquires ManagingRefs { - let primary_stores = vector::map(from, |addr| primary_fungible_store::primary_store( - addr, asset)); + let primary_stores = vector::map( + from, |addr| primary_fungible_store::primary_store(addr, asset) + ); burn(admin, asset, primary_stores, amounts); } @@ -203,12 +244,17 @@ module aave_pool::standard_token { amounts: vector ) acquires ManagingRefs { let length = vector::length(&stores); - assert!(length == vector::length(&amounts), - error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH)); + assert!( + length == vector::length(&amounts), + error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH), + ); let burn_ref = authorized_borrow_burn_ref(admin, asset); for (i in 0..length) { - fungible_asset::burn_from(burn_ref, *vector::borrow(&stores, i), *vector::borrow( - &amounts, i)); + fungible_asset::burn_from( + burn_ref, + *vector::borrow(&stores, i), + *vector::borrow(&amounts, i), + ); }; } @@ -216,29 +262,39 @@ module aave_pool::standard_token { public entry fun set_primary_stores_frozen_status( admin: &signer, asset: Object, accounts: vector
, frozen: bool ) acquires ManagingRefs { - let primary_stores = vector::map(accounts, |acct| { - primary_fungible_store::ensure_primary_store_exists(acct, asset) - }); + let primary_stores = vector::map( + accounts, + |acct| { primary_fungible_store::ensure_primary_store_exists(acct, asset) }, + ); set_frozen_status(admin, asset, primary_stores, frozen); } /// Freeze/unfreeze the fungible stores so they cannot transfer or receive fungible assets. public entry fun set_frozen_status( - admin: &signer, asset: Object, stores: vector>, + admin: &signer, + asset: Object, + stores: vector>, frozen: bool ) acquires ManagingRefs { let transfer_ref = authorized_borrow_transfer_ref(admin, asset); - vector::for_each(stores, |store| { + vector::for_each( + stores, + |store| { fungible_asset::set_frozen_flag(transfer_ref, store, frozen); - }); + }, + ); } /// Withdraw as the owner of metadata object ignoring `frozen` field from primary fungible stores of accounts. public fun withdraw_from_primary_stores( - admin: &signer, asset: Object, from: vector
, amounts: vector + admin: &signer, + asset: Object, + from: vector
, + amounts: vector ): FungibleAsset acquires ManagingRefs { - let primary_stores = vector::map(from, |addr| primary_fungible_store::primary_store( - addr, asset)); + let primary_stores = vector::map( + from, |addr| primary_fungible_store::primary_store(addr, asset) + ); withdraw(admin, asset, primary_stores, amounts) } @@ -251,14 +307,19 @@ module aave_pool::standard_token { amounts: vector ): FungibleAsset acquires ManagingRefs { let length = vector::length(&stores); - assert!(length == vector::length(&amounts), - error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH)); + assert!( + length == vector::length(&amounts), + error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH), + ); let transfer_ref = authorized_borrow_transfer_ref(admin, asset); let sum = fungible_asset::zero(asset); for (i in 0..length) { let fa = - fungible_asset::withdraw_with_ref(transfer_ref, *vector::borrow(&stores, i), *vector::borrow( - &amounts, i)); + fungible_asset::withdraw_with_ref( + transfer_ref, + *vector::borrow(&stores, i), + *vector::borrow(&amounts, i), + ); fungible_asset::merge(&mut sum, fa); }; sum @@ -272,9 +333,12 @@ module aave_pool::standard_token { from: vector
, amounts: vector, ) acquires ManagingRefs { - let primary_stores = vector::map(from, - |addr| primary_fungible_store::ensure_primary_store_exists(addr, - fungible_asset::asset_metadata(fa))); + let primary_stores = vector::map( + from, + |addr| primary_fungible_store::ensure_primary_store_exists( + addr, fungible_asset::asset_metadata(fa) + ), + ); deposit(admin, fa, primary_stores, amounts); } @@ -287,14 +351,19 @@ module aave_pool::standard_token { amounts: vector ) acquires ManagingRefs { let length = vector::length(&stores); - assert!(length == vector::length(&amounts), - error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH)); + assert!( + length == vector::length(&amounts), + error::invalid_argument(ERR_VECTORS_LENGTH_MISMATCH), + ); let transfer_ref = authorized_borrow_transfer_ref(admin, fungible_asset::asset_metadata(fa)); for (i in 0..length) { let split_fa = fungible_asset::extract(fa, *vector::borrow(&amounts, i)); - fungible_asset::deposit_with_ref(transfer_ref, *vector::borrow(&stores, i), - split_fa,); + fungible_asset::deposit_with_ref( + transfer_ref, + *vector::borrow(&stores, i), + split_fa, + ); }; } @@ -303,8 +372,10 @@ module aave_pool::standard_token { inline fun authorized_borrow_refs( owner: &signer, asset: Object, ): &ManagingRefs acquires ManagingRefs { - assert!(object::is_owner(asset, signer::address_of(owner)), - error::permission_denied(ERR_NOT_OWNER)); + assert!( + object::is_owner(asset, signer::address_of(owner)), + error::permission_denied(ERR_NOT_OWNER), + ); borrow_global(object::object_address(&asset)) } diff --git a/aave-core/sources/aave-tokens/token_base.move b/aave-core/sources/aave-tokens/token_base.move index 04f77d9..f373368 100644 --- a/aave-core/sources/aave-tokens/token_base.move +++ b/aave-core/sources/aave-tokens/token_base.move @@ -1,5 +1,5 @@ module aave_pool::token_base { - use std::option::{Self, Option}; + use std::option::Self; use std::signer; use std::string::{Self, String}; use aptos_std::smart_table::{Self, SmartTable}; @@ -14,7 +14,7 @@ module aave_pool::token_base { use aave_math::wad_ray_math; friend aave_pool::a_token_factory; - friend aave_pool::variable_token_factory; + friend aave_pool::variable_debt_token_factory; /// Only fungible asset metadata owner can make changes. const ENOT_OWNER: u64 = 1; @@ -23,6 +23,10 @@ module aave_pool::token_base { const E_TOKEN_NOT_EXISTS: u64 = 4; #[event] + /// @dev Emitted when `value` tokens are moved from one account (`from`) to + /// another (`to`). + /// + /// Note that `value` may be zero. struct Transfer has store, drop { from: address, to: address, @@ -30,6 +34,12 @@ module aave_pool::token_base { } #[event] + /// @dev Emitted after the mint action + /// @param caller The address performing the mint + /// @param on_behalf_of The address of the user that will receive the minted tokens + /// @param value The scaled-up amount being minted (based on user entered amount and balance increase from interest) + /// @param balance_increase The increase in scaled-up balance since the last action of 'onBehalfOf' + /// @param index The next liquidity index of the reserve struct Mint has store, drop { caller: address, on_behalf_of: address, @@ -39,6 +49,13 @@ module aave_pool::token_base { } #[event] + /// @dev Emitted after the burn action + /// @dev If the burn function does not involve a transfer of the underlying asset, the target defaults to zero address + /// @param from The address from which the tokens will be burned + /// @param target The address that will receive the underlying, if any + /// @param value The scaled-up amount being burned (user entered amount - balance increase from interest) + /// @param balance_increase The increase in scaled-up balance since the last action of 'from' + /// @param index The next liquidity index of the reserve struct Burn has store, drop { from: address, target: address, @@ -64,7 +81,7 @@ module aave_pool::token_base { resource_account: address } - // Atoken metadata_address => underlying token metadata_address + // Atoken metadata_address => TokenData struct TokenMap has key { value: SmartTable, } @@ -83,7 +100,9 @@ module aave_pool::token_base { move_to(signer, TokenMap { value: smart_table::new() }) } - public fun get_user_state(user: address, token_metadata_address: address): UserState acquires UserStateMap { + public fun get_user_state( + user: address, token_metadata_address: address + ): UserState acquires UserStateMap { let user_state_map = borrow_global(@aave_pool); let key = format2(&b"{}_{}", user, token_metadata_address); if (!smart_table::contains(&user_state_map.value, key)) { @@ -93,13 +112,19 @@ module aave_pool::token_base { } fun set_user_state( - user: address, token_metadata_address: address, balance: u128, additional_data: u128 + user: address, + token_metadata_address: address, + balance: u128, + additional_data: u128 ) acquires UserStateMap { let user_state_map = borrow_global_mut(@aave_pool); let key = format2(&b"{}_{}", user, token_metadata_address); if (!smart_table::contains(&user_state_map.value, key)) { - smart_table::upsert(&mut user_state_map.value, key, - UserState { balance, additional_data }) + smart_table::upsert( + &mut user_state_map.value, + key, + UserState { balance, additional_data }, + ) } else { let user_state = smart_table::borrow_mut(&mut user_state_map.value, key); user_state.balance = balance; @@ -109,7 +134,10 @@ module aave_pool::token_base { public fun get_token_data(token_metadata_address: address): TokenData acquires TokenMap { let token_map = borrow_global(@aave_pool); - assert!(smart_table::contains(&token_map.value, token_metadata_address), E_TOKEN_NOT_EXISTS); + assert!( + smart_table::contains(&token_map.value, token_metadata_address), + E_TOKEN_NOT_EXISTS, + ); *smart_table::borrow(&token_map.value, token_metadata_address) } @@ -135,12 +163,14 @@ module aave_pool::token_base { token_data.resource_account } - public fun get_previous_index(user: address, metadata_address: address): u256 acquires UserStateMap { + public fun get_previous_index( + user: address, metadata_address: address + ): u256 acquires UserStateMap { let user_state = get_user_state(user, metadata_address); (user_state.additional_data as u256) } - public fun get_scale_total_supply(token_data: &TokenData): u256 { + public fun get_scaled_total_supply(token_data: &TokenData): u256 { token_data.scaled_total_supply } @@ -159,30 +189,39 @@ module aave_pool::token_base { let token_metadata_address = object::create_object_address(&account_address, *string::bytes(&symbol)); let token_map = borrow_global_mut(@aave_pool); - assert!(!smart_table::contains(&token_map.value, token_metadata_address), - E_TOKEN_ALREADY_EXISTS); - let token_data = TokenData { underlying_asset, treasury, scaled_total_supply: 0, resource_account }; + assert!( + !smart_table::contains(&token_map.value, token_metadata_address), + E_TOKEN_ALREADY_EXISTS, + ); + let token_data = TokenData { + underlying_asset, + treasury, + scaled_total_supply: 0, + resource_account + }; smart_table::add(&mut token_map.value, token_metadata_address, token_data); - let constructor_ref = &object::create_named_object(signer, *string::bytes(&symbol)); - primary_fungible_store::create_primary_store_enabled_fungible_asset(constructor_ref, + let constructor_ref = + &object::create_named_object(signer, *string::bytes(&symbol)); + primary_fungible_store::create_primary_store_enabled_fungible_asset( + constructor_ref, option::none(), name, symbol, decimals, icon_uri, - project_uri, ); + project_uri, + ); // Create mint/burn/transfer refs to allow creator to manage the fungible asset. let mint_ref = fungible_asset::generate_mint_ref(constructor_ref); let burn_ref = fungible_asset::generate_burn_ref(constructor_ref); let transfer_ref = fungible_asset::generate_transfer_ref(constructor_ref); let metadata_object_signer = object::generate_signer(constructor_ref); - move_to(&metadata_object_signer, ManagedFungibleAsset { - mint_ref, - transfer_ref, - burn_ref - }); + move_to( + &metadata_object_signer, + ManagedFungibleAsset { mint_ref, transfer_ref, burn_ref }, + ); } public(friend) fun create_variable_token( @@ -198,31 +237,39 @@ module aave_pool::token_base { let token_metadata_address = object::create_object_address(&account_address, *string::bytes(&symbol)); let token_map = borrow_global_mut(@aave_pool); - assert!(!smart_table::contains(&token_map.value, token_metadata_address), - E_TOKEN_ALREADY_EXISTS); - let token_data = - TokenData { underlying_asset, treasury: @0x0, scaled_total_supply: 0, resource_account: @0x0 }; + assert!( + !smart_table::contains(&token_map.value, token_metadata_address), + E_TOKEN_ALREADY_EXISTS, + ); + let token_data = TokenData { + underlying_asset, + treasury: @0x0, + scaled_total_supply: 0, + resource_account: @0x0 + }; smart_table::add(&mut token_map.value, token_metadata_address, token_data); - let constructor_ref = &object::create_named_object(signer, *string::bytes(&symbol)); - primary_fungible_store::create_primary_store_enabled_fungible_asset(constructor_ref, + let constructor_ref = + &object::create_named_object(signer, *string::bytes(&symbol)); + primary_fungible_store::create_primary_store_enabled_fungible_asset( + constructor_ref, option::none(), name, symbol, decimals, icon_uri, - project_uri, ); + project_uri, + ); // Create mint/burn/transfer refs to allow creator to manage the fungible asset. let mint_ref = fungible_asset::generate_mint_ref(constructor_ref); let burn_ref = fungible_asset::generate_burn_ref(constructor_ref); let transfer_ref = fungible_asset::generate_transfer_ref(constructor_ref); let metadata_object_signer = object::generate_signer(constructor_ref); - move_to(&metadata_object_signer, ManagedFungibleAsset { - mint_ref, - transfer_ref, - burn_ref - }); + move_to( + &metadata_object_signer, + ManagedFungibleAsset { mint_ref, transfer_ref, burn_ref }, + ); } public(friend) fun mint_scaled( @@ -235,12 +282,14 @@ module aave_pool::token_base { assert_token_exists(metadata_address); let amount_scaled = wad_ray_math::ray_div(amount, index); assert!(amount_scaled != 0, error_config::get_einvalid_mint_amount()); - let scaled_balance = scale_balance_of(on_behalf_of, metadata_address); + let scaled_balance = scaled_balance_of(on_behalf_of, metadata_address); let user_state = get_user_state(on_behalf_of, metadata_address); let balance_increase = - wad_ray_math::ray_mul(scaled_balance, index) - wad_ray_math::ray_mul( - scaled_balance, (user_state.additional_data as u256)); + wad_ray_math::ray_mul(scaled_balance, index) + - wad_ray_math::ray_mul( + scaled_balance, (user_state.additional_data as u256) + ); let new_balance = user_state.balance + (amount_scaled as u128); set_user_state(on_behalf_of, metadata_address, new_balance, (index as u128)); @@ -251,24 +300,38 @@ module aave_pool::token_base { // fungible asset mint let asset = get_metadata(metadata_address); - let managed_fungible_asset = authorized_borrow_refs(asset); + let managed_fungible_asset = obtain_managed_asset_refs(asset); let to_wallet = primary_fungible_store::ensure_primary_store_exists(on_behalf_of, asset); // freeze account - fungible_asset::set_frozen_flag(&managed_fungible_asset.transfer_ref, to_wallet, true); + fungible_asset::set_frozen_flag( + &managed_fungible_asset.transfer_ref, to_wallet, true + ); let fa = fungible_asset::mint(&managed_fungible_asset.mint_ref, (amount as u64)); - fungible_asset::deposit_with_ref(&managed_fungible_asset.transfer_ref, to_wallet, fa); + fungible_asset::deposit_with_ref( + &managed_fungible_asset.transfer_ref, to_wallet, fa + ); let amount_to_mint = amount + balance_increase; event::emit(Transfer { from: @0x0, to: on_behalf_of, value: amount_to_mint, }); - event::emit(Mint { caller, on_behalf_of, value: amount_to_mint, balance_increase, index, }); + event::emit( + Mint { + caller, + on_behalf_of, + value: amount_to_mint, + balance_increase, + index, + }, + ); } fun assert_token_exists(token_metadata_address: address) acquires TokenMap { let a_token_map = borrow_global(@aave_pool); - assert!(smart_table::contains(&a_token_map.value, token_metadata_address), - E_TOKEN_ALREADY_EXISTS); + assert!( + smart_table::contains(&a_token_map.value, token_metadata_address), + E_TOKEN_ALREADY_EXISTS, + ); } public(friend) fun burn_scaled( @@ -282,12 +345,14 @@ module aave_pool::token_base { let amount_scaled = wad_ray_math::ray_div(amount, index); assert!(amount_scaled != 0, error_config::get_einvalid_mint_amount()); // get scale balance - let scaled_balance = scale_balance_of(user, metadata_address); + let scaled_balance = scaled_balance_of(user, metadata_address); let user_state = get_user_state(user, metadata_address); let balance_increase = - wad_ray_math::ray_mul(scaled_balance, index) - wad_ray_math::ray_mul( - scaled_balance, (user_state.additional_data as u256)); + wad_ray_math::ray_mul(scaled_balance, index) + - wad_ray_math::ray_mul( + scaled_balance, (user_state.additional_data as u256) + ); let new_balance = user_state.balance - (amount_scaled as u128); set_user_state(user, metadata_address, new_balance, (index as u128)); @@ -298,24 +363,34 @@ module aave_pool::token_base { // burn fungible asset let asset = get_metadata(metadata_address); - let burn_ref = &authorized_borrow_refs(asset).burn_ref; + let burn_ref = &obtain_managed_asset_refs(asset).burn_ref; let from_wallet = primary_fungible_store::primary_store(user, asset); fungible_asset::burn_from(burn_ref, from_wallet, (amount as u64)); if (balance_increase > amount) { let amount_to_mint = balance_increase - amount; event::emit(Transfer { from: @0x0, to: user, value: amount_to_mint, }); - event::emit(Mint { - caller: user, - on_behalf_of: user, - value: amount_to_mint, - balance_increase, - index, - }); + event::emit( + Mint { + caller: user, + on_behalf_of: user, + value: amount_to_mint, + balance_increase, + index, + }, + ); } else { let amount_to_burn = amount - balance_increase; event::emit(Transfer { from: user, to: @0x0, value: amount_to_burn, }); - event::emit(Burn { from: user, target, value: amount_to_burn, balance_increase, index, }); + event::emit( + Burn { + from: user, + target, + value: amount_to_burn, + balance_increase, + index, + }, + ); } } @@ -326,96 +401,103 @@ module aave_pool::token_base { index: u256, metadata_address: address, ) acquires ManagedFungibleAsset, UserStateMap { - let sender_scaled_balance = scale_balance_of(sender, metadata_address); + let sender_scaled_balance = scaled_balance_of(sender, metadata_address); let sender_user_state = get_user_state(sender, metadata_address); let sender_balance_increase = - wad_ray_math::ray_mul(sender_scaled_balance, index) - wad_ray_math::ray_mul( - sender_scaled_balance, (sender_user_state.additional_data as u256)); + wad_ray_math::ray_mul(sender_scaled_balance, index) + - wad_ray_math::ray_mul( + sender_scaled_balance, (sender_user_state.additional_data as u256) + ); let amount_ray_div = wad_ray_math::ray_div(amount, index); let new_sender_balance = sender_user_state.balance - (amount_ray_div as u128); - set_user_state(sender, metadata_address, new_sender_balance, (index as u128), ); + set_user_state(sender, metadata_address, new_sender_balance, (index as u128)); - let recipient_scaled_balance = scale_balance_of(recipient, metadata_address); + let recipient_scaled_balance = scaled_balance_of(recipient, metadata_address); let recipient_user_state = get_user_state(recipient, metadata_address); let recipient_balance_increase = - wad_ray_math::ray_mul(recipient_scaled_balance, index) - wad_ray_math::ray_mul( - recipient_scaled_balance, (recipient_user_state.additional_data as u256)); + wad_ray_math::ray_mul(recipient_scaled_balance, index) + - wad_ray_math::ray_mul( + recipient_scaled_balance, + (recipient_user_state.additional_data as u256), + ); let new_recipient_balance = recipient_user_state.balance + (amount_ray_div as u128); - set_user_state(recipient, metadata_address, new_recipient_balance, (index as u128), ); + set_user_state( + recipient, + metadata_address, + new_recipient_balance, + (index as u128), + ); // transfer fungible asset let asset = get_metadata(metadata_address); - let transfer_ref = &authorized_borrow_refs(asset).transfer_ref; + let transfer_ref = &obtain_managed_asset_refs(asset).transfer_ref; let from_wallet = primary_fungible_store::primary_store(sender, asset); let to_wallet = primary_fungible_store::ensure_primary_store_exists(recipient, asset); - fungible_asset::transfer_with_ref(transfer_ref, from_wallet, to_wallet, (amount as u64)); + fungible_asset::transfer_with_ref( + transfer_ref, from_wallet, to_wallet, (amount as u64) + ); if (sender_balance_increase > 0) { - event::emit(Transfer { from: @0x0, to: sender, value: sender_balance_increase, }); - event::emit(Mint { - caller: sender, - on_behalf_of: sender, - value: sender_balance_increase, - balance_increase: sender_balance_increase, - index, - }); + event::emit( + Transfer { from: @0x0, to: sender, value: sender_balance_increase, }, + ); + event::emit( + Mint { + caller: sender, + on_behalf_of: sender, + value: sender_balance_increase, + balance_increase: sender_balance_increase, + index, + }, + ); }; if (sender != recipient && recipient_balance_increase > 0) { - event::emit(Transfer { from: @0x0, to: recipient, value: recipient_balance_increase, }); - event::emit(Mint { - caller: sender, - on_behalf_of: recipient, - value: recipient_balance_increase, - balance_increase: recipient_balance_increase, - index, - }); + event::emit( + Transfer { from: @0x0, to: recipient, value: recipient_balance_increase, }, + ); + event::emit( + Mint { + caller: sender, + on_behalf_of: recipient, + value: recipient_balance_increase, + balance_increase: recipient_balance_increase, + index, + }, + ); }; event::emit(Transfer { from: sender, to: recipient, value: amount, }); } - public fun transfer_internal( + public(friend) fun transfer_internal( from: address, to: address, amount: u64, metadata_address: address ) acquires ManagedFungibleAsset { let asset = get_metadata(metadata_address); - let transfer_ref = &authorized_borrow_refs(asset).transfer_ref; + let transfer_ref = &obtain_managed_asset_refs(asset).transfer_ref; let from_wallet = primary_fungible_store::primary_store(from, asset); let to_wallet = primary_fungible_store::ensure_primary_store_exists(to, asset); fungible_asset::transfer_with_ref(transfer_ref, from_wallet, to_wallet, amount); } - public fun scale_balance_of(owner: address, metadata_address: address): u256 acquires UserStateMap { + public fun scaled_balance_of( + owner: address, metadata_address: address + ): u256 acquires UserStateMap { let user_state_map = get_user_state(owner, metadata_address); (user_state_map.balance as u256) } - public fun balance_of(owner: address, metadata_address: address): u256 { - let metadata = get_metadata(metadata_address); - (primary_fungible_store::balance(owner, metadata) as u256) - } - - public fun scale_total_supply(metadata_address: address): u256 acquires TokenMap { + public fun scaled_total_supply(metadata_address: address): u256 acquires TokenMap { let token_data = get_token_data(metadata_address); token_data.scaled_total_supply } - public fun supply(metadata_address: address): Option { - let asset = get_metadata(metadata_address); - fungible_asset::supply(asset) - } - public fun get_scaled_user_balance_and_supply( owner: address, metadata_address: address ): (u256, u256) acquires UserStateMap, TokenMap { - (scale_balance_of(owner, metadata_address), scale_total_supply(metadata_address)) - } - - public fun maximum(metadata_address: address): Option { - let asset = get_metadata(metadata_address); - fungible_asset::maximum(asset) + (scaled_balance_of(owner, metadata_address), scaled_total_supply(metadata_address)) } public fun name(metadata_address: address): String { @@ -437,15 +519,15 @@ module aave_pool::token_base { object::address_to_object(metadata_address) } - inline fun authorized_borrow_refs( - asset: Object, - ): &ManagedFungibleAsset acquires ManagedFungibleAsset { + inline fun obtain_managed_asset_refs(asset: Object,): &ManagedFungibleAsset acquires ManagedFungibleAsset { borrow_global(object::object_address(&asset)) } public fun only_pool_admin(account: &signer) { - assert!(acl_manage::is_pool_admin(signer::address_of(account)), - error_config::get_ecaller_not_pool_admin()); + assert!( + acl_manage::is_pool_admin(signer::address_of(account)), + error_config::get_ecaller_not_pool_admin(), + ); } public fun only_token_admin(account: &signer) { diff --git a/aave-core/sources/aave-tokens/variable_token_factory.move b/aave-core/sources/aave-tokens/variable_debt_token_factory.move similarity index 54% rename from aave-core/sources/aave-tokens/variable_token_factory.move rename to aave-core/sources/aave-tokens/variable_debt_token_factory.move index 9c7fbc2..e1df11c 100644 --- a/aave-core/sources/aave-tokens/variable_token_factory.move +++ b/aave-core/sources/aave-tokens/variable_debt_token_factory.move @@ -1,6 +1,4 @@ -module aave_pool::variable_token_factory { - use std::option; - use std::option::Option; +module aave_pool::variable_debt_token_factory { use std::signer; use std::string; use std::string::String; @@ -19,14 +17,14 @@ module aave_pool::variable_token_factory { friend aave_pool::liquidation_logic; #[test_only] - friend aave_pool::variable_token_factory_tests; + friend aave_pool::variable_debt_token_factory_tests; #[test_only] friend aave_pool::pool_configurator_tests; #[test_only] friend aave_pool::pool_tests; - const ATOKEN_REVISION: u256 = 0x1; + const DEBT_TOKEN_REVISION: u256 = 0x1; // error config const E_NOT_V_TOKEN_ADMIN: u64 = 1; @@ -57,16 +55,25 @@ module aave_pool::variable_token_factory { icon_uri, project_uri, underlying_asset, - ); + ); - event::emit(Initialized { + event::emit( + Initialized { underlying_asset, debt_token_decimals: decimals, debt_token_name: name, debt_token_symbol: symbol, - }) + }, + ) } + /// @notice Mints debt token to the `on_behalf_of` address + /// @param caller The address receiving the borrowed underlying, being the delegatee in case + /// of credit delegate, or same as `on_behalf_of` otherwise + /// @param on_behalf_of The address receiving the debt tokens + /// @param amount The amount of debt being minted + /// @param index The variable debt index of the reserve + /// @param metadata_address The address of the metadata object public(friend) fun mint( caller: address, on_behalf_of: address, @@ -77,25 +84,34 @@ module aave_pool::variable_token_factory { token_base::mint_scaled(caller, on_behalf_of, amount, index, metadata_address); } + /// @notice Burns user variable debt + /// @dev In some instances, a burn transaction will emit a mint event + /// if the amount to burn is less than the interest that the user accrued + /// @param from The address from which the debt will be burned + /// @param amount The amount getting burned + /// @param index The variable debt index of the reserve + /// @param metadata_address The address of the metadata object public(friend) fun burn( from: address, amount: u256, index: u256, metadata_address: address ) { - token_base::burn_scaled(from, @0x0, amount, index, metadata_address,); + token_base::burn_scaled(from, @0x0, amount, index, metadata_address); } #[view] public fun get_revision(): u256 { - ATOKEN_REVISION + DEBT_TOKEN_REVISION } #[view] + /// @notice Returns the address of the underlying asset of this debtToken (E.g. WETH for variableDebtWETH) + /// @param metadata_address The address of the metadata object + /// @return The address of the underlying asset public fun get_underlying_asset_address(metadata_address: address): address { let token_data = token_base::get_token_data(metadata_address); token_base::get_underlying_asset(&token_data) } #[view] - /// Return the address of the managed fungible asset that's created when this module is deployed. public fun get_metadata_by_symbol(owner: address, symbol: String): Object { let metadata_address = object::create_object_address(&owner, *string::bytes(&symbol)); @@ -113,43 +129,49 @@ module aave_pool::variable_token_factory { } #[view] - public fun get_previous_index(user: address, metadata_address: address): u256 { + /// @notice Returns last index interest was accrued to the user's balance + /// @param user The address of the user + /// @param metadata_address The address of the variable debt token + /// @return The last index interest was accrued to the user's balance, expressed in ray + public fun get_previous_index( + user: address, metadata_address: address + ): u256 { token_base::get_previous_index(user, metadata_address) } #[view] - public fun scale_balance_of(owner: address, metadata_address: address): u256 { - token_base::scale_balance_of(owner, metadata_address) - } - - #[view] - public fun balance_of(owner: address, metadata_address: address): u256 { - token_base::balance_of(owner, metadata_address) - } - - #[view] - public fun scale_total_supply(metadata_address: address): u256 { - token_base::scale_total_supply(metadata_address) + /// @notice Returns the scaled balance of the user. + /// @dev The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index + /// at the moment of the update + /// @param owner The user whose balance is calculated + /// @param metadata_address The address of the variable debt token + /// @return The scaled balance of the user + public fun scaled_balance_of( + owner: address, metadata_address: address + ): u256 { + token_base::scaled_balance_of(owner, metadata_address) } #[view] - public fun supply(metadata_address: address): u256 { - (*option::borrow(&token_base::supply(metadata_address)) as u256) + /// @notice Returns the scaled total supply of the scaled balance token. Represents sum(debt/index) + /// @param metadata_address The address of the variable debt token + /// @return The scaled total supply + public fun scaled_total_supply(metadata_address: address): u256 { + token_base::scaled_total_supply(metadata_address) } #[view] + /// @notice Returns the scaled balance of the user and the scaled total supply. + /// @param owner The address of the user + /// @param metadata_address The address of the variable debt token + /// @return The scaled balance of the user + /// @return The scaled total supply public fun get_scaled_user_balance_and_supply( owner: address, metadata_address: address ): (u256, u256) { token_base::get_scaled_user_balance_and_supply(owner, metadata_address) } - #[view] - /// Get the maximum supply from the `metadata` object. - public fun maximum(metadata_address: address): Option { - token_base::maximum(metadata_address) - } - #[view] /// Get the name of the fungible asset from the `metadata` object. public fun name(metadata_address: address): String { @@ -170,6 +192,10 @@ module aave_pool::variable_token_factory { fun only_token_admin(account: &signer) { let account_address = signer::address_of(account); - assert!(acl_manage::is_asset_listing_admin(account_address) || acl_manage::is_pool_admin(account_address), error_config::get_ecaller_not_asset_listing_or_pool_admin()) + assert!( + acl_manage::is_asset_listing_admin(account_address) + || acl_manage::is_pool_admin(account_address), + error_config::get_ecaller_not_asset_listing_or_pool_admin(), + ) } } diff --git a/aave-core/tests/aave-bridge/bridge_logic_tests.move b/aave-core/tests/aave-bridge/bridge_logic_tests.move index 9a45828..8f22330 100644 --- a/aave-core/tests/aave-bridge/bridge_logic_tests.move +++ b/aave-core/tests/aave-bridge/bridge_logic_tests.move @@ -1,19 +1,811 @@ #[test_only] module aave_pool::bridge_logic_tests { use std::features::change_feature_flags_for_testing; + use std::option::Self; + use std::signer; + use std::string::{utf8, String}; + use std::vector; + use aptos_std::string_utils; + use aptos_framework::account; + use aptos_framework::event::emitted_events; use aptos_framework::timestamp::set_time_has_started_for_testing; + use aave_acl::acl_manage::{Self}; + use aave_config::reserve; + use aave_math::wad_ray_math; + use aave_mock_oracle::oracle; + use aave_pool::pool; + use aave_pool::collector; + use aave_pool::pool_configurator; + use aave_pool::pool::{ + get_reserve_id, + get_reserve_data, + test_set_reserve_configuration, + get_reserve_liquidity_index + }; + use aave_config::user::is_using_as_collateral_or_borrowing; + use aave_pool::a_token_factory::Self; + use aave_pool::default_reserve_interest_rate_strategy::Self; + use aave_pool::pool_tests::create_user_config_for_reserve; + use aave_pool::supply_logic::Self; + use aave_pool::token_base::Self; + use aave_pool::mock_underlying_token_factory::Self; + use aave_pool::bridge_logic::{Self}; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; - #[test(_brigde = @aave_pool, aave_std = @std, aptos_framework = @0x1,)] - fun test_bridge( - _brigde: &signer, aave_std: &signer, aptos_framework: &signer, + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, supply_user = @0x042, underlying_tokens_admin = @underlying_tokens, unbacked_tokens_minter = @0x43,)] + /// Mint unbacked a-tokens (no underlyings behind them) for a user + /// The user has already supplied hence not a first supply + fun test_minting_backed_after_supply( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + supply_user: &signer, + underlying_tokens_admin: &signer, + unbacked_tokens_minter: &signer, ) { // start the timer - set_time_has_started_for_testing(aptos_framework); + set_time_has_started_for_testing(aptos_std); // add the test events feature flag - change_feature_flags_for_testing(aave_std, vector[26], vector[]); + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_bridge( + aave_role_super_admin, signer::address_of(unbacked_tokens_minter) + ); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + let reserve_unbacked_mint_cap = 1000; + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, true); + reserve::set_unbacked_mint_cap( + &mut reserve_config_new, reserve_unbacked_mint_cap + ); + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + let reserve_data = get_reserve_data(underlying_token_address); + + // assert resreve has 0 unbacked + let reserve_mint_unbacked = pool::get_reserve_unbacked(&reserve_data); + assert!(reserve_mint_unbacked == 0, TEST_SUCCESS); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(supply_user), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + // =============== MINT UNDERLYING FOR A SUPPLY USER ================= // + // mint 100 underlying tokens for the user + let underlying_tokens_to_mint = 100; + let mint_receiver_address = signer::address_of(supply_user); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + underlying_tokens_to_mint, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == underlying_tokens_to_mint, TEST_SUCCESS); + // assert underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some((underlying_tokens_to_mint as u128)), + TEST_SUCCESS, + ); + + // =============== USER SUPPLY ================= // + // user supplies the underlying token + let supply_receiver_address = signer::address_of(supply_user); + let supplied_amount: u64 = 10; + supply_logic::supply( + supply_user, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + + // check supplier balance of underlying + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); + + // check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some((underlying_tokens_to_mint as u128)), + TEST_SUCCESS, + ); + + // check a_token underlying balance + let a_token_address = + a_token_factory::token_address( + signer::address_of(aave_pool), + *vector::borrow(&atokens_symbols, 0), + ); + let atoken_acocunt_address = + a_token_factory::get_token_account_address(a_token_address); + let underlying_acocunt_balance = + mock_underlying_token_factory::balance_of( + atoken_acocunt_address, underlying_token_address + ); + assert!(underlying_acocunt_balance == supplied_amount, TEST_SUCCESS); + + // check user a_token balance after supply + let supplied_amount_scaled = + wad_ray_math::ray_div( + (supplied_amount as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + assert!(supplier_a_token_balance == supplied_amount_scaled, TEST_SUCCESS); + + // =============== MINT UNBACKED ATOKENS FOR A SUPPLY USER ================= // + let mint_unbacked_amount = 50; + bridge_logic::mint_unbacked( + unbacked_tokens_minter, + underlying_token_address, + mint_unbacked_amount, + signer::address_of(supply_user), + 0, + ); + + // check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + + // check reserve + let reserve_data = get_reserve_data(underlying_token_address); + let reserve_mint_unbacked = pool::get_reserve_unbacked(&reserve_data); + assert!(mint_unbacked_amount == (reserve_mint_unbacked as u256), TEST_SUCCESS); + + // check supplier a token balance + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + let supplied_a_token_amount_scaled = + wad_ray_math::ray_div( + mint_unbacked_amount + (supplied_amount as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + assert!(supplier_a_token_balance == supplied_a_token_amount_scaled, TEST_SUCCESS); + + // check supplier underlying token balance + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); + + // check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some((underlying_tokens_to_mint as u128)), + TEST_SUCCESS, + ); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, supply_user = @0x042, underlying_tokens_admin = @underlying_tokens, unbacked_tokens_minter = @0x43,)] + #[expected_failure(abort_code = 6)] + /// Mint unbacked a-tokens (no underlyings behind them) for a user + /// The user has already supplied hence not a first supply + fun test_minting_backed_none_bridge_failure( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + supply_user: &signer, + underlying_tokens_admin: &signer, + unbacked_tokens_minter: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_bridge( + aave_role_super_admin, signer::address_of(unbacked_tokens_minter) + ); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + let reserve_unbacked_mint_cap = 1000; + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, true); + reserve::set_unbacked_mint_cap( + &mut reserve_config_new, reserve_unbacked_mint_cap + ); + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + let reserve_data = get_reserve_data(underlying_token_address); + + // assert resreve has 0 unbacked + let reserve_mint_unbacked = pool::get_reserve_unbacked(&reserve_data); + assert!(reserve_mint_unbacked == 0, TEST_SUCCESS); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(supply_user), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + // =============== MINT UNDERLYING FOR A SUPPLY USER ================= // + // mint 100 underlying tokens for the user + let underlying_tokens_to_mint = 100; + let mint_receiver_address = signer::address_of(supply_user); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + underlying_tokens_to_mint, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == underlying_tokens_to_mint, TEST_SUCCESS); + // assert underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some((underlying_tokens_to_mint as u128)), + TEST_SUCCESS, + ); + + // =============== USER SUPPLY ================= // + // user supplies the underlying token + let supply_receiver_address = signer::address_of(supply_user); + let supplied_amount: u64 = 10; + supply_logic::supply( + supply_user, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + + // check supplier balance of underlying + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); + + // check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some((underlying_tokens_to_mint as u128)), + TEST_SUCCESS, + ); + + // check a_token underlying balance + let a_token_address = + a_token_factory::token_address( + signer::address_of(aave_pool), + *vector::borrow(&atokens_symbols, 0), + ); + let atoken_acocunt_address = + a_token_factory::get_token_account_address(a_token_address); + let underlying_acocunt_balance = + mock_underlying_token_factory::balance_of( + atoken_acocunt_address, underlying_token_address + ); + assert!(underlying_acocunt_balance == supplied_amount, TEST_SUCCESS); + + // check user a_token balance after supply + let supplied_amount_scaled = + wad_ray_math::ray_div( + (supplied_amount as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + assert!(supplier_a_token_balance == supplied_amount_scaled, TEST_SUCCESS); + + // =============== MINT UNBACKED ATOKENS FOR A SUPPLY USER ================= // + let mint_unbacked_amount = 50; + bridge_logic::mint_unbacked( + underlying_tokens_admin, + underlying_token_address, + mint_unbacked_amount, + signer::address_of(supply_user), + 0, + ); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, supply_user = @0x042, underlying_tokens_admin = @underlying_tokens, unbacked_tokens_minter = @0x43,)] + /// Mint unbacked a-tokens (no underlyings behind them) for a user + /// The user has not supplied before + fun test_minting_backed_first_supply( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + supply_user: &signer, + underlying_tokens_admin: &signer, + unbacked_tokens_minter: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_bridge( + aave_role_super_admin, signer::address_of(unbacked_tokens_minter) + ); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + let reserve_unbacked_mint_cap = 1000; + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, true); + reserve::set_unbacked_mint_cap( + &mut reserve_config_new, reserve_unbacked_mint_cap + ); + reserve::set_ltv(&mut reserve_config_new, 10000); // NOTE: set ltv here! + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + let reserve_data = get_reserve_data(underlying_token_address); + + // assert resreve has 0 unbacked + let reserve_mint_unbacked = pool::get_reserve_unbacked(&reserve_data); + assert!(reserve_mint_unbacked == 0, TEST_SUCCESS); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(supply_user), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(false), // NOTE: user is not yet using as collateral + ); + + // =============== MINT UNDERLYING FOR A SUPPLY USER ================= // + // mint 100 underlying tokens for the user + let underlying_tokens_to_mint = 100; + let mint_receiver_address = signer::address_of(supply_user); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + underlying_tokens_to_mint, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + + // assert user balance of underlying + assert!(initial_user_balance == underlying_tokens_to_mint, TEST_SUCCESS); + + // assert underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some((underlying_tokens_to_mint as u128)), + TEST_SUCCESS, + ); + + // check a_token underlying balance + let a_token_address = + a_token_factory::token_address( + signer::address_of(aave_pool), + *vector::borrow(&atokens_symbols, 0), + ); + let atoken_acocunt_address = + a_token_factory::get_token_account_address(a_token_address); + let underlying_acocunt_balance = + mock_underlying_token_factory::balance_of( + atoken_acocunt_address, underlying_token_address + ); + assert!(underlying_acocunt_balance == 0, TEST_SUCCESS); + + // check user a_token balance + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + assert!(supplier_a_token_balance == 0, TEST_SUCCESS); + + // =============== MINT UNBACKED ATOKENS FOR A SUPPLY USER ================= // + let mint_unbacked_amount = 50; + bridge_logic::mint_unbacked( + unbacked_tokens_minter, + underlying_token_address, + mint_unbacked_amount, + signer::address_of(supply_user), + 0, + ); + + // check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + let emitted_reserve_used_as_collateral_events = + emitted_events(); + assert!( + vector::length(&emitted_reserve_used_as_collateral_events) == 1, TEST_SUCCESS + ); + + // check reserve + let reserve_data = get_reserve_data(underlying_token_address); + let reserve_mint_unbacked = pool::get_reserve_unbacked(&reserve_data); + assert!(mint_unbacked_amount == (reserve_mint_unbacked as u256), TEST_SUCCESS); + + // check supplier a token balance + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + let supplied_a_token_amount_scaled = + wad_ray_math::ray_div( + mint_unbacked_amount, (get_reserve_liquidity_index(&reserve_data) as u256) + ); + assert!(supplier_a_token_balance == supplied_a_token_amount_scaled, TEST_SUCCESS); + + // check supplier underlying token balance + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance, TEST_SUCCESS); + + // check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some((underlying_tokens_to_mint as u128)), + TEST_SUCCESS, + ); + + // check the set using as collateral or borrowing flat is now set + let user_config = pool::get_user_configuration(mint_receiver_address); + assert!( + is_using_as_collateral_or_borrowing( + &user_config, (get_reserve_id(&reserve_data) as u256) + ) == true, + TEST_SUCCESS, + ); } } diff --git a/aave-core/tests/aave-flash-loan/flash_loan_tests.move b/aave-core/tests/aave-flash-loan/flash_loan_tests.move index 6159994..104858c 100644 --- a/aave-core/tests/aave-flash-loan/flash_loan_tests.move +++ b/aave-core/tests/aave-flash-loan/flash_loan_tests.move @@ -3,1046 +3,1298 @@ module aave_pool::flashloan_logic_tests { use std::features::change_feature_flags_for_testing; use std::option::Self; use std::signer; - use std::string::utf8; + use std::string::{utf8, String}; use std::vector; + use aptos_std::string_utils; use aptos_framework::event::emitted_events; use aptos_framework::timestamp::set_time_has_started_for_testing; use aptos_framework::account; - use aave_acl::acl_manage::{Self, test_init_module}; + use aave_acl::acl_manage::{Self}; use aave_math::wad_ray_math; - use aave_mock_oracle::oracle::test_init_oracle; use aave_pool::default_reserve_interest_rate_strategy::Self; - use aave_pool::pool_configurator::test_init_module as pool_config_init_reserves; - use aave_pool::pool_tests::{create_reserve_with_config, create_user_config_for_reserve}; + use aave_pool::pool_tests::create_user_config_for_reserve; use aave_pool::a_token_factory::Self; use aave_pool::token_base::Self; - use aave_pool::underlying_token_factory::Self; - use aave_pool::variable_token_factory::Self; + use aave_pool::mock_underlying_token_factory::Self; use aave_pool::supply_logic::Self; + use aave_pool::pool::{ + Self, + test_set_reserve_configuration, + get_reserve_liquidity_index + }; use aave_pool::flashloan_logic::{Self}; use aave_math::math_utils::get_percentage_factor; use aave_config::user as user_config; + use aave_config::reserve::{Self}; + use aave_mock_oracle::oracle; + use aave_pool::pool::{get_reserve_id, get_reserve_data}; + use aave_pool::pool_configurator; + use aave_pool::collector; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; - // #[test(pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aave_std = @std, flashloan_user = @0x042, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aptos_framework = @0x1, collector_account = @0x55,)] - // /// User takes and repays a single asset flashloan - // fun simple_flashloan_same_payer_receiver( - // pool: &signer, - // aave_role_super_admin: &signer, - // mock_oracle: &signer, - // aave_std: &signer, - // flashloan_user: &signer, - // variable_tokens_admin: &signer, - // a_tokens_admin: &signer, - // underlying_tokens_admin: &signer, - // aptos_framework: &signer, - // collector_account: &signer, - // ) { - // // start the timer - // set_time_has_started_for_testing(aptos_framework); - // - // // add the test events feature flag - // change_feature_flags_for_testing(aave_std, vector[26], vector[]); - // - // // create a tokens admin account - // account::create_account_for_test(signer::address_of(a_tokens_admin)); - // - // // init the acl module and make aave_pool the asset listing/pool admin - // test_init_module(aave_role_super_admin); - // acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); - // acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); - // - // // init oracle - // test_init_oracle(mock_oracle); - // - // // init pool conigutrator and pool modules - // pool_config_init_reserves(pool); - // - // // init underlying tokens - // underlying_token_factory::test_init_module(pool); - // let underlying_token_name = utf8(b"TOKEN_1"); - // let underlying_token_symbol = utf8(b"T1"); - // let underlying_token_decimals = 3; - // let underlying_token_max_supply = 10000; - // underlying_token_factory::create_token(underlying_tokens_admin, - // underlying_token_max_supply, - // underlying_token_name, - // underlying_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""),); - // let underlying_token_address = underlying_token_factory::token_address( - // underlying_token_symbol); - // - // // init token base for tokens - // token_base::test_init_module(pool); - // - // // create variable tokens - // variable_token_factory::create_token(variable_tokens_admin, - // utf8(b"TEST_VAR_TOKEN_1"), - // utf8(b"VAR1"), - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // @0x033, // take random - // ); - // let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); - // - // //create a tokens - // let a_token_symbol = utf8(b"A1"); - // a_token_factory::create_token(a_tokens_admin, - // utf8(b"TEST_A_TOKEN_1"), - // a_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // underlying_token_address, // underlying asset address - // signer::address_of(collector_account), // treasury address - // ); - // let a_token_address = a_token_factory::token_address(utf8(b"A1")); - // - // // init and add a single reserve to the pool - // let reserve_index = - // create_reserve_with_config((underlying_token_decimals as u256), - // a_token_address, - // variable_token_address, - // underlying_token_address, - // option::none(), // ltv - // option::none(), // liq threshold - // option::none(), // liq bonus - // option::some((underlying_token_decimals as u256)), //decimals - // option::some(true), //active - // option::some(false), //frozen - // option::some(false), // paused - // option::some(true), // borrowable_in_isolation - // option::some(true), // siloed_borrowing - // option::some(true), // borrowing_enabled - // option::none(), // reserve_factor* - // option::none(), // borrow_cap - // option::none(), // supply_cap - // option::none(), // debt_ceiling - // option::none(), // liquidation_protocol_fee - // option::none(), // unbacked_mint_cap - // option::some((0 as u256)), // e_mode_category - // option::some(true), // flash_loan_enabled - // ); - // - // // init the default interest rate strategy for the underlying_token_address - // let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); - // let base_variable_borrow_rate: u256 = 0; - // let variable_rate_slope1: u256 = 0; - // let variable_rate_slope2: u256 = 0; - // default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy(pool, - // underlying_token_address, - // optimal_usage_ratio, - // base_variable_borrow_rate, - // variable_rate_slope1, - // variable_rate_slope2,); - // - // // init user config for reserve index - // create_user_config_for_reserve(signer::address_of(flashloan_user), reserve_index, - // option::some(false), option::some(true)); - // - // // ----> mint underlying for the flashloan user - // // mint 100 underlying tokens for the flashloan user - // let mint_receiver_address = signer::address_of(flashloan_user); - // underlying_token_factory::mint(underlying_tokens_admin, mint_receiver_address, 100, - // underlying_token_address); - // let initial_user_balance = - // underlying_token_factory::balance_of(mint_receiver_address, - // underlying_token_address); - // // assert user balance of underlying - // assert!(initial_user_balance == 100, TEST_SUCCESS); - // // assert underlying supply - // assert!(underlying_token_factory::supply(underlying_token_address) - // == option::some(100), - // TEST_SUCCESS); - // - // // ----> flashloan user supplies - // // flashloan user supplies the underlying token to fill the pool before attempting to take a flashloan - // let supply_receiver_address = signer::address_of(flashloan_user); - // let supplied_amount: u64 = 50; - // supply_logic::supply(flashloan_user, - // underlying_token_address, - // (supplied_amount as u256), - // supply_receiver_address, - // 0); - // - // // > check emitted events - // let emitted_supply_events = emitted_events(); - // assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); - // - // // > check flashloan user (supplier) balance of underlying - // let supplier_balance = - // underlying_token_factory::balance_of(mint_receiver_address, - // underlying_token_address); - // assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); - // // > check underlying supply - // assert!(underlying_token_factory::supply(underlying_token_address) - // == option::some(100), - // TEST_SUCCESS); - // - // // ----> flashloan user takes a flashloan - // let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% - // let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% - // let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 - // let flashloan_receipt = - // flashloan_logic::flash_loan_simple(flashloan_user, - // signer::address_of(flashloan_user), - // underlying_token_address, - // (flashloan_amount as u256), - // 0, // referal code - // ); - // - // // check intermediate underlying balance - // let flashloan_taker_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_user), - // underlying_token_address); - // assert!(flashloan_taker_underlying_balance - // == supplier_balance + flashloan_amount, TEST_SUCCESS); - // - // // ----> flashloan user repays flashloan + premium - // flashloan_logic::pay_flash_loan_simple(flashloan_user, flashloan_receipt,); - // - // // check intermediate underlying balance for flashloan user - // let flashloan_taken_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_user), - // underlying_token_address); - // let flashloan_paid_premium = 3; // 10% * 25 = 2.5 = 3 - // assert!(flashloan_taken_underlying_balance - // == supplier_balance - flashloan_paid_premium, TEST_SUCCESS); - // - // // check emitted events - // let emitted_withdraw_events = emitted_events(); - // assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); - // } - // - // #[test(pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aave_std = @std, flashloan_payer = @0x042, flashloan_receiver = @0x043, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aptos_framework = @0x1, collector_account = @0x55,)] - // /// User takes a flashloan which is received by someone else. Either user or taker then repays a single asset flashloan - // fun simple_flashloan_different_payer_receiver( - // pool: &signer, - // aave_role_super_admin: &signer, - // mock_oracle: &signer, - // aave_std: &signer, - // flashloan_payer: &signer, - // flashloan_receiver: &signer, - // variable_tokens_admin: &signer, - // a_tokens_admin: &signer, - // underlying_tokens_admin: &signer, - // aptos_framework: &signer, - // collector_account: &signer, - // ) { - // // start the timer - // set_time_has_started_for_testing(aptos_framework); - // - // // add the test events feature flag - // change_feature_flags_for_testing(aave_std, vector[26], vector[]); - // - // // create a tokens admin account - // account::create_account_for_test(signer::address_of(a_tokens_admin)); - // - // // init the acl module and make aave_pool the asset listing/pool admin - // test_init_module(aave_role_super_admin); - // acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); - // acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); - // - // // init oracle - // test_init_oracle(mock_oracle); - // - // // init pool conigutrator and pool modules - // pool_config_init_reserves(pool); - // - // // init underlying tokens - // underlying_token_factory::test_init_module(pool); - // let underlying_token_name = utf8(b"TOKEN_1"); - // let underlying_token_symbol = utf8(b"T1"); - // let underlying_token_decimals = 3; - // let underlying_token_max_supply = 10000; - // underlying_token_factory::create_token(underlying_tokens_admin, - // underlying_token_max_supply, - // underlying_token_name, - // underlying_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""),); - // let underlying_token_address = underlying_token_factory::token_address( - // underlying_token_symbol); - // - // // init token base for tokens - // token_base::test_init_module(pool); - // - // // create variable tokens - // variable_token_factory::create_token(variable_tokens_admin, - // utf8(b"TEST_VAR_TOKEN_1"), - // utf8(b"VAR1"), - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // @0x033, // take random - // ); - // let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); - // - // //create a tokens - // let a_token_symbol = utf8(b"A1"); - // a_token_factory::create_token(a_tokens_admin, - // utf8(b"TEST_A_TOKEN_1"), - // a_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // underlying_token_address, // underlying asset address - // signer::address_of(collector_account), // treasury address - // ); - // let a_token_address = a_token_factory::token_address(utf8(b"A1")); - // - // // init and add a single reserve to the pool - // let reserve_index = - // create_reserve_with_config((underlying_token_decimals as u256), - // a_token_address, - // variable_token_address, - // underlying_token_address, - // option::none(), // ltv - // option::none(), // liq threshold - // option::none(), // liq bonus - // option::some((underlying_token_decimals as u256)), //decimals - // option::some(true), //active - // option::some(false), //frozen - // option::some(false), // paused - // option::some(true), // borrowable_in_isolation - // option::some(true), // siloed_borrowing - // option::some(true), // borrowing_enabled - // option::none(), // reserve_factor* - // option::none(), // borrow_cap - // option::none(), // supply_cap - // option::none(), // debt_ceiling - // option::none(), // liquidation_protocol_fee - // option::none(), // unbacked_mint_cap - // option::some((0 as u256)), // e_mode_category - // option::some(true), // flash_loan_enabled - // ); - // - // // init the default interest rate strategy for the underlying_token_address - // let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); - // let base_variable_borrow_rate: u256 = 0; - // let variable_rate_slope1: u256 = 0; - // let variable_rate_slope2: u256 = 0; - // default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy(pool, - // underlying_token_address, - // optimal_usage_ratio, - // base_variable_borrow_rate, - // variable_rate_slope1, - // variable_rate_slope2,); - // - // // init user configs for reserve index - // create_user_config_for_reserve(signer::address_of(flashloan_payer), reserve_index, - // option::some(false), option::some(true)); - // - // create_user_config_for_reserve(signer::address_of(flashloan_receiver), - // reserve_index, - // option::some(false), - // option::some(true)); - // - // // ----> mint underlying for flashloan payer and receiver - // // mint 100 underlying tokens for flashloan payer and receiver - // let mint_amount: u64 = 100; - // let users = vector[ - // signer::address_of(flashloan_payer), - // signer::address_of(flashloan_receiver)]; - // for (i in 0..vector::length(&users)) { - // underlying_token_factory::mint(underlying_tokens_admin, - // *vector::borrow(&users, i), - // mint_amount, - // underlying_token_address); - // let initial_user_balance = - // underlying_token_factory::balance_of(*vector::borrow(&users, i), - // underlying_token_address); - // // assert user balance of underlying - // assert!(initial_user_balance == mint_amount, TEST_SUCCESS); - // }; - // - // // ----> flashloan payer supplies - // // flashloan payer supplies the underlying token to fill the pool before attempting to take a flashloan - // let supply_receiver_address = signer::address_of(flashloan_payer); - // let supplied_amount: u64 = 50; - // supply_logic::supply(flashloan_payer, - // underlying_token_address, - // (supplied_amount as u256), - // supply_receiver_address, - // 0); - // - // // > check flashloan payer balance of underlying - // let initial_payer_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_payer), - // underlying_token_address); - // assert!(initial_payer_balance == mint_amount - supplied_amount, TEST_SUCCESS); - // // > check flashloan payer a_token balance after supply - // let supplier_a_token_balance = - // a_token_factory::balance_of(signer::address_of(flashloan_payer), a_token_address); - // assert!(supplier_a_token_balance == (supplied_amount as u256), TEST_SUCCESS); - // - // let initial_receiver_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_receiver), - // underlying_token_address); - // - // // ----> flashloan payer takes a flashloan but receiver is different - // let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% - // let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% - // let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 - // let flashloan_receipt = - // flashloan_logic::flash_loan_simple(flashloan_payer, - // signer::address_of(flashloan_receiver), // now the receiver expects to receive the flashloan - // underlying_token_address, - // (flashloan_amount as u256), - // 0, // referal code - // ); - // - // // check intermediate underlying balance for flashloan payer - // let flashloan_payer_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_payer), - // underlying_token_address); - // assert!(flashloan_payer_underlying_balance == initial_payer_balance, TEST_SUCCESS); // same balance as before - // - // // check intermediate underlying balance for flashloan receiver - // let flashloan_receiver_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_receiver), - // underlying_token_address); - // assert!(flashloan_receiver_underlying_balance - // == initial_receiver_balance + flashloan_amount, - // TEST_SUCCESS); // increased balance due to flashloan - // - // // ----> receiver repays flashloan + premium - // flashloan_logic::pay_flash_loan_simple(flashloan_receiver, flashloan_receipt,); - // - // // check intermediate underlying balance for flashloan payer - // let flashloan_payer_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_payer), - // underlying_token_address); - // assert!(flashloan_payer_underlying_balance == initial_payer_balance, TEST_SUCCESS); - // - // // check intermediate underlying balance for flashloan receiver - // let flashloan_receiver_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_receiver), - // underlying_token_address); - // let flashloan_paid_premium = 3; // 10% * 25 = 2.5 = 3 - // assert!(flashloan_receiver_underlying_balance - // == initial_receiver_balance - flashloan_paid_premium, - // TEST_SUCCESS); - // - // // check emitted events - // let emitted_withdraw_events = emitted_events(); - // assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); - // } - // - // #[test(pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aave_std = @std, flashloan_user = @0x042, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aptos_framework = @0x1, collector_account = @0x55,)] - // /// User takes and repays a single asset flashloan - // fun complex_flashloan_same_payer_receiver( - // pool: &signer, - // aave_role_super_admin: &signer, - // mock_oracle: &signer, - // aave_std: &signer, - // flashloan_user: &signer, - // variable_tokens_admin: &signer, - // a_tokens_admin: &signer, - // underlying_tokens_admin: &signer, - // aptos_framework: &signer, - // collector_account: &signer, - // ) { - // // start the timer - // set_time_has_started_for_testing(aptos_framework); - // - // // add the test events feature flag - // change_feature_flags_for_testing(aave_std, vector[26], vector[]); - // - // // create a tokens admin account - // account::create_account_for_test(signer::address_of(a_tokens_admin)); - // - // // init the acl module and make aave_pool the asset listing/pool admin - // test_init_module(aave_role_super_admin); - // acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); - // acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); - // - // // init oracle - // test_init_oracle(mock_oracle); - // - // // init pool conigutrator and pool modules - // pool_config_init_reserves(pool); - // - // // init underlying tokens - // underlying_token_factory::test_init_module(pool); - // let underlying_token_name = utf8(b"TOKEN_1"); - // let underlying_token_symbol = utf8(b"T1"); - // let underlying_token_decimals = 3; - // let underlying_token_max_supply = 10000; - // underlying_token_factory::create_token(underlying_tokens_admin, - // underlying_token_max_supply, - // underlying_token_name, - // underlying_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""),); - // let underlying_token_address = underlying_token_factory::token_address( - // underlying_token_symbol); - // - // // init token base for tokens - // token_base::test_init_module(pool); - // - // // create variable tokens - // variable_token_factory::create_token(variable_tokens_admin, - // utf8(b"TEST_VAR_TOKEN_1"), - // utf8(b"VAR1"), - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // @0x033, // take random - // ); - // let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); - // - // //create a tokens - // let a_token_symbol = utf8(b"A1"); - // a_token_factory::create_token(a_tokens_admin, - // utf8(b"TEST_A_TOKEN_1"), - // a_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // underlying_token_address, // underlying asset address - // signer::address_of(collector_account), // treasury address - // ); - // let a_token_address = a_token_factory::token_address(utf8(b"A1")); - // - // // init and add a single reserve to the pool - // let reserve_index = - // create_reserve_with_config((underlying_token_decimals as u256), - // a_token_address, - // variable_token_address, - // underlying_token_address, - // option::none(), // ltv - // option::none(), // liq threshold - // option::none(), // liq bonus - // option::some((underlying_token_decimals as u256)), //decimals - // option::some(true), //active - // option::some(false), //frozen - // option::some(false), // paused - // option::some(true), // borrowable_in_isolation - // option::some(true), // siloed_borrowing - // option::some(true), // borrowing_enabled - // option::none(), // reserve_factor* - // option::none(), // borrow_cap - // option::none(), // supply_cap - // option::none(), // debt_ceiling - // option::none(), // liquidation_protocol_fee - // option::none(), // unbacked_mint_cap - // option::some((0 as u256)), // e_mode_category - // option::some(true), // flash_loan_enabled - // ); - // - // // init the default interest rate strategy for the underlying_token_address - // let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); - // let base_variable_borrow_rate: u256 = 0; - // let variable_rate_slope1: u256 = 0; - // let variable_rate_slope2: u256 = 0; - // default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy(pool, - // underlying_token_address, - // optimal_usage_ratio, - // base_variable_borrow_rate, - // variable_rate_slope1, - // variable_rate_slope2,); - // - // // init user config for reserve index - // create_user_config_for_reserve(signer::address_of(flashloan_user), reserve_index, - // option::some(false), option::some(true)); - // - // // ----> mint underlying for the flashloan user - // // mint 100 underlying tokens for the flashloan user - // let mint_receiver_address = signer::address_of(flashloan_user); - // underlying_token_factory::mint(underlying_tokens_admin, mint_receiver_address, 100, - // underlying_token_address); - // let initial_user_balance = - // underlying_token_factory::balance_of(mint_receiver_address, - // underlying_token_address); - // // assert user balance of underlying - // assert!(initial_user_balance == 100, TEST_SUCCESS); - // // assert underlying supply - // assert!(underlying_token_factory::supply(underlying_token_address) - // == option::some(100), - // TEST_SUCCESS); - // - // // ----> flashloan user supplies - // // flashloan user supplies the underlying token to fill the pool before attempting to take a flashloan - // let supply_receiver_address = signer::address_of(flashloan_user); - // let supplied_amount: u64 = 50; - // supply_logic::supply(flashloan_user, - // underlying_token_address, - // (supplied_amount as u256), - // supply_receiver_address, - // 0); - // - // // > check emitted events - // let emitted_supply_events = emitted_events(); - // assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); - // - // // > check flashloan user (supplier) balance of underlying - // let supplier_balance = - // underlying_token_factory::balance_of(mint_receiver_address, - // underlying_token_address); - // assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); - // // > check underlying supply - // assert!(underlying_token_factory::supply(underlying_token_address) - // == option::some(100), - // TEST_SUCCESS); - // - // // ----> flashloan user takes a flashloan - // let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% - // let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% - // let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 - // let flashloan_receipts = - // flashloan_logic::flash_loan_simple(flashloan_user, - // signer::address_of(flashloan_user), - // vector[underlying_token_address], - // vector[(flashloan_amount as u256)], - // vector[user_config::get_interest_rate_mode_none()], // interest rate modes - // signer::address_of(flashloan_user), // on behalf of - // 0, // referal code - // flashloan_premium_to_protocol, - // flashloan_premium_total, - // false, // is_authorized_flash_borrower - // ); - // - // // check intermediate underlying balance - // let flashloan_taker_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_user), - // underlying_token_address); - // assert!(flashloan_taker_underlying_balance - // == supplier_balance + flashloan_amount, TEST_SUCCESS); - // - // // ----> flashloan user repays flashloan + premium - // flashloan_logic::pay_flash_loan_complex(flashloan_user, flashloan_receipts,); - // - // // check intermediate underlying balance for flashloan user - // let flashloan_taken_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_user), - // underlying_token_address); - // let flashloan_paid_premium = 3; // 10% * 25 = 2.5 = 3 - // assert!(flashloan_taken_underlying_balance - // == supplier_balance - flashloan_paid_premium, TEST_SUCCESS); - // - // // check emitted events - // let emitted_flashloan_events = emitted_events(); - // assert!(vector::length(&emitted_flashloan_events) == 1, TEST_SUCCESS); - // } - // - // #[test(pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aave_std = @std, flashloan_user = @0x042, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aptos_framework = @0x1, collector_account = @0x55,)] - // /// User takes and repays a single asset flashloan - // fun complex_flashloan_same_payer_receiver_authorized( - // pool: &signer, - // aave_role_super_admin: &signer, - // mock_oracle: &signer, - // aave_std: &signer, - // flashloan_user: &signer, - // variable_tokens_admin: &signer, - // a_tokens_admin: &signer, - // underlying_tokens_admin: &signer, - // aptos_framework: &signer, - // collector_account: &signer, - // ) { - // // start the timer - // set_time_has_started_for_testing(aptos_framework); - // - // // add the test events feature flag - // change_feature_flags_for_testing(aave_std, vector[26], vector[]); - // - // // create a tokens admin account - // account::create_account_for_test(signer::address_of(a_tokens_admin)); - // - // // init the acl module and make aave_pool the asset listing/pool admin - // test_init_module(aave_role_super_admin); - // acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); - // acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); - // - // // init oracle - // test_init_oracle(mock_oracle); - // - // // init pool conigutrator and pool modules - // pool_config_init_reserves(pool); - // - // // init underlying tokens - // underlying_token_factory::test_init_module(pool); - // let underlying_token_name = utf8(b"TOKEN_1"); - // let underlying_token_symbol = utf8(b"T1"); - // let underlying_token_decimals = 3; - // let underlying_token_max_supply = 10000; - // underlying_token_factory::create_token(underlying_tokens_admin, - // underlying_token_max_supply, - // underlying_token_name, - // underlying_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""),); - // let underlying_token_address = underlying_token_factory::token_address( - // underlying_token_symbol); - // - // // init token base for tokens - // token_base::test_init_module(pool); - // - // // create variable tokens - // variable_token_factory::create_token(variable_tokens_admin, - // utf8(b"TEST_VAR_TOKEN_1"), - // utf8(b"VAR1"), - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // @0x033, // take random - // ); - // let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); - // - // //create a tokens - // let a_token_symbol = utf8(b"A1"); - // a_token_factory::create_token(a_tokens_admin, - // utf8(b"TEST_A_TOKEN_1"), - // a_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // underlying_token_address, // underlying asset address - // signer::address_of(collector_account), // treasury address - // ); - // let a_token_address = a_token_factory::token_address(utf8(b"A1")); - // - // // init and add a single reserve to the pool - // let reserve_index = - // create_reserve_with_config((underlying_token_decimals as u256), - // a_token_address, - // variable_token_address, - // underlying_token_address, - // option::none(), // ltv - // option::none(), // liq threshold - // option::none(), // liq bonus - // option::some((underlying_token_decimals as u256)), //decimals - // option::some(true), //active - // option::some(false), //frozen - // option::some(false), // paused - // option::some(true), // borrowable_in_isolation - // option::some(true), // siloed_borrowing - // option::some(true), // borrowing_enabled - // option::none(), // reserve_factor* - // option::none(), // borrow_cap - // option::none(), // supply_cap - // option::none(), // debt_ceiling - // option::none(), // liquidation_protocol_fee - // option::none(), // unbacked_mint_cap - // option::some((0 as u256)), // e_mode_category - // option::some(true), // flash_loan_enabled - // ); - // - // // init the default interest rate strategy for the underlying_token_address - // let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); - // let base_variable_borrow_rate: u256 = 0; - // let variable_rate_slope1: u256 = 0; - // let variable_rate_slope2: u256 = 0; - // default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy(pool, - // underlying_token_address, - // optimal_usage_ratio, - // base_variable_borrow_rate, - // variable_rate_slope1, - // variable_rate_slope2,); - // - // // init user config for reserve index - // create_user_config_for_reserve(signer::address_of(flashloan_user), reserve_index, - // option::some(false), option::some(true)); - // - // // ----> mint underlying for the flashloan user - // // mint 100 underlying tokens for the flashloan user - // let mint_receiver_address = signer::address_of(flashloan_user); - // underlying_token_factory::mint(underlying_tokens_admin, mint_receiver_address, 100, - // underlying_token_address); - // let initial_user_balance = - // underlying_token_factory::balance_of(mint_receiver_address, - // underlying_token_address); - // // assert user balance of underlying - // assert!(initial_user_balance == 100, TEST_SUCCESS); - // // assert underlying supply - // assert!(underlying_token_factory::supply(underlying_token_address) - // == option::some(100), - // TEST_SUCCESS); - // - // // ----> flashloan user supplies - // // flashloan user supplies the underlying token to fill the pool before attempting to take a flashloan - // let supply_receiver_address = signer::address_of(flashloan_user); - // let supplied_amount: u64 = 50; - // supply_logic::supply(flashloan_user, - // underlying_token_address, - // (supplied_amount as u256), - // supply_receiver_address, - // 0); - // - // // > check emitted events - // let emitted_supply_events = emitted_events(); - // assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); - // - // // > check flashloan user (supplier) balance of underlying - // let supplier_balance = - // underlying_token_factory::balance_of(mint_receiver_address, - // underlying_token_address); - // assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); - // // > check underlying supply - // assert!(underlying_token_factory::supply(underlying_token_address) - // == option::some(100), - // TEST_SUCCESS); - // - // // ----> flashloan user takes a flashloan - // let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% - // let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% - // let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 - // let flashloan_receipts = - // flashloan_logic::flashloan(flashloan_user, - // signer::address_of(flashloan_user), - // vector[underlying_token_address], - // vector[(flashloan_amount as u256)], - // vector[user_config::get_interest_rate_mode_none()], // interest rate modes - // signer::address_of(flashloan_user), // on behalf of - // 0, // referal code - // ); - // - // // check intermediate underlying balance - // let flashloan_taker_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_user), - // underlying_token_address); - // assert!(flashloan_taker_underlying_balance - // == supplier_balance + flashloan_amount, TEST_SUCCESS); - // - // // ----> flashloan user repays flashloan + premium - // flashloan_logic::pay_flash_loan_complex(flashloan_user, flashloan_receipts,); - // - // // check intermediate underlying balance for flashloan user - // let flashloan_taken_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_user), - // underlying_token_address); - // let flashloan_paid_premium = 0; // because the user is authorized flash borrower - // assert!(flashloan_taken_underlying_balance - // == supplier_balance - flashloan_paid_premium, TEST_SUCCESS); - // - // // check emitted events - // let emitted_flashloan_events = emitted_events(); - // assert!(vector::length(&emitted_flashloan_events) == 1, TEST_SUCCESS); - // } - // - // #[test(pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aave_std = @std, flashloan_payer = @0x042, flashloan_receiver = @0x043, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aptos_framework = @0x1, collector_account = @0x55,)] - // /// User takes a complex flashloan which is received by someone else. Either user or taker then repays the complex flashloan - // fun complex_flashloan_different_payer_receiver( - // pool: &signer, - // aave_role_super_admin: &signer, - // mock_oracle: &signer, - // aave_std: &signer, - // flashloan_payer: &signer, - // flashloan_receiver: &signer, - // variable_tokens_admin: &signer, - // a_tokens_admin: &signer, - // underlying_tokens_admin: &signer, - // aptos_framework: &signer, - // collector_account: &signer, - // ) { - // // start the timer - // set_time_has_started_for_testing(aptos_framework); - // - // // add the test events feature flag - // change_feature_flags_for_testing(aave_std, vector[26], vector[]); - // - // // create a tokens admin account - // account::create_account_for_test(signer::address_of(a_tokens_admin)); - // - // // init the acl module and make aave_pool the asset listing/pool admin - // test_init_module(aave_role_super_admin); - // acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); - // acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); - // - // // init oracle - // test_init_oracle(mock_oracle); - // - // // init pool conigutrator and pool modules - // pool_config_init_reserves(pool); - // - // // init underlying tokens - // underlying_token_factory::test_init_module(pool); - // let underlying_token_name = utf8(b"TOKEN_1"); - // let underlying_token_symbol = utf8(b"T1"); - // let underlying_token_decimals = 3; - // let underlying_token_max_supply = 10000; - // underlying_token_factory::create_token(underlying_tokens_admin, - // underlying_token_max_supply, - // underlying_token_name, - // underlying_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""),); - // let underlying_token_address = underlying_token_factory::token_address( - // underlying_token_symbol); - // - // // init token base for tokens - // token_base::test_init_module(pool); - // - // // create variable tokens - // variable_token_factory::create_token(variable_tokens_admin, - // utf8(b"TEST_VAR_TOKEN_1"), - // utf8(b"VAR1"), - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // @0x033, // take random - // ); - // let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); - // - // //create a tokens - // let a_token_symbol = utf8(b"A1"); - // a_token_factory::create_token(a_tokens_admin, - // utf8(b"TEST_A_TOKEN_1"), - // a_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // underlying_token_address, // underlying asset address - // signer::address_of(collector_account), // treasury address - // ); - // let a_token_address = a_token_factory::token_address(utf8(b"A1")); - // - // // init and add a single reserve to the pool - // let reserve_index = - // create_reserve_with_config((underlying_token_decimals as u256), - // a_token_address, - // variable_token_address, - // underlying_token_address, - // option::none(), // ltv - // option::none(), // liq threshold - // option::none(), // liq bonus - // option::some((underlying_token_decimals as u256)), //decimals - // option::some(true), //active - // option::some(false), //frozen - // option::some(false), // paused - // option::some(true), // borrowable_in_isolation - // option::some(true), // siloed_borrowing - // option::some(true), // borrowing_enabled - // option::none(), // reserve_factor* - // option::none(), // borrow_cap - // option::none(), // supply_cap - // option::none(), // debt_ceiling - // option::none(), // liquidation_protocol_fee - // option::none(), // unbacked_mint_cap - // option::some((0 as u256)), // e_mode_category - // option::some(true), // flash_loan_enabled - // ); - // - // // init the default interest rate strategy for the underlying_token_address - // let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); - // let base_variable_borrow_rate: u256 = 0; - // let variable_rate_slope1: u256 = 0; - // let variable_rate_slope2: u256 = 0; - // default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy(pool, - // underlying_token_address, - // optimal_usage_ratio, - // base_variable_borrow_rate, - // variable_rate_slope1, - // variable_rate_slope2,); - // - // // init user configs for reserve index - // create_user_config_for_reserve(signer::address_of(flashloan_payer), reserve_index, - // option::some(false), option::some(true)); - // - // create_user_config_for_reserve(signer::address_of(flashloan_receiver), - // reserve_index, - // option::some(false), - // option::some(true)); - // - // // ----> mint underlying for flashloan payer and receiver - // // mint 100 underlying tokens for flashloan payer and receiver - // let mint_amount: u64 = 100; - // let users = vector[ - // signer::address_of(flashloan_payer), - // signer::address_of(flashloan_receiver)]; - // for (i in 0..vector::length(&users)) { - // underlying_token_factory::mint(underlying_tokens_admin, - // *vector::borrow(&users, i), - // mint_amount, - // underlying_token_address); - // let initial_user_balance = - // underlying_token_factory::balance_of(*vector::borrow(&users, i), - // underlying_token_address); - // // assert user balance of underlying - // assert!(initial_user_balance == mint_amount, TEST_SUCCESS); - // }; - // - // // ----> flashloan payer supplies - // // flashloan payer supplies the underlying token to fill the pool before attempting to take a flashloan - // let supply_receiver_address = signer::address_of(flashloan_payer); - // let supplied_amount: u64 = 50; - // supply_logic::supply(flashloan_payer, - // underlying_token_address, - // (supplied_amount as u256), - // supply_receiver_address, - // 0); - // - // // > check flashloan payer balance of underlying - // let initial_payer_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_payer), - // underlying_token_address); - // assert!(initial_payer_balance == mint_amount - supplied_amount, TEST_SUCCESS); - // // > check flashloan payer a_token balance after supply - // let supplier_a_token_balance = - // a_token_factory::balance_of(signer::address_of(flashloan_payer), a_token_address); - // assert!(supplier_a_token_balance == (supplied_amount as u256), TEST_SUCCESS); - // - // let initial_receiver_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_receiver), - // underlying_token_address); - // - // // ----> flashloan payer takes a flashloan but receiver is different - // let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% - // let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% - // let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 - // let flashloan_receipts = - // flashloan_logic::flashloan(flashloan_payer, - // signer::address_of(flashloan_receiver), - // vector[underlying_token_address], - // vector[(flashloan_amount as u256)], - // vector[user_config::get_interest_rate_mode_none()], // interest rate modes - // signer::address_of(flashloan_payer), // on behalf of - // 0, // referal code - // ); - // - // // check intermediate underlying balance for flashloan payer - // let flashloan_payer_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_payer), - // underlying_token_address); - // assert!(flashloan_payer_underlying_balance == initial_payer_balance, TEST_SUCCESS); // same balance as before - // - // // check intermediate underlying balance for flashloan receiver - // let flashloan_receiver_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_receiver), - // underlying_token_address); - // assert!(flashloan_receiver_underlying_balance - // == initial_receiver_balance + flashloan_amount, - // TEST_SUCCESS); // increased balance due to flashloan - // - // // ----> receiver repays flashloan + premium - // flashloan_logic::pay_flash_loan_complex(flashloan_receiver, flashloan_receipts,); - // - // // check intermediate underlying balance for flashloan payer - // let flashloan_payer_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_payer), - // underlying_token_address); - // assert!(flashloan_payer_underlying_balance == initial_payer_balance, TEST_SUCCESS); - // - // // check intermediate underlying balance for flashloan receiver - // let flashloan_receiver_underlying_balance = - // underlying_token_factory::balance_of(signer::address_of(flashloan_receiver), - // underlying_token_address); - // let flashloan_paid_premium = 3; // 10% * 25 = 2.5 = 3 - // assert!(flashloan_receiver_underlying_balance - // == initial_receiver_balance - flashloan_paid_premium, - // TEST_SUCCESS); - // - // // check emitted events - // let emitted_withdraw_events = emitted_events(); - // assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); - // } -} \ No newline at end of file + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, flashloan_user = @0x042, underlying_tokens_admin = @underlying_tokens)] + /// User takes and repays a single asset flashloan + fun simple_flashloan_same_payer_receiver( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + flashloan_user: &signer, + underlying_tokens_admin: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, true); + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + // get the reserve config for it + let reserve_data = get_reserve_data(underlying_token_address); + + // set flashloan premium + let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% + let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% + pool::set_flashloan_premiums_test( + (flashloan_premium_total as u128), (flashloan_premium_to_protocol as u128) + ); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(flashloan_user), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + // ----> mint underlying for the flashloan user + // mint 100 underlying tokens for the flashloan user + let mint_receiver_address = signer::address_of(flashloan_user); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + 100, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == 100, TEST_SUCCESS); + // assert underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + + // ----> flashloan user supplies + // flashloan user supplies the underlying token to fill the pool before attempting to take a flashloan + let supply_receiver_address = signer::address_of(flashloan_user); + let supplied_amount: u64 = 50; + supply_logic::supply( + flashloan_user, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + + // > check flashloan user (supplier) balance of underlying + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); + // > check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + + // ----> flashloan user takes a flashloan + let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 + let flashloan_receipt = + flashloan_logic::flash_loan_simple( + flashloan_user, + signer::address_of(flashloan_user), + underlying_token_address, + (flashloan_amount as u256), + 0, // referal code + ); + + // check intermediate underlying balance + let flashloan_taker_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_user), underlying_token_address + ); + assert!( + flashloan_taker_underlying_balance == supplier_balance + flashloan_amount, + TEST_SUCCESS, + ); + + // ----> flashloan user repays flashloan + premium + flashloan_logic::pay_flash_loan_simple(flashloan_user, flashloan_receipt); + + // check intermediate underlying balance for flashloan user + let flashloan_taken_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_user), underlying_token_address + ); + let flashloan_paid_premium = 3; // 10% * 25 = 2.5 = 3 + assert!( + flashloan_taken_underlying_balance == supplier_balance - flashloan_paid_premium, + TEST_SUCCESS, + ); + + // check emitted events + let emitted_withdraw_events = emitted_events(); + assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @std, flashloan_payer = @0x042, flashloan_receiver = @0x043, underlying_tokens_admin = @underlying_tokens)] + /// User takes a flashloan which is received by someone else. Either user or taker then repays a single asset flashloan + fun simple_flashloan_different_payer_receiver( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + flashloan_payer: &signer, + flashloan_receiver: &signer, + underlying_tokens_admin: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, true); + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + // get the reserve config for it + let reserve_data = get_reserve_data(underlying_token_address); + + // set flashloan premium + let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% + let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% + pool::set_flashloan_premiums_test( + (flashloan_premium_total as u128), (flashloan_premium_to_protocol as u128) + ); + + // init user configs for reserve index + create_user_config_for_reserve( + signer::address_of(flashloan_payer), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + create_user_config_for_reserve( + signer::address_of(flashloan_receiver), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + // ----> mint underlying for flashloan payer and receiver + // mint 100 underlying tokens for flashloan payer and receiver + let mint_amount: u64 = 100; + let users = vector[ + signer::address_of(flashloan_payer), + signer::address_of(flashloan_receiver)]; + for (i in 0..vector::length(&users)) { + mock_underlying_token_factory::mint( + underlying_tokens_admin, + *vector::borrow(&users, i), + mint_amount, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + *vector::borrow(&users, i), underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == mint_amount, TEST_SUCCESS); + }; + + // ----> flashloan payer supplies + // flashloan payer supplies the underlying token to fill the pool before attempting to take a flashloan + let supply_receiver_address = signer::address_of(flashloan_payer); + let supplied_amount: u64 = 50; + supply_logic::supply( + flashloan_payer, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check flashloan payer balance of underlying + let initial_payer_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_payer), underlying_token_address + ); + assert!(initial_payer_balance == mint_amount - supplied_amount, TEST_SUCCESS); + // > check flashloan payer a_token balance after supply + let a_token_address = + a_token_factory::token_address( + signer::address_of(aave_pool), + *vector::borrow(&atokens_symbols, 0), + ); + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(flashloan_payer), a_token_address + ); + let supplied_amount_scaled = + wad_ray_math::ray_div( + (supplied_amount as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + assert!(supplier_a_token_balance == supplied_amount_scaled, TEST_SUCCESS); + + let initial_receiver_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_receiver), underlying_token_address + ); + + // ----> flashloan payer takes a flashloan but receiver is different + let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 + let flashloan_receipt = + flashloan_logic::flash_loan_simple( + flashloan_payer, + signer::address_of(flashloan_receiver), // now the receiver expects to receive the flashloan + underlying_token_address, + (flashloan_amount as u256), + 0, // referal code + ); + + // check intermediate underlying balance for flashloan payer + let flashloan_payer_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_payer), underlying_token_address + ); + assert!(flashloan_payer_underlying_balance == initial_payer_balance, TEST_SUCCESS); // same balance as before + + // check intermediate underlying balance for flashloan receiver + let flashloan_receiver_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_receiver), underlying_token_address + ); + assert!( + flashloan_receiver_underlying_balance + == initial_receiver_balance + flashloan_amount, + TEST_SUCCESS, + ); // increased balance due to flashloan + + // ----> receiver repays flashloan + premium + flashloan_logic::pay_flash_loan_simple(flashloan_receiver, flashloan_receipt); + + // check intermediate underlying balance for flashloan payer + let flashloan_payer_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_payer), underlying_token_address + ); + assert!(flashloan_payer_underlying_balance == initial_payer_balance, TEST_SUCCESS); + + // check intermediate underlying balance for flashloan receiver + let flashloan_receiver_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_receiver), underlying_token_address + ); + let flashloan_paid_premium = 3; // 10% * 25 = 2.5 = 3 + assert!( + flashloan_receiver_underlying_balance + == initial_receiver_balance - flashloan_paid_premium, + TEST_SUCCESS, + ); + + // check emitted events + let emitted_withdraw_events = emitted_events(); + assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, flashloan_user = @0x042, underlying_tokens_admin = @underlying_tokens)] + /// User takes and repays a single asset flashloan + fun complex_flashloan_same_payer_receiver( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + flashloan_user: &signer, + underlying_tokens_admin: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, true); + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + // get the reserve config for it + let reserve_data = get_reserve_data(underlying_token_address); + + // set flashloan premium + let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% + let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% + pool::set_flashloan_premiums_test( + (flashloan_premium_total as u128), (flashloan_premium_to_protocol as u128) + ); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(flashloan_user), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + // ----> mint underlying for the flashloan user + // mint 100 underlying tokens for the flashloan user + let mint_receiver_address = signer::address_of(flashloan_user); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + 100, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == 100, TEST_SUCCESS); + // assert underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + + // ----> flashloan user supplies + // flashloan user supplies the underlying token to fill the pool before attempting to take a flashloan + let supply_receiver_address = signer::address_of(flashloan_user); + let supplied_amount: u64 = 50; + supply_logic::supply( + flashloan_user, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + + // > check flashloan user (supplier) balance of underlying + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); + // > check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + + // ----> flashloan user takes a flashloan + let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 + let flashloan_receipts = + flashloan_logic::flashloan( + flashloan_user, + signer::address_of(flashloan_user), + vector[underlying_token_address], + vector[(flashloan_amount as u256)], + vector[user_config::get_interest_rate_mode_none()], // interest rate modes + signer::address_of(flashloan_user), + 0, // referral code + ); + + // check intermediate underlying balance + let flashloan_taker_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_user), underlying_token_address + ); + assert!( + flashloan_taker_underlying_balance == supplier_balance + flashloan_amount, + TEST_SUCCESS, + ); + + // ----> flashloan user repays flashloan + premium + flashloan_logic::pay_flash_loan_complex(flashloan_user, flashloan_receipts); + + // check intermediate underlying balance for flashloan user + let flashloan_taken_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_user), underlying_token_address + ); + let flashloan_paid_premium = 3; // 10% * 25 = 2.5 = 3 + assert!( + flashloan_taken_underlying_balance == supplier_balance - flashloan_paid_premium, + TEST_SUCCESS, + ); + + // check emitted events + let emitted_flashloan_events = emitted_events(); + assert!(vector::length(&emitted_flashloan_events) == 1, TEST_SUCCESS); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, flashloan_user = @0x042, underlying_tokens_admin = @underlying_tokens)] + /// User takes and repays a single asset flashloan being authorized + fun complex_flashloan_same_payer_receiver_authorized( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + flashloan_user: &signer, + underlying_tokens_admin: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // grant the flashloan user an authorized borrower role + acl_manage::add_flash_borrower( + aave_role_super_admin, signer::address_of(flashloan_user) + ); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, true); + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + // get the reserve config for it + let reserve_data = get_reserve_data(underlying_token_address); + + // set flashloan premium + let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% + let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% + pool::set_flashloan_premiums_test( + (flashloan_premium_total as u128), (flashloan_premium_to_protocol as u128) + ); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(flashloan_user), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + // ----> mint underlying for the flashloan user + // mint 100 underlying tokens for the flashloan user + let mint_receiver_address = signer::address_of(flashloan_user); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + 100, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == 100, TEST_SUCCESS); + // assert underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + + // ----> flashloan user supplies + // flashloan user supplies the underlying token to fill the pool before attempting to take a flashloan + let supply_receiver_address = signer::address_of(flashloan_user); + let supplied_amount: u64 = 50; + supply_logic::supply( + flashloan_user, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + + // > check flashloan user (supplier) balance of underlying + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); + // > check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + + // ----> flashloan user takes a flashloan + let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 + let flashloan_receipts = + flashloan_logic::flashloan( + flashloan_user, + signer::address_of(flashloan_user), + vector[underlying_token_address], + vector[(flashloan_amount as u256)], + vector[user_config::get_interest_rate_mode_none()], // interest rate modes + signer::address_of(flashloan_user), + 0, // referral code + ); + + // check intermediate underlying balance + let flashloan_taker_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_user), underlying_token_address + ); + assert!( + flashloan_taker_underlying_balance == supplier_balance + flashloan_amount, + TEST_SUCCESS, + ); + + // ----> flashloan user repays flashloan + premium + flashloan_logic::pay_flash_loan_complex(flashloan_user, flashloan_receipts); + + // check intermediate underlying balance for flashloan user + let flashloan_taken_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_user), underlying_token_address + ); + let flashloan_paid_premium = 0; // because the user is authorized flash borrower + assert!( + flashloan_taken_underlying_balance == supplier_balance - flashloan_paid_premium, + TEST_SUCCESS, + ); + + // check emitted events + let emitted_flashloan_events = emitted_events(); + assert!(vector::length(&emitted_flashloan_events) == 1, TEST_SUCCESS); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @std, flashloan_payer = @0x042, flashloan_receiver = @0x043, underlying_tokens_admin = @underlying_tokens)] + /// User takes a complex flashloan which is received by someone else. Either user or taker then repays the complex flashloan + fun complex_flashloan_different_payer_receiver( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + flashloan_payer: &signer, + flashloan_receiver: &signer, + underlying_tokens_admin: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, true); + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + // get the reserve config for it + let reserve_data = get_reserve_data(underlying_token_address); + + // set flashloan premium + let flashloan_premium_total = get_percentage_factor() / 10; // 100/10 = 10% + let flashloan_premium_to_protocol = get_percentage_factor() / 20; // 100/20 = 5% + pool::set_flashloan_premiums_test( + (flashloan_premium_total as u128), (flashloan_premium_to_protocol as u128) + ); + + // init user configs for reserve index + create_user_config_for_reserve( + signer::address_of(flashloan_payer), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + create_user_config_for_reserve( + signer::address_of(flashloan_receiver), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + // ----> mint underlying for flashloan payer and receiver + // mint 100 underlying tokens for flashloan payer and receiver + let mint_amount: u64 = 100; + let users = vector[ + signer::address_of(flashloan_payer), + signer::address_of(flashloan_receiver)]; + for (i in 0..vector::length(&users)) { + mock_underlying_token_factory::mint( + underlying_tokens_admin, + *vector::borrow(&users, i), + mint_amount, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + *vector::borrow(&users, i), underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == mint_amount, TEST_SUCCESS); + }; + + // ----> flashloan payer supplies + // flashloan payer supplies the underlying token to fill the pool before attempting to take a flashloan + let supply_receiver_address = signer::address_of(flashloan_payer); + let supplied_amount: u64 = 50; + supply_logic::supply( + flashloan_payer, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check flashloan payer balance of underlying + let initial_payer_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_payer), underlying_token_address + ); + assert!(initial_payer_balance == mint_amount - supplied_amount, TEST_SUCCESS); + // > check flashloan payer a_token balance after supply + let a_token_address = + a_token_factory::token_address( + signer::address_of(aave_pool), + *vector::borrow(&atokens_symbols, 0), + ); + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(flashloan_payer), a_token_address + ); + let supplied_amount_scaled = + wad_ray_math::ray_div( + (supplied_amount as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + assert!(supplier_a_token_balance == supplied_amount_scaled, TEST_SUCCESS); + + let initial_receiver_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_receiver), underlying_token_address + ); + + // ----> flashloan payer takes a flashloan but receiver is different + let flashloan_amount = supplied_amount / 2; // half of the pool = 50/2 = 25 + let flashloan_receipts = + flashloan_logic::flashloan( + flashloan_payer, + signer::address_of(flashloan_receiver), + vector[underlying_token_address], + vector[(flashloan_amount as u256)], + vector[user_config::get_interest_rate_mode_none()], // interest rate modes + signer::address_of(flashloan_payer), // on behalf of + 0, // referal code + ); + + // check intermediate underlying balance for flashloan payer + let flashloan_payer_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_payer), underlying_token_address + ); + assert!(flashloan_payer_underlying_balance == initial_payer_balance, TEST_SUCCESS); // same balance as before + + // check intermediate underlying balance for flashloan receiver + let flashloan_receiver_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_receiver), underlying_token_address + ); + assert!( + flashloan_receiver_underlying_balance + == initial_receiver_balance + flashloan_amount, + TEST_SUCCESS, + ); // increased balance due to flashloan + + // ----> receiver repays flashloan + premium + flashloan_logic::pay_flash_loan_complex(flashloan_receiver, flashloan_receipts); + + // check intermediate underlying balance for flashloan payer + let flashloan_payer_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_payer), underlying_token_address + ); + assert!(flashloan_payer_underlying_balance == initial_payer_balance, TEST_SUCCESS); + + // check intermediate underlying balance for flashloan receiver + let flashloan_receiver_underlying_balance = + mock_underlying_token_factory::balance_of( + signer::address_of(flashloan_receiver), underlying_token_address + ); + let flashloan_paid_premium = 3; // 10% * 25 = 2.5 = 3 + assert!( + flashloan_receiver_underlying_balance + == initial_receiver_balance - flashloan_paid_premium, + TEST_SUCCESS, + ); + + // check emitted events + let emitted_withdraw_events = emitted_events(); + assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); + } +} diff --git a/aave-core/tests/aave-periphery/coin_wrapper_tests.move b/aave-core/tests/aave-periphery/coin_wrapper_tests.move index 9a31b94..196c9b6 100644 --- a/aave-core/tests/aave-periphery/coin_wrapper_tests.move +++ b/aave-core/tests/aave-periphery/coin_wrapper_tests.move @@ -7,9 +7,15 @@ module aave_pool::coin_wrapper_tests { use aptos_framework::fungible_asset::{Self}; use aptos_framework::aggregator_factory::initialize_aggregator_factory_for_test; use std::string::{Self, String}; - use aave_pool::package_manager::{Self}; + use aave_pool::package_manager::Self; use std::option; - use aave_pool::coin_wrapper::{initialize, test_unwrap, test_wrap, wrapper_address,}; + use aave_pool::coin_wrapper::{ + initialize, + test_unwrap, + test_wrap, + wrapper_address, + test_get_original, + }; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; @@ -33,12 +39,17 @@ module aave_pool::coin_wrapper_tests { initialize_aggregator_factory_for_test(framework); let (burn_ref, freeze_ref, mint_ref) = - coin::initialize(coin_creator, + coin::initialize( + coin_creator, string::utf8(b"Generic Coin"), string::utf8(b"GCC"), decimals, - monitor_supply); - move_to(coin_creator, GenericAptosCoinRefs { burn_ref, freeze_ref, mint_ref, }); + monitor_supply, + ); + move_to( + coin_creator, + GenericAptosCoinRefs { burn_ref, freeze_ref, mint_ref, }, + ); } inline fun get_coin_refs(account: &signer,): &GenericAptosCoinRefs { @@ -48,7 +59,8 @@ module aave_pool::coin_wrapper_tests { #[test(deployer = @resource_pm)] fun test_can_get_signer_package_manager(deployer: &signer) { package_manager::initialize_for_test(deployer); - let package_deployer_address = signer::address_of(&package_manager::get_signer_test()); + let package_deployer_address = + signer::address_of(&package_manager::get_signer_test()); assert!(package_deployer_address == signer::address_of(deployer), TEST_SUCCESS); } @@ -56,8 +68,10 @@ module aave_pool::coin_wrapper_tests { public fun test_can_set_get_signer_package_manager(deployer: &signer) { package_manager::initialize_for_test(deployer); package_manager::add_address_test(string::utf8(b"test"), @0xdeadbeef); - assert!(package_manager::get_address_test(string::utf8(b"test")) == @0xdeadbeef, - TEST_SUCCESS); + assert!( + package_manager::get_address_test(string::utf8(b"test")) == @0xdeadbeef, + TEST_SUCCESS, + ); } #[test(framework = @aptos_framework, aave_periphery = @aave_pool, deployer = @resource_pm, _aave_pool = @aave_pool, coin_holder = @0x123, _receiver = @0x234)] @@ -82,8 +96,14 @@ module aave_pool::coin_wrapper_tests { let coin_symbol = string::utf8(b"GCC"); let coin_decimals = 2; - initialize_aptos_coin(framework, aave_periphery, coin_decimals, true, coin_name, - coin_symbol); + initialize_aptos_coin( + framework, + aave_periphery, + coin_decimals, + true, + coin_name, + coin_symbol, + ); // register the holder coin::register(coin_holder); @@ -91,8 +111,9 @@ module aave_pool::coin_wrapper_tests { // mint some coins let token_holder_initial_balance = 100; let coins_minted = - coin::mint(token_holder_initial_balance, &get_coin_refs( - aave_periphery).mint_ref); + coin::mint( + token_holder_initial_balance, &get_coin_refs(aave_periphery).mint_ref + ); // deposit to holder coin::deposit(coinholder_addr, coins_minted); @@ -103,15 +124,19 @@ module aave_pool::coin_wrapper_tests { coin::withdraw(coin_holder, coin_withdraw_amount); // check the coin balance assert!(coin::value(&withdrawn_coins) == coin_withdraw_amount, TEST_SUCCESS); - assert!(coin::balance(signer::address_of(coin_holder)) - == token_holder_initial_balance - coin_withdraw_amount, - TEST_SUCCESS); + assert!( + coin::balance(signer::address_of(coin_holder)) + == token_holder_initial_balance - coin_withdraw_amount, + TEST_SUCCESS, + ); // coin holder now warps the coin using the wrapper and gets an equivalent fa let wrapped_fa = test_wrap(withdrawn_coins); // check the wrapper address balance - assert!(coin::balance(wrapper_address()) - == coin_withdraw_amount, TEST_SUCCESS); + assert!( + coin::balance(wrapper_address()) == coin_withdraw_amount, + TEST_SUCCESS, + ); // run assertions on the generated equivalent fa assert!(fungible_asset::amount(&wrapped_fa) == coin_withdraw_amount, TEST_SUCCESS); @@ -133,15 +158,85 @@ module aave_pool::coin_wrapper_tests { assert!(coin::value(&unwrapped_coins) == coin_withdraw_amount, TEST_SUCCESS); assert!(coin::decimals() == coin_decimals, TEST_SUCCESS); assert!(coin::symbol() == coin_symbol, TEST_SUCCESS); - assert!(coin::supply() - == option::some((token_holder_initial_balance as u128)), - TEST_SUCCESS); + assert!( + coin::supply() + == option::some((token_holder_initial_balance as u128)), + TEST_SUCCESS, + ); // send the coins back to the original coin holder aptos_account::deposit_coins(signer::address_of(coin_holder), unwrapped_coins); // check the original coin holder balance - assert!(coin::balance(signer::address_of(coin_holder)) - == token_holder_initial_balance, - TEST_SUCCESS); + assert!( + coin::balance(signer::address_of(coin_holder)) + == token_holder_initial_balance, + TEST_SUCCESS, + ); + } + + #[test(framework = @aptos_framework, aave_periphery = @aave_pool, deployer = @resource_pm, _aave_pool = @aave_pool, coin_holder = @0x123, _receiver = @0x234)] + fun test_get_orig( + framework: &signer, + aave_periphery: &signer, + deployer: &signer, + _aave_pool: &signer, + coin_holder: &signer, + _receiver: &signer + ) acquires GenericAptosCoinRefs { + // init the package manager + package_manager::initialize_for_test(deployer); + + // init the coin wrapper package + initialize(); + + // initialize old-style aptos coin + let coinholder_addr = signer::address_of(coin_holder); + account::create_account_for_test(coinholder_addr); + let coin_name = string::utf8(b"Generic Coin"); + let coin_symbol = string::utf8(b"GCC"); + let coin_decimals = 2; + + initialize_aptos_coin( + framework, + aave_periphery, + coin_decimals, + true, + coin_name, + coin_symbol, + ); + + // register the holder + coin::register(coin_holder); + + // mint some coins + let token_holder_initial_balance = 100; + let coins_minted = + coin::mint( + token_holder_initial_balance, + &get_coin_refs(aave_periphery).mint_ref, + ); + + // deposit to holder + coin::deposit(coinholder_addr, coins_minted); + + // withdraw some of the generic coin + let coin_withdraw_amount = 20; + let withdrawn_coins = + coin::withdraw(coin_holder, coin_withdraw_amount); + // check the coin balance + assert!(coin::value(&withdrawn_coins) == coin_withdraw_amount, TEST_SUCCESS); + assert!( + coin::balance(signer::address_of(coin_holder)) + == token_holder_initial_balance - coin_withdraw_amount, + TEST_SUCCESS, + ); + + // coin holder now warps the coin using the wrapper and gets an equivalent fa + let wrapped_fa = test_wrap(withdrawn_coins); + let fa_metadata = fungible_asset::metadata_from_asset(&wrapped_fa); + + test_get_original(fa_metadata); + let unwrapped_coins = test_unwrap(wrapped_fa); + aptos_account::deposit_coins(signer::address_of(coin_holder), unwrapped_coins); } } diff --git a/aave-core/tests/aave-periphery/collector_tests.move b/aave-core/tests/aave-periphery/collector_tests.move index 09a4937..c707e01 100644 --- a/aave-core/tests/aave-periphery/collector_tests.move +++ b/aave-core/tests/aave-periphery/collector_tests.move @@ -7,14 +7,21 @@ module aave_pool::collector_tests { use std::string::utf8; use aave_pool::standard_token::{Self}; use std::signer; - use aave_pool::collector::{Self, withdraw, init_module_test, deposit, get_collected_fees,}; + use aave_pool::collector::{ + Self, + withdraw, + init_module_test, + deposit, + get_collected_fees, + }; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; fun create_test_fa(creator: &signer): Object { let test_symbol = b"TEST"; - standard_token::initialize(creator, + standard_token::initialize( + creator, 0, utf8(b"Test Token"), utf8(test_symbol), @@ -23,9 +30,10 @@ module aave_pool::collector_tests { utf8(b"http://example.com"), vector[true, true, true], @0x1, - false,); - let metadata_address = object::create_object_address(&signer::address_of(creator), - test_symbol); + false, + ); + let metadata_address = + object::create_object_address(&signer::address_of(creator), test_symbol); object::address_to_object(metadata_address) } @@ -40,10 +48,13 @@ module aave_pool::collector_tests { // init acl acl_manage::test_init_module(aave_role_super_admin); // set fund admin - acl_manage::add_funds_admin(aave_role_super_admin, - signer::address_of(acl_fund_admin)); + acl_manage::add_funds_admin( + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted - assert!(acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)), TEST_SUCCESS); + assert!( + acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)), TEST_SUCCESS + ); // create test token let metadata = create_test_fa(fa_creator); @@ -51,14 +62,21 @@ module aave_pool::collector_tests { // mint coins to user let _creator_address = signer::address_of(fa_creator); let user_address = signer::address_of(user_account); - standard_token::mint_to_primary_stores(fa_creator, metadata, vector[user_address], - vector[100]); - assert!(primary_fungible_store::balance(user_address, metadata) == 100, TEST_SUCCESS); + standard_token::mint_to_primary_stores( + fa_creator, metadata, vector[user_address], vector[100] + ); + assert!( + primary_fungible_store::balance(user_address, metadata) == 100, TEST_SUCCESS + ); // user withdraws all fees he has let fa = - standard_token::withdraw_from_primary_stores(fa_creator, metadata, vector[user_address], - vector[100]); + standard_token::withdraw_from_primary_stores( + fa_creator, + metadata, + vector[user_address], + vector[100], + ); assert!(fungible_asset::amount(&fa) == 100, TEST_SUCCESS); // initialize the collector @@ -75,32 +93,43 @@ module aave_pool::collector_tests { // check user and collectpr's store balances assert!(get_collected_fees(metadata) == 50, 5); - assert!(primary_fungible_store::balance(user_address, metadata) == 50, TEST_SUCCESS); + assert!( + primary_fungible_store::balance(user_address, metadata) == 50, TEST_SUCCESS + ); } #[test(aave_role_super_admin = @aave_acl, collector_account = @aave_pool, acl_fund_admin = @0x111)] fun test_is_funds_admin_pass( - aave_role_super_admin: &signer, collector_account: &signer, acl_fund_admin: &signer, + aave_role_super_admin: &signer, + collector_account: &signer, + acl_fund_admin: &signer, ) { // init acl acl_manage::test_init_module(aave_role_super_admin); // set fund admin - acl_manage::add_funds_admin(aave_role_super_admin, - signer::address_of(acl_fund_admin)); + acl_manage::add_funds_admin( + aave_role_super_admin, signer::address_of(acl_fund_admin) + ); // assert role is granted - assert!(acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)), TEST_SUCCESS); + assert!( + acl_manage::is_funds_admin(signer::address_of(acl_fund_admin)), TEST_SUCCESS + ); // initialize the collector init_module_test(collector_account); // assert funds admin role is granted - assert!(collector::check_is_funds_admin(signer::address_of(acl_fund_admin)), - TEST_SUCCESS); + assert!( + collector::check_is_funds_admin(signer::address_of(acl_fund_admin)), + TEST_SUCCESS, + ); } #[test(aave_role_super_admin = @aave_acl, collector_account = @aave_pool, acl_fund_admin = @0x111)] fun test_is_funds_admin_fail( - aave_role_super_admin: &signer, collector_account: &signer, acl_fund_admin: &signer, + aave_role_super_admin: &signer, + collector_account: &signer, + acl_fund_admin: &signer, ) { // init acl acl_manage::test_init_module(aave_role_super_admin); @@ -114,7 +143,9 @@ module aave_pool::collector_tests { init_module_test(collector_account); // assert funds admin role is granted - assert!(!collector::check_is_funds_admin(signer::address_of(acl_fund_admin)), - TEST_SUCCESS); + assert!( + !collector::check_is_funds_admin(signer::address_of(acl_fund_admin)), + TEST_SUCCESS, + ); } } diff --git a/aave-core/tests/aave-periphery/emission_manager_tests.move b/aave-core/tests/aave-periphery/emission_manager_tests.move index d1a23bd..d484d2d 100644 --- a/aave-core/tests/aave-periphery/emission_manager_tests.move +++ b/aave-core/tests/aave-periphery/emission_manager_tests.move @@ -35,24 +35,30 @@ module aave_pool::emission_manager_tests { // init acl acl_manage::test_init_module(aave_role_super_admin); - aave_pool::rewards_controller::initialize(periphery_account, - signer::address_of(periphery_account)); + aave_pool::rewards_controller::initialize( + periphery_account, signer::address_of(periphery_account) + ); let user_account_addr = signer::address_of(user_account); let pull_rewards_transfer_strategy = aave_pool::transfer_strategy::create_pull_rewards_transfer_strategy( - user_account_addr, user_account_addr, user_account_addr); + user_account_addr, user_account_addr, user_account_addr + ); let rewards_addr = aave_pool::rewards_controller::rewards_controller_address(); - acl_manage::add_emission_admin_role(aave_role_super_admin, - signer::address_of(periphery_account)); + acl_manage::add_emission_admin_role( + aave_role_super_admin, signer::address_of(periphery_account) + ); initialize(periphery_account, rewards_addr); - set_pull_rewards_transfer_strategy(periphery_account, - signer::address_of(periphery_account), pull_rewards_transfer_strategy); + set_pull_rewards_transfer_strategy( + periphery_account, + signer::address_of(periphery_account), + pull_rewards_transfer_strategy, + ); } @@ -67,8 +73,9 @@ module aave_pool::emission_manager_tests { // init acl acl_manage::test_init_module(aave_role_super_admin); - aave_pool::rewards_controller::initialize(periphery_account, - signer::address_of(periphery_account)); + aave_pool::rewards_controller::initialize( + periphery_account, signer::address_of(periphery_account) + ); let user_account_addr = signer::address_of(user_account); @@ -77,17 +84,25 @@ module aave_pool::emission_manager_tests { let staked_token_transfer_strategy = aave_pool::transfer_strategy::create_staked_token_transfer_strategy( - user_account_addr, user_account_addr, mock_staked_token, user_account_addr); + user_account_addr, + user_account_addr, + mock_staked_token, + user_account_addr, + ); let rewards_addr = aave_pool::rewards_controller::rewards_controller_address(); - acl_manage::add_emission_admin_role(aave_role_super_admin, - signer::address_of(periphery_account)); + acl_manage::add_emission_admin_role( + aave_role_super_admin, signer::address_of(periphery_account) + ); initialize(periphery_account, rewards_addr); - set_staked_token_transfer_strategy(periphery_account, - signer::address_of(periphery_account), staked_token_transfer_strategy); + set_staked_token_transfer_strategy( + periphery_account, + signer::address_of(periphery_account), + staked_token_transfer_strategy, + ); } } diff --git a/aave-core/tests/aave-periphery/rewards_controller_tests.move b/aave-core/tests/aave-periphery/rewards_controller_tests.move index 76278ae..70af0da 100644 --- a/aave-core/tests/aave-periphery/rewards_controller_tests.move +++ b/aave-core/tests/aave-periphery/rewards_controller_tests.move @@ -40,21 +40,25 @@ module aave_pool::rewards_controller_tests { // init acl acl_manage::test_init_module(aave_role_super_admin); - aave_pool::rewards_controller::initialize(periphery_account, - signer::address_of(periphery_account)); + aave_pool::rewards_controller::initialize( + periphery_account, signer::address_of(periphery_account) + ); let user_account_addr = signer::address_of(user_account); let pull_rewards_transfer_strategy = aave_pool::transfer_strategy::create_pull_rewards_transfer_strategy( - user_account_addr, user_account_addr, user_account_addr); + user_account_addr, user_account_addr, user_account_addr + ); let rewards_addr = aave_pool::rewards_controller::rewards_controller_address(); - set_pull_rewards_transfer_strategy(periphery_account, + set_pull_rewards_transfer_strategy( + periphery_account, signer::address_of(periphery_account), pull_rewards_transfer_strategy, - rewards_addr); + rewards_addr, + ); } @@ -69,8 +73,9 @@ module aave_pool::rewards_controller_tests { // init acl acl_manage::test_init_module(aave_role_super_admin); - aave_pool::rewards_controller::initialize(periphery_account, - signer::address_of(periphery_account)); + aave_pool::rewards_controller::initialize( + periphery_account, signer::address_of(periphery_account) + ); let user_account_addr = signer::address_of(user_account); @@ -79,14 +84,20 @@ module aave_pool::rewards_controller_tests { let staked_token_transfer_strategy = aave_pool::transfer_strategy::create_staked_token_transfer_strategy( - user_account_addr, user_account_addr, mock_staked_token, user_account_addr); + user_account_addr, + user_account_addr, + mock_staked_token, + user_account_addr, + ); let rewards_addr = aave_pool::rewards_controller::rewards_controller_address(); - set_staked_token_transfer_strategy(periphery_account, + set_staked_token_transfer_strategy( + periphery_account, signer::address_of(periphery_account), staked_token_transfer_strategy, - rewards_addr); + rewards_addr, + ); } @@ -101,8 +112,9 @@ module aave_pool::rewards_controller_tests { // init acl acl_manage::test_init_module(aave_role_super_admin); - aave_pool::rewards_controller::initialize(periphery_account, - signer::address_of(periphery_account)); + aave_pool::rewards_controller::initialize( + periphery_account, signer::address_of(periphery_account) + ); let user_account_addr = signer::address_of(user_account); @@ -111,7 +123,11 @@ module aave_pool::rewards_controller_tests { let _staked_token_transfer_strategy = aave_pool::transfer_strategy::create_staked_token_transfer_strategy( - user_account_addr, user_account_addr, mock_staked_token, user_account_addr); + user_account_addr, + user_account_addr, + mock_staked_token, + user_account_addr, + ); let rewards_addr = aave_pool::rewards_controller::rewards_controller_address(); @@ -131,8 +147,9 @@ module aave_pool::rewards_controller_tests { // init acl acl_manage::test_init_module(aave_role_super_admin); - aave_pool::rewards_controller::initialize(periphery_account, - signer::address_of(periphery_account)); + aave_pool::rewards_controller::initialize( + periphery_account, signer::address_of(periphery_account) + ); let user_account_addr = signer::address_of(user_account); @@ -141,7 +158,11 @@ module aave_pool::rewards_controller_tests { let _staked_token_transfer_strategy = aave_pool::transfer_strategy::create_staked_token_transfer_strategy( - user_account_addr, user_account_addr, mock_staked_token, user_account_addr); + user_account_addr, + user_account_addr, + mock_staked_token, + user_account_addr, + ); let rewards_addr = aave_pool::rewards_controller::rewards_controller_address(); @@ -162,8 +183,9 @@ module aave_pool::rewards_controller_tests { // init acl acl_manage::test_init_module(aave_role_super_admin); - aave_pool::rewards_controller::initialize(periphery_account, - signer::address_of(periphery_account)); + aave_pool::rewards_controller::initialize( + periphery_account, signer::address_of(periphery_account) + ); let user_account_addr = signer::address_of(user_account); @@ -172,7 +194,11 @@ module aave_pool::rewards_controller_tests { let _staked_token_transfer_strategy = aave_pool::transfer_strategy::create_staked_token_transfer_strategy( - user_account_addr, user_account_addr, mock_staked_token, user_account_addr); + user_account_addr, + user_account_addr, + mock_staked_token, + user_account_addr, + ); let rewards_addr = aave_pool::rewards_controller::rewards_controller_address(); diff --git a/aave-core/tests/aave-pool/default_reserve_interest_rate_strategy_tests.move b/aave-core/tests/aave-pool/default_reserve_interest_rate_strategy_tests.move index 5952a96..f2b38ed 100644 --- a/aave-core/tests/aave-pool/default_reserve_interest_rate_strategy_tests.move +++ b/aave-core/tests/aave-pool/default_reserve_interest_rate_strategy_tests.move @@ -45,26 +45,38 @@ module aave_pool::default_reserve_interest_rate_strategy_tests { let variable_rate_slope1: u256 = 200; let variable_rate_slope2: u256 = 300; let max_excess_usage_ratio = wad_ray_math::ray() - optimal_usage_ratio; - set_reserve_interest_rate_strategy(pool, + set_reserve_interest_rate_strategy( + pool, asset_address, optimal_usage_ratio, base_variable_borrow_rate, variable_rate_slope1, - variable_rate_slope2,); + variable_rate_slope2, + ); // assertions on getters - assert!(get_max_excess_usage_ratio(asset_address) - == max_excess_usage_ratio, TEST_SUCCESS); - assert!(get_optimal_usage_ratio(asset_address) == optimal_usage_ratio, TEST_SUCCESS); - assert!(get_variable_rate_slope1(asset_address) == variable_rate_slope1, - TEST_SUCCESS); - assert!(get_variable_rate_slope2(asset_address) == variable_rate_slope2, - TEST_SUCCESS); - assert!(get_base_variable_borrow_rate(asset_address) - == base_variable_borrow_rate, TEST_SUCCESS); - assert!(get_max_variable_borrow_rate(asset_address) - == base_variable_borrow_rate + variable_rate_slope1 + variable_rate_slope2, - TEST_SUCCESS); + assert!( + get_max_excess_usage_ratio(asset_address) == max_excess_usage_ratio, + TEST_SUCCESS, + ); + assert!( + get_optimal_usage_ratio(asset_address) == optimal_usage_ratio, TEST_SUCCESS + ); + assert!( + get_variable_rate_slope1(asset_address) == variable_rate_slope1, TEST_SUCCESS + ); + assert!( + get_variable_rate_slope2(asset_address) == variable_rate_slope2, TEST_SUCCESS + ); + assert!( + get_base_variable_borrow_rate(asset_address) == base_variable_borrow_rate, + TEST_SUCCESS, + ); + assert!( + get_max_variable_borrow_rate(asset_address) + == base_variable_borrow_rate + variable_rate_slope1 + variable_rate_slope2, + TEST_SUCCESS, + ); } #[test(pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, aptos_framework = @0x1,)] diff --git a/aave-core/tests/aave-pool/emode_logic_tests.move b/aave-core/tests/aave-pool/emode_logic_tests.move index 75f1db7..59aba4e 100644 --- a/aave-core/tests/aave-pool/emode_logic_tests.move +++ b/aave-core/tests/aave-pool/emode_logic_tests.move @@ -3,11 +3,21 @@ module aave_pool::emode_logic_tests { use std::features::change_feature_flags_for_testing; use std::option::Self; use std::signer; - use std::string::utf8; + use std::string::{utf8, String}; use std::vector; + use aptos_std::string_utils; + use aptos_framework::account; use aptos_framework::event::emitted_events; + use aave_acl::acl_manage; + use aave_math::wad_ray_math; + use aave_mock_oracle::oracle; use aave_mock_oracle::oracle::test_init_oracle; + use aave_pool::default_reserve_interest_rate_strategy; + use aave_pool::pool_configurator; + use aave_pool::mock_underlying_token_factory; + use aave_pool::token_base; + use aave_pool::collector; use aave_pool::emode_logic::{ configure_emode_category, @@ -22,243 +32,417 @@ module aave_pool::emode_logic_tests { set_user_emode, UserEModeSet, }; - use aave_pool::pool::test_init_pool; - use aave_pool::pool_tests::{create_reserve_with_config, create_user_config_for_reserve}; + use aave_pool::pool::{get_reserve_data, get_reserve_id}; + use aave_pool::pool_tests::{create_user_config_for_reserve}; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; -// -// #[test(pool = @aave_pool,)] -// #[expected_failure(abort_code = 16)] -// fun zero_emode_id_failure(pool: &signer) { -// // init the emode -// init_emode(pool); -// -// // configure an illegal emode category -// let id: u8 = 0; -// let ltv: u16 = 100; -// let liquidation_threshold: u16 = 200; -// let liquidation_bonus: u16 = 300; -// let price_source: address = @0x01; -// let label = utf8(b"MODE1"); -// configure_emode_category(id, ltv, liquidation_threshold, liquidation_bonus, -// price_source, label); -// } -// -// #[test(pool = @aave_pool,)] -// fun get_nonexisting_emode_category(pool: &signer) { -// // init the emode -// init_emode(pool); -// -// // get an non-existing emode category -// let id: u8 = 3; -// let (ltv, liquidation_threshold, emode_asset_price) = get_emode_configuration(id); -// assert!(ltv == 0, TEST_SUCCESS); -// assert!(liquidation_threshold == 0, TEST_SUCCESS); -// assert!(emode_asset_price == 0, TEST_SUCCESS); -// } -// -// #[test(pool = @aave_pool, mock_oracle = @aave_mock_oracle,)] -// fun test_emode_config(pool: &signer, mock_oracle: &signer,) { -// // init oracle -// test_init_oracle(mock_oracle); -// -// // init the emode -// init_emode(pool); -// -// // configure and assert two emode categories -// let id1: u8 = 1; -// let ltv1: u16 = 100; -// let liquidation_threshold1: u16 = 200; -// let liquidation_bonus1: u16 = 300; -// let price_source1: address = @0x01; -// let label1 = utf8(b"MODE1"); -// configure_emode_category(id1, -// ltv1, -// liquidation_threshold1, -// liquidation_bonus1, -// price_source1, -// label1); -// let emode_data1 = get_emode_category_data(id1); -// assert!(get_emode_category_liquidation_bonus(&emode_data1) -// == liquidation_bonus1, TEST_SUCCESS); -// assert!(get_emode_category_liquidation_threshold(&emode_data1) -// == liquidation_threshold1, -// TEST_SUCCESS); -// assert!(get_emode_category_price_source(&emode_data1) == price_source1, TEST_SUCCESS); -// let (ltv, liquidation_threshold, _emode_asset_price) = get_emode_configuration(id1); -// assert!(ltv == (ltv1 as u256), TEST_SUCCESS); -// assert!(liquidation_threshold == (liquidation_threshold1 as u256), TEST_SUCCESS); -// -// let id2: u8 = 2; -// let ltv2: u16 = 101; -// let liquidation_threshold2: u16 = 201; -// let liquidation_bonus2: u16 = 301; -// let price_source2: address = @0x02; -// let label2 = utf8(b"MODE2"); -// configure_emode_category(id2, -// ltv2, -// liquidation_threshold2, -// liquidation_bonus2, -// price_source2, -// label2); -// let emode_data2 = get_emode_category_data(id2); -// assert!(get_emode_category_liquidation_bonus(&emode_data2) -// == liquidation_bonus2, TEST_SUCCESS); -// assert!(get_emode_category_liquidation_threshold(&emode_data2) -// == liquidation_threshold2, -// TEST_SUCCESS); -// assert!(get_emode_category_price_source(&emode_data2) == price_source2, TEST_SUCCESS); -// let (ltv, liquidation_threshold, _emode_asset_price) = get_emode_configuration(id2); -// assert!(ltv == (ltv2 as u256), TEST_SUCCESS); -// assert!(liquidation_threshold == (liquidation_threshold2 as u256), TEST_SUCCESS); -// } -// -// #[test(pool = @aave_pool, mock_oracle = @aave_mock_oracle, user = @0x01, aave_std = @std,)] -// fun test_legitimate_user_emode( -// pool: &signer, mock_oracle: &signer, user: &signer, aave_std: &signer, -// ) { -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // init oracle -// test_init_oracle(mock_oracle); -// -// // init the emode -// init_emode(pool); -// // define an emode cat for reserve and user -// let emode_cat_id1: u8 = 1; -// // configure an emode category -// let ltv1: u16 = 100; -// let liquidation_threshold1: u16 = 200; -// let liquidation_bonus1: u16 = 300; -// let price_source1: address = @0x01; -// let label1 = utf8(b"MODE1"); -// configure_emode_category(emode_cat_id1, -// ltv1, -// liquidation_threshold1, -// liquidation_bonus1, -// price_source1, -// label1); -// -// // init a reserve -// test_init_pool(pool); -// -// let underlying_asset_decimals = 2; -// let a_token_tmpl = @0x011; -// let variable_debt_token_addr = @0x013; -// let underlying_asset_addr = @0x015; -// -// let reserve_index = -// create_reserve_with_config(underlying_asset_decimals, -// a_token_tmpl, -// variable_debt_token_addr, -// underlying_asset_addr, -// option::none(), // ltv -// option::none(), // liq threshold -// option::none(), // liq bonus -// option::some(2), //decimals -// option::some(true), //active -// option::some(false), //frozen -// option::some(false), // paused -// option::some(true), // borrowable_in_isolation -// option::some(true), // siloed_borrowing -// option::some(true), // borrowing_enabled -// option::none(), // reserve_factor -// option::none(), // borrow_cap -// option::none(), // supply_cap -// option::none(), // debt_ceiling -// option::none(), // liquidation_protocol_fee -// option::none(), // unbacked_mint_cap -// option::some((emode_cat_id1 as u256)), // e_mode_category -// option::some(true), // flash_loan_enabled -// ); -// -// // init user config for reserve index -// create_user_config_for_reserve(signer::address_of(user), reserve_index, -// option::some(true), option::some(true)); -// -// // set user emode -// set_user_emode(user, emode_cat_id1); -// -// // get and assert user emode -// let user_emode = get_user_emode(signer::address_of(user)); -// assert!(user_emode == (emode_cat_id1 as u256), TEST_SUCCESS); -// -// assert!(is_in_emode_category(user_emode, (emode_cat_id1 as u256)), TEST_SUCCESS); -// assert!(!is_in_emode_category(user_emode, (2 as u256)), TEST_SUCCESS); -// -// // check emitted events -// let emitted_events = emitted_events(); -// // make sure event of type was emitted -// assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); -// } -// -// #[test(pool = @aave_pool, mock_oracle = @aave_mock_oracle, user = @0x01, aave_std = @std,)] -// #[expected_failure(abort_code = 58)] -// fun test_user_emode_with_0_reserve( -// pool: &signer, mock_oracle: &signer, user: &signer, aave_std: &signer, -// ) { -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // init oracle -// test_init_oracle(mock_oracle); -// -// // init the emode -// init_emode(pool); -// // define an emode cat for reserve and user -// let emode_cat_id1: u8 = 1; -// // configure an emode category -// let ltv1: u16 = 100; -// let liquidation_threshold1: u16 = 200; -// let liquidation_bonus1: u16 = 300; -// let price_source1: address = @0x01; -// let label1 = utf8(b"MODE1"); -// configure_emode_category(emode_cat_id1, -// ltv1, -// liquidation_threshold1, -// liquidation_bonus1, -// price_source1, -// label1); -// -// // init a reserve with 0 emod category -// test_init_pool(pool); -// -// let underlying_asset_decimals = 2; -// let a_token_tmpl = @0x011; -// let variable_debt_token_addr = @0x013; -// let underlying_asset_addr = @0x015; -// let reserve_index = -// create_reserve_with_config(underlying_asset_decimals, -// a_token_tmpl, -// variable_debt_token_addr, -// underlying_asset_addr, -// option::none(), // ltv -// option::none(), // liq threshold -// option::none(), // liq bonus -// option::some(2), //decimals -// option::some(true), //active -// option::some(false), //frozen -// option::some(false), // paused -// option::some(true), // borrowable_in_isolation -// option::some(true), // siloed_borrowing -// option::some(true), // borrowing_enabled -// option::none(), // reserve_factor -// option::none(), // borrow_cap -// option::none(), // supply_cap -// option::none(), // debt_ceiling -// option::none(), // liquidation_protocol_fee -// option::none(), // unbacked_mint_cap -// option::none(), // e_mode_category -// option::some(true), // flash_loan_enabled -// ); -// -// // init user config for reserve index -// create_user_config_for_reserve(signer::address_of(user), reserve_index, -// option::some(true), option::some(true)); -// -// // set user emode -// set_user_emode(user, 2); -// } + + #[test(pool = @aave_pool,)] + #[expected_failure(abort_code = 16)] + fun zero_emode_id_failure(pool: &signer) { + // init the emode + init_emode(pool); + + // configure an illegal emode category + let id: u8 = 0; + let ltv: u16 = 100; + let liquidation_threshold: u16 = 200; + let liquidation_bonus: u16 = 300; + let price_source: address = @0x01; + let label = utf8(b"MODE1"); + configure_emode_category( + id, + ltv, + liquidation_threshold, + liquidation_bonus, + price_source, + label, + ); + } + + #[test(pool = @aave_pool,)] + fun get_nonexisting_emode_category(pool: &signer) { + // init the emode + init_emode(pool); + + // get an non-existing emode category + let id: u8 = 3; + let (ltv, liquidation_threshold, emode_asset_price) = get_emode_configuration(id); + assert!(ltv == 0, TEST_SUCCESS); + assert!(liquidation_threshold == 0, TEST_SUCCESS); + assert!(emode_asset_price == 0, TEST_SUCCESS); + } + + #[test(pool = @aave_pool, mock_oracle = @aave_mock_oracle,)] + fun test_emode_config(pool: &signer, mock_oracle: &signer,) { + // init oracle + test_init_oracle(mock_oracle); + + // init the emode + init_emode(pool); + + // configure and assert two emode categories + let id1: u8 = 1; + let ltv1: u16 = 100; + let liquidation_threshold1: u16 = 200; + let liquidation_bonus1: u16 = 300; + let price_source1: address = @0x01; + let label1 = utf8(b"MODE1"); + configure_emode_category( + id1, + ltv1, + liquidation_threshold1, + liquidation_bonus1, + price_source1, + label1, + ); + let emode_data1 = get_emode_category_data(id1); + assert!( + get_emode_category_liquidation_bonus(&emode_data1) == liquidation_bonus1, + TEST_SUCCESS, + ); + assert!( + get_emode_category_liquidation_threshold(&emode_data1) == liquidation_threshold1, + TEST_SUCCESS, + ); + assert!( + get_emode_category_price_source(&emode_data1) == price_source1, TEST_SUCCESS + ); + let (ltv, liquidation_threshold, _emode_asset_price) = + get_emode_configuration(id1); + assert!(ltv == (ltv1 as u256), TEST_SUCCESS); + assert!(liquidation_threshold == (liquidation_threshold1 as u256), TEST_SUCCESS); + + let id2: u8 = 2; + let ltv2: u16 = 101; + let liquidation_threshold2: u16 = 201; + let liquidation_bonus2: u16 = 301; + let price_source2: address = @0x02; + let label2 = utf8(b"MODE2"); + configure_emode_category( + id2, + ltv2, + liquidation_threshold2, + liquidation_bonus2, + price_source2, + label2, + ); + let emode_data2 = get_emode_category_data(id2); + assert!( + get_emode_category_liquidation_bonus(&emode_data2) == liquidation_bonus2, + TEST_SUCCESS, + ); + assert!( + get_emode_category_liquidation_threshold(&emode_data2) == liquidation_threshold2, + TEST_SUCCESS, + ); + assert!( + get_emode_category_price_source(&emode_data2) == price_source2, TEST_SUCCESS + ); + let (ltv, liquidation_threshold, _emode_asset_price) = + get_emode_configuration(id2); + assert!(ltv == (ltv2 as u256), TEST_SUCCESS); + assert!(liquidation_threshold == (liquidation_threshold2 as u256), TEST_SUCCESS); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens, user = @0x042,)] + fun test_legitimate_user_emode( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + user: &signer, + ) { + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + + // create the underlying token + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare a and var tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // define an emode cat for reserve and user + let emode_cat_id: u8 = 1; + // configure an emode category + let ltv: u16 = 100; + let liquidation_threshold: u16 = 200; + let liquidation_bonus: u16 = 300; + let price_source: address = signer::address_of(mock_oracle); + let label = utf8(b"MODE1"); + configure_emode_category( + emode_cat_id, + ltv, + liquidation_threshold, + liquidation_bonus, + price_source, + label, + ); + + // get the reserve config + let underlying_asset_addr = *vector::borrow(&underlying_assets, 0); + let reserve_data = get_reserve_data(underlying_asset_addr); + pool_configurator::set_asset_emode_category( + aave_pool, underlying_asset_addr, emode_cat_id + ); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(user), + (get_reserve_id(&reserve_data) as u256), + option::some(true), + option::some(true), + ); + + // set user emode + set_user_emode(user, emode_cat_id); + + // get and assert user emode + let user_emode = get_user_emode(signer::address_of(user)); + assert!(user_emode == (emode_cat_id as u256), TEST_SUCCESS); + + assert!(is_in_emode_category(user_emode, (emode_cat_id as u256)), TEST_SUCCESS); + assert!( + !is_in_emode_category(user_emode, (emode_cat_id + 1 as u256)), TEST_SUCCESS + ); + + // check emitted events + let emitted_events = emitted_events(); + // make sure event of type was emitted + assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens, user = @0x042,)] + #[expected_failure(abort_code = 58)] + fun test_user_emode_with_non_existing_user_emode( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + user: &signer, + ) { + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prep a and var tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // define an emode cat for reserve and user + let emode_cat_id: u8 = 1; + // configure an emode category + let ltv: u16 = 100; + let liquidation_threshold: u16 = 200; + let liquidation_bonus: u16 = 300; + let price_source: address = signer::address_of(mock_oracle); + let label = utf8(b"MODE1"); + configure_emode_category( + emode_cat_id, + ltv, + liquidation_threshold, + liquidation_bonus, + price_source, + label, + ); + + // get the reserve config + let underlying_asset_addr = *vector::borrow(&underlying_assets, 0); + let reserve_data = get_reserve_data(underlying_asset_addr); + pool_configurator::set_asset_emode_category( + aave_pool, underlying_asset_addr, emode_cat_id + ); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(user), + (get_reserve_id(&reserve_data) as u256), + option::some(true), + option::some(true), + ); + + // set user emode + let non_existing_emode_id = emode_cat_id + 1; + set_user_emode(user, non_existing_emode_id); + } } diff --git a/aave-core/tests/aave-pool/pool_addresses_provider_tests.move b/aave-core/tests/aave-pool/pool_addresses_provider_tests.move index 0457710..46feacf 100644 --- a/aave-core/tests/aave-pool/pool_addresses_provider_tests.move +++ b/aave-core/tests/aave-pool/pool_addresses_provider_tests.move @@ -42,7 +42,9 @@ module aave_pool::pool_addresses_provider_tests { const TEST_FAILED: u64 = 2; #[test(deployer = @aave_pool, super_admin = @aave_acl, fx = @std)] - fun test_market_id(deployer: &signer, super_admin: &signer, fx: &signer) { + fun test_market_id( + deployer: &signer, super_admin: &signer, fx: &signer + ) { let new_market_id = b"MAIN_MARKET"; // add the test events feature flag change_feature_flags_for_testing(fx, vector[26], vector[]); @@ -51,7 +53,10 @@ module aave_pool::pool_addresses_provider_tests { // set market id set_market_id(super_admin, string::utf8(new_market_id)); // check the new market id via getter - assert!(get_market_id() == option::some(string::utf8(new_market_id)), TEST_SUCCESS); + assert!( + get_market_id() == option::some(string::utf8(new_market_id)), + TEST_SUCCESS, + ); // check emitted events let market_id_set_events = emitted_events(); // make sure event of type was emitted @@ -74,9 +79,11 @@ module aave_pool::pool_addresses_provider_tests { // check has mapped account assert!(has_id_mapped_account(string::utf8(id)), TEST_SUCCESS); // test get market id address - assert!(get_address(string::utf8(id)) - == option::some(signer::address_of(new_market_id_addr)), - TEST_SUCCESS); + assert!( + get_address(string::utf8(id)) + == option::some(signer::address_of(new_market_id_addr)), + TEST_SUCCESS, + ); } #[test(deployer = @aave_pool, super_admin = @aave_acl, fx = @std, new_pool_impl = @0x3)] @@ -92,7 +99,10 @@ module aave_pool::pool_addresses_provider_tests { // set pool impl set_pool_impl(super_admin, signer::address_of(new_pool_impl)); // test get pool address - assert!(get_pool() == option::some(signer::address_of(new_pool_impl)), TEST_SUCCESS); + assert!( + get_pool() == option::some(signer::address_of(new_pool_impl)), + TEST_SUCCESS, + ); // check emitted events let events = emitted_events(); // make sure event of type was emitted @@ -112,8 +122,10 @@ module aave_pool::pool_addresses_provider_tests { // set pool configurator impl set_pool_configurator(super_admin, signer::address_of(new_pool_impl)); // test get pool configurator address - assert!(get_pool_configurator() - == option::some(signer::address_of(new_pool_impl)), TEST_SUCCESS); + assert!( + get_pool_configurator() == option::some(signer::address_of(new_pool_impl)), + TEST_SUCCESS, + ); // check emitted events let events = emitted_events(); // make sure event of type was emitted @@ -133,8 +145,10 @@ module aave_pool::pool_addresses_provider_tests { // set price oracle impl set_price_oracle(super_admin, signer::address_of(new_price_oracle)); // test get price oracle address - assert!(get_price_oracle() - == option::some(signer::address_of(new_price_oracle)), TEST_SUCCESS); + assert!( + get_price_oracle() == option::some(signer::address_of(new_price_oracle)), + TEST_SUCCESS, + ); // check emitted events let events = emitted_events(); // make sure event of type was emitted @@ -154,8 +168,10 @@ module aave_pool::pool_addresses_provider_tests { // set acl admin impl set_acl_admin(super_admin, signer::address_of(new_acl_admin)); // test acl admin address - assert!(get_acl_admin() - == option::some(signer::address_of(new_acl_admin)), TEST_SUCCESS); + assert!( + get_acl_admin() == option::some(signer::address_of(new_acl_admin)), + TEST_SUCCESS, + ); // check emitted events let events = emitted_events(); // make sure event of type was emitted @@ -175,8 +191,10 @@ module aave_pool::pool_addresses_provider_tests { // set acl manager impl set_acl_manager(super_admin, signer::address_of(new_acl_manager)); // test acl manager address - assert!(get_acl_manager() - == option::some(signer::address_of(new_acl_manager)), TEST_SUCCESS); + assert!( + get_acl_manager() == option::some(signer::address_of(new_acl_manager)), + TEST_SUCCESS, + ); // check emitted events let events = emitted_events(); // make sure event of type was emitted @@ -185,7 +203,10 @@ module aave_pool::pool_addresses_provider_tests { #[test(deployer = @aave_pool, super_admin = @aave_acl, fx = @std, new_price_oracle_sentinel = @0x3)] fun test_set_get_price_oracle_sentinel( - deployer: &signer, super_admin: &signer, fx: &signer, new_price_oracle_sentinel: &signer + deployer: &signer, + super_admin: &signer, + fx: &signer, + new_price_oracle_sentinel: &signer ) { // add the test events feature flag change_feature_flags_for_testing(fx, vector[26], vector[]); @@ -194,11 +215,15 @@ module aave_pool::pool_addresses_provider_tests { // test get price oracle sentinel address assert!(get_price_oracle_sentinel() == option::none(), TEST_SUCCESS); // set price oracle sentinel impl - set_price_oracle_sentinel(super_admin, signer::address_of(new_price_oracle_sentinel)); + set_price_oracle_sentinel( + super_admin, signer::address_of(new_price_oracle_sentinel) + ); // test price oracle sentinel address - assert!(get_price_oracle_sentinel() - == option::some(signer::address_of(new_price_oracle_sentinel)), - TEST_SUCCESS); + assert!( + get_price_oracle_sentinel() + == option::some(signer::address_of(new_price_oracle_sentinel)), + TEST_SUCCESS, + ); // check emitted events let events = emitted_events(); // make sure event of type was emitted @@ -207,7 +232,9 @@ module aave_pool::pool_addresses_provider_tests { #[test(deployer = @aave_pool, super_admin = @aave_acl, fx = @std, new_pool_data_provider_sentinel = @0x3)] fun test_set_get_pool_data_provider_sentinel( - deployer: &signer, super_admin: &signer, fx: &signer, + deployer: &signer, + super_admin: &signer, + fx: &signer, new_pool_data_provider_sentinel: &signer ) { // add the test events feature flag @@ -217,12 +244,15 @@ module aave_pool::pool_addresses_provider_tests { // test get pool data provider address assert!(get_pool_data_provider() == option::none(), TEST_SUCCESS); // set pool data provider impl - set_pool_data_provider(super_admin, - signer::address_of(new_pool_data_provider_sentinel)); + set_pool_data_provider( + super_admin, signer::address_of(new_pool_data_provider_sentinel) + ); // test pool data provider address - assert!(get_pool_data_provider() - == option::some(signer::address_of(new_pool_data_provider_sentinel)), - TEST_SUCCESS); + assert!( + get_pool_data_provider() + == option::some(signer::address_of(new_pool_data_provider_sentinel)), + TEST_SUCCESS, + ); // check emitted events let events = emitted_events(); // make sure event of type was emitted diff --git a/aave-core/tests/aave-pool/pool_configurator_tests.move b/aave-core/tests/aave-pool/pool_configurator_tests.move index 6dddc37..f18ef6c 100644 --- a/aave-core/tests/aave-pool/pool_configurator_tests.move +++ b/aave-core/tests/aave-pool/pool_configurator_tests.move @@ -2,412 +2,751 @@ module aave_pool::pool_configurator_tests { use std::features::change_feature_flags_for_testing; use std::signer; - use std::string::utf8; + use std::string::{utf8, String}; use std::vector; + use aptos_std::string_utils; use aptos_framework::event::emitted_events; use aptos_framework::account; + use aptos_framework::timestamp::set_time_has_started_for_testing; use aave_acl::acl_manage; - use aave_acl::acl_manage::test_init_module; - use aave_mock_oracle::oracle::test_init_oracle; + use aave_math::wad_ray_math; + use aave_mock_oracle::oracle::{Self}; + use aave_pool::default_reserve_interest_rate_strategy; use aave_pool::a_token_factory::Self; use aave_pool::token_base; - use aave_pool::variable_token_factory::Self; - use aave_pool::underlying_token_factory::{Self}; - + use aave_pool::variable_debt_token_factory::Self; + use aave_pool::mock_underlying_token_factory::{Self}; + use aave_pool::collector::{Self}; use aave_pool::pool::{get_reserves_count, ReserveInitialized}; use aave_pool::pool_configurator::Self; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; - // #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle,)] - // fun test_add_reserves( - // aave_pool: &signer, - // aave_role_super_admin: &signer, - // aave_std: &signer, - // mock_oracle: &signer, - // ) { - // // init the acl module and make aave_pool the asset listing/pool admin - // acl_manage::test_init_module(aave_role_super_admin); - // acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); - // acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); - // - // // init token base - // token_base::test_init_module(aave_pool); - // - // // init underlying tokens - // underlying_token_factory::test_init_module(aave_pool); - // - // // add the test events feature flag - // change_feature_flags_for_testing(aave_std, vector[26], vector[]); - // - // // init oracle module - // test_init_oracle(mock_oracle); - // - // // init pool_configurator & reserves module - // pool_configurator::test_init_module(aave_pool); - // - // assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); - // - // // init input data for creating pool reserves - // let treasuries = vector[@0x011, @0x012]; - // - // let underlying_asset = vector[@0x061, @0x062]; - // let underlying_asset_decimals = vector[2, 3]; - // - // let a_token_names = vector[utf8(b"TEST_A_TOKEN_1"), utf8(b"TEST_A_TOKEN_2")]; - // let a_token_symbols = vector[utf8(b"A1"), utf8(b"A2")]; - // - // let variable_debt_token_names = vector[utf8(b"TEST_VAR_TOKEN_1"), utf8(b"TEST_VAR_TOKEN_2")]; - // let variable_debt_token_symbols = vector[utf8(b"V1"), utf8(b"V2")]; - // - // pool_configurator::init_reserves( - // aave_pool, - // underlying_asset, - // underlying_asset_decimals, - // treasuries, - // a_token_names, - // a_token_symbols, - // variable_debt_token_names, - // variable_debt_token_symbols, - // ); - // // check emitted events - // let emitted_events = emitted_events(); - // // make sure event of type was emitted - // assert!(vector::length(&emitted_events) == 2, TEST_SUCCESS); - // // test reserves count - // assert!(get_reserves_count() == 2, TEST_SUCCESS); - // } -// -// #[test(pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle,)] -// #[expected_failure(abort_code = 5)] -// fun test_add_reserves_wrong_sender( -// pool: &signer, -// aave_role_super_admin: &signer, -// aave_std: &signer, -// mock_oracle: &signer, -// ) { -// // init the acl module and make aave_pool the asset listing/pool admin -// test_init_module(aave_role_super_admin); -// acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); -// acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); -// -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // init oracle module -// test_init_oracle(mock_oracle); -// -// // init pool_configurator & reserves module -// pool_configurator::test_init_module(pool); -// -// let a_token_tmpl = vector[@0x011, @0x012]; -// let variable_debt_token_impl = vector[@0x031, @0x032]; -// let underlying_asset_decimals = vector[2, 3]; -// let underlying_asset = vector[@0x061, @0x062]; -// -// pool_configurator::add_reserves(mock_oracle, -// a_token_tmpl, -// variable_debt_token_impl, -// underlying_asset_decimals, -// underlying_asset,); -// } -// -// #[test(pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle,)] -// #[expected_failure(abort_code = 1)] -// fun test_drop_reserves_bad_signer( -// pool: &signer, -// aave_role_super_admin: &signer, -// aave_std: &signer, -// mock_oracle: &signer, -// ) { -// // init the acl module and make aave_pool the asset listing/pool admin -// test_init_module(aave_role_super_admin); -// acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); -// acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); -// -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // init oracle module -// test_init_oracle(mock_oracle); -// -// // init pool_configurator & reserves module & emode -// pool_configurator::test_init_module(pool); -// -// let a_token_tmpl = vector[@0x011, @0x012]; -// let variable_debt_token_impl = vector[@0x031, @0x032]; -// let underlying_asset_decimals = vector[2, 3]; -// let underlying_asset = vector[@0x061, @0x062]; -// -// pool_configurator::add_reserves(pool, -// a_token_tmpl, -// variable_debt_token_impl, -// underlying_asset_decimals, -// underlying_asset,); -// -// // drop the first reserve -// pool_configurator::drop_reserve(mock_oracle, *vector::borrow(&underlying_asset, 0)); -// } -// -// #[test(pool = @aave_pool, aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens,)] -// fun test_drop_reserves_with_0_supply( -// pool: &signer, -// aave_pool: &signer, -// aave_role_super_admin: &signer, -// aave_std: &signer, -// mock_oracle: &signer, -// variable_tokens_admin: &signer, -// a_tokens_admin: &signer, -// ) { -// // init the acl module and make aave_pool the asset listing/pool admin -// test_init_module(aave_role_super_admin); -// acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); -// acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); -// -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // init oracle module -// test_init_oracle(mock_oracle); -// -// // create a tokens admin account -// account::create_account_for_test(signer::address_of(a_tokens_admin)); -// -// // init pool_configurator & reserves module & emode -// pool_configurator::test_init_module(pool); -// -// // init token base for tokens -// token_base::test_init_module(aave_pool); -// -// // create variable tokens -// variable_token_factory::create_token(variable_tokens_admin, -// utf8(b"TEST_VAR_TOKEN_1"), -// utf8(b"VAR1"), -// 2, -// utf8(b""), -// utf8(b""), -// @0x033, // take random -// ); -// let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); -// -// //create a tokens -// a_token_factory::create_token(a_tokens_admin, -// utf8(b"TEST_A_TOKEN_1"), -// utf8(b"A1"), -// 2, -// utf8(b""), -// utf8(b""), -// @0x043, // take random -// @0x044, // take random -// ); -// let a_token_address = a_token_factory::token_address(utf8(b"A1")); -// -// // create add reserves data -// let a_token_tmpl = vector[a_token_address]; -// let variable_debt_token_impl = vector[variable_token_address]; -// let underlying_asset_decimals = vector[2]; -// let underlying_asset = vector[@0x061]; -// -// pool_configurator::add_reserves(pool, -// a_token_tmpl, -// variable_debt_token_impl, -// underlying_asset_decimals, -// underlying_asset,); -// // test reserves count -// assert!(get_reserves_count() == 1, TEST_SUCCESS); -// -// // drop the first reserve -// pool_configurator::drop_reserve(pool, *vector::borrow(&underlying_asset, 0)); -// // check emitted events -// let emitted_events = emitted_events(); -// // make sure event of type was emitted -// assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); -// // test reserves count -// assert!(get_reserves_count() == 0, TEST_SUCCESS); -// } -// -// #[test(pool = @aave_pool, aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, caller = @0x41,)] -// #[expected_failure(abort_code = 54)] -// fun test_drop_reserves_with_nonzero_supply_variable_failure( -// pool: &signer, -// aave_pool: &signer, -// aave_role_super_admin: &signer, -// aave_std: &signer, -// mock_oracle: &signer, -// variable_tokens_admin: &signer, -// a_tokens_admin: &signer, -// caller: &signer, -// ) { -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // init oracle module -// test_init_oracle(mock_oracle); -// -// // create a tokens admin account -// account::create_account_for_test(signer::address_of(a_tokens_admin)); -// -// // init the acl module and make aave_pool the asset listing/pool admin -// test_init_module(aave_role_super_admin); -// acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); -// acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); -// -// // init pool_configurator & reserves module -// pool_configurator::test_init_module(pool); -// -// // init token base for tokens -// token_base::test_init_module(aave_pool); -// -// let asset_decimals: u8 = 2; -// -// // create variable tokens -// variable_token_factory::create_token(variable_tokens_admin, -// utf8(b"TEST_VAR_TOKEN_1"), -// utf8(b"VAR1"), -// asset_decimals, -// utf8(b""), -// utf8(b""), -// @0x033, // take random -// ); -// let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); -// let _supply = variable_token_factory::supply(variable_token_address); -// -// //create a tokens -// a_token_factory::create_token(a_tokens_admin, -// utf8(b"TEST_A_TOKEN_1"), -// utf8(b"A1"), -// asset_decimals, -// utf8(b""), -// utf8(b""), -// @0x043, // take random -// @0x044, // take random -// ); -// let a_token_address = a_token_factory::token_address(utf8(b"A1")); -// -// // ============= MINT ATOKENS ============== // -// let amount_to_mint: u256 = 100; -// let reserve_index: u256 = 1; -// let token_receiver = @0x03; -// a_token_factory::mint(signer::address_of(caller), -// token_receiver, -// amount_to_mint, -// reserve_index, -// a_token_address); -// -// // assert a token supply -// assert!(a_token_factory::supply(a_token_address) == amount_to_mint, TEST_SUCCESS); -// -// // add reserves data -// let a_token_tmpl = vector[a_token_address]; -// let variable_debt_token_impl = vector[variable_token_address]; -// let underlying_asset_decimals = vector[(asset_decimals as u256)]; -// let underlying_asset = vector[@0x061]; -// -// // ============= ADD RESERVES ============== // -// pool_configurator::add_reserves(pool, -// a_token_tmpl, -// variable_debt_token_impl, -// underlying_asset_decimals, -// underlying_asset,); -// -// // test reserves count -// assert!(get_reserves_count() == 1, TEST_SUCCESS); -// -// // ============= DROP RESERVES ============== // -// // drop the reserve -// pool_configurator::drop_reserve(pool, *vector::borrow(&underlying_asset, 0)); -// } -// -// #[test(pool = @aave_pool, aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, caller = @0x41,)] -// #[expected_failure(abort_code = 56)] -// fun test_drop_reserves_with_nonzero_supply_atokens_failure( -// pool: &signer, -// aave_pool: &signer, -// aave_role_super_admin: &signer, -// aave_std: &signer, -// mock_oracle: &signer, -// variable_tokens_admin: &signer, -// a_tokens_admin: &signer, -// caller: &signer, -// ) { -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // init oracle module -// test_init_oracle(mock_oracle); -// -// // create a tokens admin account -// account::create_account_for_test(signer::address_of(a_tokens_admin)); -// -// // init the acl module and make aave_pool the asset listing/pool admin -// test_init_module(aave_role_super_admin); -// acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); -// acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); -// -// // init pool_configurator & reserves module -// pool_configurator::test_init_module(pool); -// -// // init token base for tokens -// token_base::test_init_module(aave_pool); -// -// let asset_decimals: u8 = 2; -// -// // create variable tokens -// variable_token_factory::create_token(variable_tokens_admin, -// utf8(b"TEST_VAR_TOKEN_1"), -// utf8(b"VAR1"), -// asset_decimals, -// utf8(b""), -// utf8(b""), -// @0x033, // take random -// ); -// let var_token_address = variable_token_factory::token_address(utf8(b"VAR1")); -// -// //create a tokens -// a_token_factory::create_token(a_tokens_admin, -// utf8(b"TEST_A_TOKEN_1"), -// utf8(b"A1"), -// asset_decimals, -// utf8(b""), -// utf8(b""), -// @0x043, // take random -// @0x044, // take random -// ); -// let a_token_address = a_token_factory::token_address(utf8(b"A1")); -// -// // ============= MINT VAR TOKENS ============== // -// let amount_to_mint: u256 = 100; -// let reserve_index: u256 = 1; -// let token_receiver = @0x03; -// variable_token_factory::mint(signer::address_of(caller), -// token_receiver, -// amount_to_mint, -// reserve_index, -// var_token_address); -// -// // assert a token supply -// assert!(variable_token_factory::supply(var_token_address) == amount_to_mint, -// TEST_SUCCESS); -// -// // ============= ADD RESERVES ============== // -// // add reserves data -// let a_token_tmpl = vector[a_token_address]; -// let variable_debt_token_impl = vector[var_token_address]; -// let underlying_asset_decimals = vector[(asset_decimals as u256)]; -// let underlying_asset = vector[@0x061]; -// -// pool_configurator::add_reserves(pool, -// a_token_tmpl, -// variable_debt_token_impl, -// underlying_asset_decimals, -// underlying_asset,); -// -// // test reserves count -// assert!(get_reserves_count() == 1, TEST_SUCCESS); -// -// // ============= DROP RESERVES ============== // -// // drop the reserve -// pool_configurator::drop_reserve(pool, *vector::borrow(&underlying_asset, 0)); -// } + const TEST_ASSETS_COUNT: u8 = 3; + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens,)] + fun test_add_reserves( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + ) { + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + for (i in 0..TEST_ASSETS_COUNT) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + // check emitted events + let emitted_events = emitted_events(); + // make sure event of type was emitted + assert!( + vector::length(&emitted_events) == (TEST_ASSETS_COUNT as u64), TEST_SUCCESS + ); + // test reserves count + assert!(get_reserves_count() == (TEST_ASSETS_COUNT as u256), TEST_SUCCESS); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens,)] + #[expected_failure(abort_code = 5)] + fun test_add_reserves_wrong_sender( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + ) { + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + for (i in 0..TEST_ASSETS_COUNT) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + pool_configurator::init_reserves( + mock_oracle, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens,)] + #[expected_failure(abort_code = 1)] + fun test_drop_reserves_bad_signer( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + ) { + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + for (i in 0..TEST_ASSETS_COUNT) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + assert!(get_reserves_count() == (TEST_ASSETS_COUNT as u256), TEST_SUCCESS); + + // drop the first reserve + pool_configurator::drop_reserve( + mock_oracle, *vector::borrow(&underlying_assets, 0) + ); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens,)] + #[expected_failure(abort_code = 1)] + fun test_drop_reserves_with_0_supply( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + ) { + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + for (i in 0..TEST_ASSETS_COUNT) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + // test reserves count + assert!(get_reserves_count() == (TEST_ASSETS_COUNT as u256), TEST_SUCCESS); + + // drop the first reserve + pool_configurator::drop_reserve(aave_pool, *vector::borrow(&underlying_assets, 0)); + // check emitted events + let emitted_events = emitted_events(); + // make sure event of type was emitted + assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); + // test reserves count + assert!(get_reserves_count() == ((TEST_ASSETS_COUNT as u256) - 1), TEST_SUCCESS); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens, caller = @0x42,)] + #[expected_failure(abort_code = 54)] + fun test_drop_reserves_with_nonzero_supply_atokens_failure( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + caller: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aave_std); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + for (i in 0..TEST_ASSETS_COUNT) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + // test reserves count + assert!(get_reserves_count() == (TEST_ASSETS_COUNT as u256), TEST_SUCCESS); + + // ============= MINT ATOKENS ============== // + let a_token_symbol = *vector::borrow(&atokens_symbols, 0); + let a_token_address = + a_token_factory::token_address(signer::address_of(aave_pool), a_token_symbol); + let amount_to_mint: u256 = 100; + let reserve_index: u256 = 1; + let amount_to_mint_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); + + a_token_factory::mint( + signer::address_of(caller), + signer::address_of(caller), + amount_to_mint, + reserve_index, + a_token_address, + ); + + // assert a token supply + assert!( + a_token_factory::scaled_total_supply(a_token_address) == amount_to_mint_scaled, + TEST_SUCCESS, + ); + + // drop the first reserve + pool_configurator::drop_reserve(aave_pool, *vector::borrow(&underlying_assets, 0)); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens, caller = @0x42,)] + #[expected_failure(abort_code = 56)] + fun test_drop_reserves_with_nonzero_supply_variable_tokens_failure( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + caller: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aave_std); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + for (i in 0..TEST_ASSETS_COUNT) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + // test reserves count + assert!(get_reserves_count() == (TEST_ASSETS_COUNT as u256), TEST_SUCCESS); + + // ============= MINT VARIABLE TOKENS ============== // + let var_token_symbol = *vector::borrow(&var_tokens_symbols, 0); + let var_token_address = + variable_debt_token_factory::token_address( + signer::address_of(aave_pool), var_token_symbol + ); + let amount_to_mint: u256 = 100; + let reserve_index: u256 = 1; + let amount_to_mint_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); + + variable_debt_token_factory::mint( + signer::address_of(caller), + signer::address_of(caller), + amount_to_mint, + reserve_index, + var_token_address, + ); + + // assert var token supply + assert!( + variable_debt_token_factory::scaled_total_supply(var_token_address) + == amount_to_mint_scaled, + TEST_SUCCESS, + ); + + // drop the first reserve + pool_configurator::drop_reserve(aave_pool, *vector::borrow(&underlying_assets, 0)); + } } diff --git a/aave-core/tests/aave-pool/pool_data_provider_tests.move b/aave-core/tests/aave-pool/pool_data_provider_tests.move new file mode 100644 index 0000000..48b85e9 --- /dev/null +++ b/aave-core/tests/aave-pool/pool_data_provider_tests.move @@ -0,0 +1,206 @@ +#[test_only] +module aave_pool::pool_data_provider_tests { + use std::features::change_feature_flags_for_testing; + use std::signer; + use std::string::{utf8, String}; + use std::vector; + use aptos_std::string_utils; + use aptos_framework::event::emitted_events; + use aptos_framework::account; + use aave_acl::acl_manage; + use aave_math::wad_ray_math; + use aave_mock_oracle::oracle::{Self}; + use aave_pool::default_reserve_interest_rate_strategy; + use aave_pool::a_token_factory::Self; + use aave_pool::token_base; + use aave_pool::variable_debt_token_factory::Self; + use aave_pool::mock_underlying_token_factory::{Self}; + use aave_pool::collector::{Self}; + use aave_pool::pool::{get_reserves_count, ReserveInitialized}; + use aave_pool::pool_configurator::Self; + use aave_pool::pool_data_provider::Self; + + const TEST_SUCCESS: u64 = 1; + const TEST_FAILED: u64 = 2; + + const TEST_ASSETS_COUNT: u8 = 3; + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens,)] + fun test_get_all_exposed_tokens( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + ) { + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + for (i in 0..TEST_ASSETS_COUNT) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + // check emitted events + let emitted_events = emitted_events(); + // make sure event of type was emitted + assert!( + vector::length(&emitted_events) == (TEST_ASSETS_COUNT as u64), TEST_SUCCESS + ); + // test reserves count + assert!(get_reserves_count() == (TEST_ASSETS_COUNT as u256), TEST_SUCCESS); + + // get all reserve tokens + let all_reserve_tokens = pool_data_provider::get_all_reserves_tokens(); + assert!( + vector::length(&underlying_assets) == vector::length(&all_reserve_tokens), + TEST_SUCCESS, + ); + for (i in 0..vector::length(&underlying_assets)) { + let underlying_token_data = vector::borrow(&all_reserve_tokens, i); + let underlying_token_symbol = + pool_data_provider::get_reserve_token_symbol(underlying_token_data); + let underlying_token_address = + pool_data_provider::get_reserve_token_address(underlying_token_data); + assert!( + underlying_token_address + == mock_underlying_token_factory::token_address( + underlying_token_symbol + ), + TEST_SUCCESS, + ); + assert!( + *vector::borrow(&underlying_assets, i) == underlying_token_address, + TEST_SUCCESS, + ); + }; + + // get all a tokens + let all_a_tokens = pool_data_provider::get_all_a_tokens(); + assert!( + vector::length(&atokens_names) == vector::length(&all_a_tokens), TEST_SUCCESS + ); + for (i in 0..vector::length(&atokens_symbols)) { + let a_token_data = vector::borrow(&all_a_tokens, i); + let a_token_symbol = + pool_data_provider::get_reserve_token_symbol(a_token_data); + let a_token_address = + pool_data_provider::get_reserve_token_address(a_token_data); + assert!( + a_token_address + == a_token_factory::token_address( + signer::address_of(aave_pool), a_token_symbol + ), + TEST_SUCCESS, + ); + }; + + // get all var tokens + let all_var_tokens = pool_data_provider::get_all_var_tokens(); + assert!( + vector::length(&var_tokens_names) == vector::length(&all_var_tokens), + TEST_SUCCESS, + ); + for (i in 0..vector::length(&var_tokens_names)) { + let var_token_data = vector::borrow(&all_var_tokens, i); + let var_token_symbol = + pool_data_provider::get_reserve_token_symbol(var_token_data); + let var_token_address = + pool_data_provider::get_reserve_token_address(var_token_data); + assert!( + var_token_address + == variable_debt_token_factory::token_address( + signer::address_of(aave_pool), var_token_symbol + ), + TEST_SUCCESS, + ); + }; + } +} diff --git a/aave-core/tests/aave-pool/pool_tests.move b/aave-core/tests/aave-pool/pool_tests.move index 743a500..712deaf 100644 --- a/aave-core/tests/aave-pool/pool_tests.move +++ b/aave-core/tests/aave-pool/pool_tests.move @@ -6,10 +6,9 @@ module aave_pool::pool_tests { use std::signer::Self; use std::string::{utf8, String}; use std::vector; - use aptos_std::string_utils::format1; + use aptos_std::string_utils; use aptos_framework::account; use aptos_framework::event::emitted_events; - use aptos_framework::timestamp::set_time_has_started_for_testing; use aave_acl::acl_manage::Self; use aave_config::reserve::{ @@ -64,6 +63,10 @@ module aave_pool::pool_tests { set_using_as_collateral, }; use aave_math::wad_ray_math; + use aave_mock_oracle::oracle; + use aave_pool::default_reserve_interest_rate_strategy; + use aave_pool::pool_configurator; + use aave_pool::collector; use aave_pool::a_token_factory::Self; use aave_pool::pool::{ @@ -90,7 +93,7 @@ module aave_pool::pool_tests { get_user_configuration, ReserveInitialized, set_bridge_protocol_fee, - set_flashloan_premiums, + update_flashloan_premiums, set_reserve_accrued_to_treasury, set_reserve_current_liquidity_rate_for_testing, set_reserve_current_variable_borrow_rate_for_testing, @@ -99,373 +102,563 @@ module aave_pool::pool_tests { set_reserve_unbacked, set_reserve_variable_borrow_index_for_testing, set_user_configuration, - test_drop_reserve, - test_init_pool, test_init_reserve, test_set_reserve_configuration, }; use aave_pool::token_base::Self; - use aave_pool::underlying_token_factory::Self; - use aave_pool::variable_token_factory::Self; + use aave_pool::mock_underlying_token_factory::Self; + use aave_pool::variable_debt_token_factory::Self; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; + const TEST_ASSETS_COUNT: u8 = 3; + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens,)] + fun test_default_state( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + ) { + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + for (i in 0..TEST_ASSETS_COUNT) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + // check emitted events + let emitted_events = emitted_events(); + // make sure event of type was emitted + assert!( + vector::length(&emitted_events) == (TEST_ASSETS_COUNT as u64), TEST_SUCCESS + ); + // test reserves count + assert!(get_reserves_count() == (TEST_ASSETS_COUNT as u256), TEST_SUCCESS); + + // get the reserve config + let underlying_asset_addr = *vector::borrow(&underlying_assets, 0); + let underlying_asset_decimals = *vector::borrow(&underlying_asset_decimals, 0); + let reserve_config_map = get_reserve_configuration(underlying_asset_addr); + + // test reserve config + assert!(get_ltv(&reserve_config_map) == 0, TEST_SUCCESS); + assert!(get_liquidation_threshold(&reserve_config_map) == 0, TEST_SUCCESS); + assert!(get_liquidation_bonus(&reserve_config_map) == 0, TEST_SUCCESS); + assert!( + get_decimals(&reserve_config_map) == (underlying_asset_decimals as u256), + TEST_SUCCESS, + ); + assert!(get_active(&reserve_config_map) == true, TEST_SUCCESS); + assert!(get_frozen(&reserve_config_map) == false, TEST_SUCCESS); + assert!(get_paused(&reserve_config_map) == false, TEST_SUCCESS); + assert!(get_borrowable_in_isolation(&reserve_config_map) == false, TEST_SUCCESS); + assert!(get_siloed_borrowing(&reserve_config_map) == false, TEST_SUCCESS); + assert!(get_borrowing_enabled(&reserve_config_map) == false, TEST_SUCCESS); + assert!(get_reserve_factor(&reserve_config_map) == 0, TEST_SUCCESS); + assert!(get_borrow_cap(&reserve_config_map) == 0, TEST_SUCCESS); + assert!(get_supply_cap(&reserve_config_map) == 0, TEST_SUCCESS); + assert!(get_debt_ceiling(&reserve_config_map) == 0, TEST_SUCCESS); + assert!(get_liquidation_protocol_fee(&reserve_config_map) == 0, TEST_SUCCESS); + assert!(get_unbacked_mint_cap(&reserve_config_map) == 0, TEST_SUCCESS); + assert!(get_emode_category(&reserve_config_map) == 0, TEST_SUCCESS); + assert!(get_flash_loan_enabled(&reserve_config_map) == false, TEST_SUCCESS); + + // get the reserve data + let reserve_data = get_reserve_data(underlying_asset_addr); + let reserve_config = get_reserve_configuration_by_reserve_data(&reserve_data); + assert!(reserve_config_map == reserve_config, TEST_SUCCESS); + let (reserve_data1, count) = + get_reserve_data_and_reserves_count(underlying_asset_addr); + assert!(count == (TEST_ASSETS_COUNT as u256), TEST_SUCCESS); + let reserve_id = get_reserve_id(&reserve_data); + let reserve_data2 = get_reserve_address_by_id((reserve_id as u256)); + // assert counts + assert!(reserve_data == reserve_data1, TEST_SUCCESS); + assert!(reserve_data2 == underlying_asset_addr, TEST_SUCCESS); + assert!(count == get_reserves_count(), TEST_SUCCESS); + // assert reserves list + let reserves_list = get_reserves_list(); + assert!(vector::length(&reserves_list) == (TEST_ASSETS_COUNT as u64), TEST_SUCCESS); + assert!(*vector::borrow(&reserves_list, 0) == underlying_asset_addr, TEST_SUCCESS); + + // test reserve data + let a_token_symbol = *vector::borrow(&atokens_symbols, 0); + let a_token_address = + a_token_factory::token_address(signer::address_of(aave_pool), a_token_symbol); + let var_token_symbol = *vector::borrow(&var_tokens_symbols, 0); + let var_token_address = + variable_debt_token_factory::token_address( + signer::address_of(aave_pool), var_token_symbol + ); + assert!( + get_reserve_a_token_address(&reserve_data) == a_token_address, TEST_SUCCESS + ); + assert!(get_reserve_accrued_to_treasury(&reserve_data) == 0, TEST_SUCCESS); + assert!( + get_reserve_variable_borrow_index(&reserve_data) == ( + wad_ray_math::ray() as u128 + ), + TEST_SUCCESS, + ); + assert!( + get_reserve_liquidity_index(&reserve_data) == (wad_ray_math::ray() as u128), + TEST_SUCCESS, + ); + assert!(get_reserve_current_liquidity_rate(&reserve_data) == 0, TEST_SUCCESS); + assert!( + get_reserve_current_variable_borrow_rate(&reserve_data) == 0, TEST_SUCCESS + ); + assert!( + get_reserve_variable_debt_token_address(&reserve_data) == var_token_address, + TEST_SUCCESS, + ); + assert!(get_reserve_unbacked(&reserve_data) == 0, TEST_SUCCESS); + assert!(get_reserve_isolation_mode_total_debt(&reserve_data) == 0, TEST_SUCCESS); + + // test default extended config + assert!(get_flashloan_premium_total() == 0, TEST_SUCCESS); + assert!(get_bridge_protocol_fee() == 0, TEST_SUCCESS); + assert!(get_flashloan_premium_to_protocol() == 0, TEST_SUCCESS); + + // test default user config + let random_user = @0x42; + let user_config_map = get_user_configuration(random_user); + assert!(is_empty(&user_config_map), TEST_SUCCESS); + assert!(!is_borrowing_any(&user_config_map), TEST_SUCCESS); + assert!(!is_using_as_collateral_any(&user_config_map), TEST_SUCCESS); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens,)] + fun test_modified_state( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + ) { + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + for (i in 0..TEST_ASSETS_COUNT) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // get tokens data + let underlying_asset_addr = *vector::borrow(&underlying_assets, 0); + let a_token_symbol = *vector::borrow(&atokens_symbols, 0); + let a_token_address = + a_token_factory::token_address(signer::address_of(aave_pool), a_token_symbol); + let var_token_symbol = *vector::borrow(&var_tokens_symbols, 0); + let var_token_address = + variable_debt_token_factory::token_address( + signer::address_of(aave_pool), var_token_symbol + ); + + // test reserve config + let reserve_config_new = init(); + set_ltv(&mut reserve_config_new, 100); + set_liquidation_threshold(&mut reserve_config_new, 101); + set_liquidation_bonus(&mut reserve_config_new, 102); + set_decimals(&mut reserve_config_new, 103); + set_active(&mut reserve_config_new, true); + set_frozen(&mut reserve_config_new, true); + set_paused(&mut reserve_config_new, true); + set_borrowable_in_isolation(&mut reserve_config_new, true); + set_siloed_borrowing(&mut reserve_config_new, true); + set_borrowing_enabled(&mut reserve_config_new, true); + set_reserve_factor(&mut reserve_config_new, 104); + set_borrow_cap(&mut reserve_config_new, 105); + set_supply_cap(&mut reserve_config_new, 106); + set_debt_ceiling(&mut reserve_config_new, 107); + set_liquidation_protocol_fee(&mut reserve_config_new, 108); + set_unbacked_mint_cap(&mut reserve_config_new, 109); + set_emode_category(&mut reserve_config_new, 110); + set_flash_loan_enabled(&mut reserve_config_new, true); + + // set the reserve configuration + test_set_reserve_configuration(underlying_asset_addr, reserve_config_new); + + let reserve_data = get_reserve_data(underlying_asset_addr); + let reserve_config_map = get_reserve_configuration_by_reserve_data(&reserve_data); + + assert!(get_ltv(&reserve_config_map) == 100, TEST_SUCCESS); + assert!(get_liquidation_threshold(&reserve_config_map) == 101, TEST_SUCCESS); + assert!(get_liquidation_bonus(&reserve_config_map) == 102, TEST_SUCCESS); + assert!(get_decimals(&reserve_config_map) == 103, TEST_SUCCESS); + assert!(get_active(&reserve_config_map) == true, TEST_SUCCESS); + assert!(get_frozen(&reserve_config_map) == true, TEST_SUCCESS); + assert!(get_paused(&reserve_config_map) == true, TEST_SUCCESS); + assert!(get_borrowable_in_isolation(&reserve_config_map) == true, TEST_SUCCESS); + assert!(get_siloed_borrowing(&reserve_config_map) == true, TEST_SUCCESS); + assert!(get_borrowing_enabled(&reserve_config_map) == true, TEST_SUCCESS); + assert!(get_reserve_factor(&reserve_config_map) == 104, TEST_SUCCESS); + assert!(get_borrow_cap(&reserve_config_map) == 105, TEST_SUCCESS); + assert!(get_supply_cap(&reserve_config_map) == 106, TEST_SUCCESS); + assert!(get_debt_ceiling(&reserve_config_map) == 107, TEST_SUCCESS); + assert!(get_liquidation_protocol_fee(&reserve_config_map) == 108, TEST_SUCCESS); + assert!(get_unbacked_mint_cap(&reserve_config_map) == 109, TEST_SUCCESS); + assert!(get_emode_category(&reserve_config_map) == 110, TEST_SUCCESS); + assert!(get_flash_loan_enabled(&reserve_config_map) == true, TEST_SUCCESS); + + // test reserve data + set_reserve_isolation_mode_total_debt(underlying_asset_addr, 200); + set_reserve_unbacked(underlying_asset_addr, &mut reserve_data, 201); + set_reserve_current_variable_borrow_rate_for_testing(underlying_asset_addr, 202); + set_reserve_current_liquidity_rate_for_testing(underlying_asset_addr, 204); + set_reserve_liquidity_index_for_testing(underlying_asset_addr, 205); + set_reserve_variable_borrow_index_for_testing(underlying_asset_addr, 206); + set_reserve_accrued_to_treasury(underlying_asset_addr, 207); + let reserve_data = get_reserve_data(underlying_asset_addr); + assert!(get_reserve_isolation_mode_total_debt(&reserve_data) == 200, TEST_SUCCESS); + assert!(get_reserve_unbacked(&reserve_data) == 201, TEST_SUCCESS); + assert!( + get_reserve_current_variable_borrow_rate(&reserve_data) == 202, TEST_SUCCESS + ); + assert!(get_reserve_current_liquidity_rate(&reserve_data) == 204, TEST_SUCCESS); + assert!(get_reserve_liquidity_index(&reserve_data) == 205, TEST_SUCCESS); + assert!(get_reserve_variable_borrow_index(&reserve_data) == 206, TEST_SUCCESS); + assert!(get_reserve_accrued_to_treasury(&reserve_data) == 207, TEST_SUCCESS); + assert!( + get_reserve_a_token_address(&reserve_data) == a_token_address, TEST_SUCCESS + ); + assert!( + get_reserve_variable_debt_token_address(&reserve_data) == var_token_address, + TEST_SUCCESS, + ); + + // test reserve extended config + update_flashloan_premiums(1000, 2000); + assert!(get_flashloan_premium_total() == 1000, TEST_SUCCESS); + assert!(get_flashloan_premium_to_protocol() == 2000, TEST_SUCCESS); + set_bridge_protocol_fee(4000); + assert!(get_bridge_protocol_fee() == 4000, TEST_SUCCESS); + + // test reserve user config + let random_user = @0x42; + let reserve_index = get_reserve_id(&reserve_data); + let user_config_map = get_user_configuration(random_user); + set_borrowing(&mut user_config_map, (reserve_index as u256), true); + set_using_as_collateral(&mut user_config_map, (reserve_index as u256), true); + set_user_configuration(random_user, user_config_map); + assert!( + is_borrowing(&user_config_map, (reserve_index as u256)) == true, TEST_SUCCESS + ); + assert!(is_borrowing_any(&user_config_map) == true, TEST_SUCCESS); + assert!(is_borrowing_one(&user_config_map) == true, TEST_SUCCESS); + assert!( + is_using_as_collateral_or_borrowing(&user_config_map, (reserve_index as u256)) == + true, + TEST_SUCCESS, + ); + assert!( + is_using_as_collateral(&user_config_map, (reserve_index as u256)) == true, + TEST_SUCCESS, + ); + assert!(is_using_as_collateral_any(&user_config_map) == true, TEST_SUCCESS); + assert!(is_using_as_collateral_one(&user_config_map) == true, TEST_SUCCESS); + assert!( + is_using_as_collateral_or_borrowing(&user_config_map, (reserve_index as u256)) == + true, + TEST_SUCCESS, + ); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_std = @std, mock_oracle = @aave_mock_oracle, underlying_tokens_admin = @underlying_tokens,)] + fun test_add_drop_reserves( + aave_pool: &signer, + aave_role_super_admin: &signer, + aave_std: &signer, + mock_oracle: &signer, + underlying_tokens_admin: &signer, + ) { + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // add the test events feature flag + change_feature_flags_for_testing(aave_std, vector[26], vector[]); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + assert!(pool_configurator::get_revision() == 1, TEST_SUCCESS); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; - // #[test(pool = @aave_pool, aave_std = @std, aptos_framework = @0x1, a_token = @0x01, variable_debt_token = @0x03, underlying_asset = @0x05,)] - // fun test_default_state( - // pool: &signer, - // aave_std: &signer, - // aptos_framework: &signer, - // a_token: &signer, - // variable_debt_token: &signer, - // underlying_asset: &signer, - // ) { - // // start the timer - // set_time_has_started_for_testing(aptos_framework); - // - // let underlying_asset_decimals = 2; - // - // let a_token_tmpl = signer::address_of(a_token); - // let variable_debt_token_addr = signer::address_of(variable_debt_token); - // let underlying_asset_addr = signer::address_of(underlying_asset); - // - // // add the test events feature flag - // change_feature_flags_for_testing(aave_std, vector[26], vector[]); - // - // // init the reserve - // test_init_pool(pool); - // - // // create a brand new reserve - // test_init_reserve( - // pool, - // underlying_asset_addr, - // underlying_asset_decimals, - // signer::address_of(pool), - // utf8(b"Fa"), - // utf8(b"FA") , - // utf8(b"Fv") , - // utf8(b"FV") - // ); - // - // // check emitted events - // let emitted_events = emitted_events(); - // // make sure event of type was emitted - // assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); - // - // // test reserves cound - // assert!(get_reserves_count() == 1, TEST_SUCCESS); - // - // // get the reserve config - // let reserve_config_map = get_reserve_configuration(underlying_asset_addr); - // - // // test reserve config - // assert!(get_ltv(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_liquidation_threshold(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_liquidation_bonus(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_decimals(&reserve_config_map) == (underlying_asset_decimals as u256), TEST_SUCCESS); - // assert!(get_active(&reserve_config_map) == true, TEST_SUCCESS); - // assert!(get_frozen(&reserve_config_map) == false, TEST_SUCCESS); - // assert!(get_paused(&reserve_config_map) == false, TEST_SUCCESS); - // assert!(get_borrowable_in_isolation(&reserve_config_map) == false, TEST_SUCCESS); - // assert!(get_siloed_borrowing(&reserve_config_map) == false, TEST_SUCCESS); - // assert!(get_borrowing_enabled(&reserve_config_map) == false, TEST_SUCCESS); - // assert!(get_reserve_factor(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_borrow_cap(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_supply_cap(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_debt_ceiling(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_liquidation_protocol_fee(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_unbacked_mint_cap(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_emode_category(&reserve_config_map) == 0, TEST_SUCCESS); - // assert!(get_flash_loan_enabled(&reserve_config_map) == false, TEST_SUCCESS); - // - // // get the reserve data - // let reserve_data = get_reserve_data(underlying_asset_addr); - // let reserve_config = get_reserve_configuration_by_reserve_data(&reserve_data); - // assert!(reserve_config_map == reserve_config, TEST_SUCCESS); - // let (reserve_data1, count) = get_reserve_data_and_reserves_count( - // underlying_asset_addr); - // let reserve_data2 = get_reserve_address_by_id(count); - // // assert counts - // assert!(reserve_data == reserve_data1, TEST_SUCCESS); - // assert!(reserve_data2 == underlying_asset_addr, TEST_SUCCESS); - // assert!(count == get_reserves_count(), TEST_SUCCESS); - // // assert reserves list - // let reserves_list = get_reserves_list(); - // assert!(vector::length(&reserves_list) == 1, TEST_SUCCESS); - // assert!(*vector::borrow(&reserves_list, 0) == underlying_asset_addr, TEST_SUCCESS); - // - // // test reserve data - // assert!((get_reserve_id(&reserve_data) as u256) == count, TEST_SUCCESS); - // assert!(get_reserve_a_token_address(&reserve_data) == a_token_tmpl, TEST_SUCCESS); - // assert!(get_reserve_accrued_to_treasury(&reserve_data) == 0, TEST_SUCCESS); - // assert!(get_reserve_variable_borrow_index(&reserve_data) - // == (wad_ray_math::ray() as u128), - // TEST_SUCCESS); - // assert!(get_reserve_liquidity_index(&reserve_data) - // == (wad_ray_math::ray() as u128), TEST_SUCCESS); - // assert!(get_reserve_current_liquidity_rate(&reserve_data) == 0, TEST_SUCCESS); - // assert!(get_reserve_current_variable_borrow_rate(&reserve_data) == 0, TEST_SUCCESS); - // assert!(get_reserve_variable_debt_token_address(&reserve_data) - // == variable_debt_token_addr, - // TEST_SUCCESS); - // assert!(get_reserve_unbacked(&reserve_data) == 0, TEST_SUCCESS); - // assert!(get_reserve_isolation_mode_total_debt(&reserve_data) == 0, TEST_SUCCESS); - // - // // test default extended config - // assert!(get_flashloan_premium_total() == 0, TEST_SUCCESS); - // assert!(get_bridge_protocol_fee() == 0, TEST_SUCCESS); - // assert!(get_flashloan_premium_to_protocol() == 0, TEST_SUCCESS); - // - // // test default user config - // let random_user = @0x42; - // let user_config_map = get_user_configuration(random_user); - // assert!(is_empty(&user_config_map), TEST_SUCCESS); - // assert!(!is_borrowing_any(&user_config_map), TEST_SUCCESS); - // assert!(!is_using_as_collateral_any(&user_config_map), TEST_SUCCESS); - // } - // - // #[test(pool = @aave_pool, aave_std = @std, aptos_framework = @0x1, a_token = @0x01, variable_debt_token = @0x03, underlying_asset = @0x04,)] - // fun test_modified_state( - // pool: &signer, - // aave_std: &signer, - // aptos_framework: &signer, - // a_token: &signer, - // variable_debt_token: &signer, - // underlying_asset: &signer, - // ) { - // // start the timer - // set_time_has_started_for_testing(aptos_framework); - // - // // get addresses - // let underlying_asset_decimals = 2; - // let a_token_tmpl = signer::address_of(a_token); - // let variable_debt_token_addr = signer::address_of(variable_debt_token); - // let underlying_asset_addr = signer::address_of(underlying_asset); - // - // // add the test events feature flag - // change_feature_flags_for_testing(aave_std, vector[26], vector[]); - // - // // init the reserve - // test_init_pool(pool); - // - // // create a brand new reserve - // test_init_reserve( - // pool, - // underlying_asset_addr, - // underlying_asset_decimals, - // signer::address_of(pool), - // utf8(b"Fa"), - // utf8(b"FA") , - // utf8(b"Fv") , - // utf8(b"FV") - // ); - // - // let reserve_index = get_reserves_count(); - // - // // test reserve config - // let reserve_config_new = init(); - // set_ltv(&mut reserve_config_new, 100); - // set_liquidation_threshold(&mut reserve_config_new, 101); - // set_liquidation_bonus(&mut reserve_config_new, 102); - // set_decimals(&mut reserve_config_new, 103); - // set_active(&mut reserve_config_new, true); - // set_frozen(&mut reserve_config_new, true); - // set_paused(&mut reserve_config_new, true); - // set_borrowable_in_isolation(&mut reserve_config_new, true); - // set_siloed_borrowing(&mut reserve_config_new, true); - // set_borrowing_enabled(&mut reserve_config_new, true); - // set_reserve_factor(&mut reserve_config_new, 104); - // set_borrow_cap(&mut reserve_config_new, 105); - // set_supply_cap(&mut reserve_config_new, 106); - // set_debt_ceiling(&mut reserve_config_new, 107); - // set_liquidation_protocol_fee(&mut reserve_config_new, 108); - // set_unbacked_mint_cap(&mut reserve_config_new, 109); - // set_emode_category(&mut reserve_config_new, 110); - // set_flash_loan_enabled(&mut reserve_config_new, true); - // - // // set the reserve configuration - // test_set_reserve_configuration(underlying_asset_addr, reserve_config_new); - // - // let reserve_data = get_reserve_data(underlying_asset_addr); - // let reserve_config_map = get_reserve_configuration_by_reserve_data(&reserve_data); - // - // assert!(get_ltv(&reserve_config_map) == 100, TEST_SUCCESS); - // assert!(get_liquidation_threshold(&reserve_config_map) == 101, TEST_SUCCESS); - // assert!(get_liquidation_bonus(&reserve_config_map) == 102, TEST_SUCCESS); - // assert!(get_decimals(&reserve_config_map) == 103, TEST_SUCCESS); - // assert!(get_active(&reserve_config_map) == true, TEST_SUCCESS); - // assert!(get_frozen(&reserve_config_map) == true, TEST_SUCCESS); - // assert!(get_paused(&reserve_config_map) == true, TEST_SUCCESS); - // assert!(get_borrowable_in_isolation(&reserve_config_map) == true, TEST_SUCCESS); - // assert!(get_siloed_borrowing(&reserve_config_map) == true, TEST_SUCCESS); - // assert!(get_borrowing_enabled(&reserve_config_map) == true, TEST_SUCCESS); - // assert!(get_reserve_factor(&reserve_config_map) == 104, TEST_SUCCESS); - // assert!(get_borrow_cap(&reserve_config_map) == 105, TEST_SUCCESS); - // assert!(get_supply_cap(&reserve_config_map) == 106, TEST_SUCCESS); - // assert!(get_debt_ceiling(&reserve_config_map) == 107, TEST_SUCCESS); - // assert!(get_liquidation_protocol_fee(&reserve_config_map) == 108, TEST_SUCCESS); - // assert!(get_unbacked_mint_cap(&reserve_config_map) == 109, TEST_SUCCESS); - // assert!(get_emode_category(&reserve_config_map) == 110, TEST_SUCCESS); - // assert!(get_flash_loan_enabled(&reserve_config_map) == true, TEST_SUCCESS); - // - // // test reserve data - // set_reserve_isolation_mode_total_debt(underlying_asset_addr, 200); - // set_reserve_unbacked(underlying_asset_addr, 201); - // set_reserve_current_variable_borrow_rate_for_testing(underlying_asset_addr, 202); - // set_reserve_current_liquidity_rate_for_testing(underlying_asset_addr, 204); - // set_reserve_liquidity_index_for_testing(underlying_asset_addr, 205); - // set_reserve_variable_borrow_index_for_testing(underlying_asset_addr, 206); - // set_reserve_accrued_to_treasury(underlying_asset_addr, 207); - // let reserve_data = get_reserve_data(underlying_asset_addr); - // assert!(get_reserve_isolation_mode_total_debt(&reserve_data) == 200, TEST_SUCCESS); - // assert!(get_reserve_unbacked(&reserve_data) == 201, TEST_SUCCESS); - // assert!(get_reserve_current_variable_borrow_rate(&reserve_data) == 202, TEST_SUCCESS); - // assert!(get_reserve_current_liquidity_rate(&reserve_data) == 204, TEST_SUCCESS); - // assert!(get_reserve_liquidity_index(&reserve_data) == 205, TEST_SUCCESS); - // assert!(get_reserve_variable_borrow_index(&reserve_data) == 206, TEST_SUCCESS); - // assert!(get_reserve_accrued_to_treasury(&reserve_data) == 207, TEST_SUCCESS); - // assert!((get_reserve_id(&reserve_data) as u256) == reserve_index, TEST_SUCCESS); - // assert!(get_reserve_a_token_address(&reserve_data) == a_token_tmpl, TEST_SUCCESS); - // assert!(get_reserve_variable_debt_token_address(&reserve_data) - // == variable_debt_token_addr, - // TEST_SUCCESS); - // - // // test reserve extended config - // set_flashloan_premiums(1000, 2000); - // assert!(get_flashloan_premium_total() == 1000, TEST_SUCCESS); - // assert!(get_flashloan_premium_to_protocol() == 2000, TEST_SUCCESS); - // set_bridge_protocol_fee(4000); - // assert!(get_bridge_protocol_fee() == 4000, TEST_SUCCESS); - // - // // test reserve user config - // let random_user = @0x42; - // let user_config_map = get_user_configuration(random_user); - // set_borrowing(&mut user_config_map, reserve_index, true); - // set_using_as_collateral(&mut user_config_map, reserve_index, true); - // set_user_configuration(random_user, user_config_map); - // assert!(is_borrowing(&user_config_map, reserve_index) == true, TEST_SUCCESS); - // assert!(is_borrowing_any(&user_config_map) == true, TEST_SUCCESS); - // assert!(is_borrowing_one(&user_config_map) == true, TEST_SUCCESS); - // assert!(is_using_as_collateral_or_borrowing(&user_config_map, reserve_index) == true, - // TEST_SUCCESS); - // assert!(is_using_as_collateral(&user_config_map, reserve_index) == true, - // TEST_SUCCESS); - // assert!(is_using_as_collateral_any(&user_config_map) == true, TEST_SUCCESS); - // assert!(is_using_as_collateral_one(&user_config_map) == true, TEST_SUCCESS); - // assert!(is_using_as_collateral_or_borrowing(&user_config_map, reserve_index) == true, - // TEST_SUCCESS); - // } - // - // #[test(pool = @aave_pool, aave_std = @std, aptos_framework = @0x1, aave_role_super_admin = @aave_acl, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aave_pool = @aave_pool,)] - // fun test_add_drop_reserves( - // pool: &signer, - // aave_std: &signer, - // aptos_framework: &signer, - // aave_role_super_admin: &signer, - // variable_tokens_admin: &signer, - // a_tokens_admin: &signer, - // underlying_tokens_admin: &signer, - // aave_pool: &signer, - // ) { - // // start the timer - // set_time_has_started_for_testing(aptos_framework); - // - // // add the test events feature flag - // change_feature_flags_for_testing(aave_std, vector[26], vector[]); - // - // // create a tokens admin account - // account::create_account_for_test(signer::address_of(a_tokens_admin)); - // - // // init the acl module and make aave_pool the asset listing/pool admin - // acl_manage::test_init_module(aave_role_super_admin); - // acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); - // acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); - // - // // init underlying tokens - // underlying_token_factory::test_init_module(aave_pool); - // // init token base for tokens - // token_base::test_init_module(aave_pool); - // - // // init the reserve - // test_init_pool(pool); - // - // // create all tokens - // let decimals = 2; - // let tokens_to_create = 4; - // let a_token_impl = vector
[]; - // let variable_debt_token_addr = vector
[]; - // let underlying_asset_addr = vector
[]; - // - // for (i in 0..tokens_to_create) { - // // create underlying tokens - // let underlying_token_name = format1(&b"TEST_TOKEN_{}", i); - // let underlying_token_symbol = format1(&b"TOKEN{}", i); - // let underlying_token_decimals = 3; - // let underlying_token_max_supply = 10000; - // underlying_token_factory::create_token(underlying_tokens_admin, - // underlying_token_max_supply, - // underlying_token_name, - // underlying_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""),); - // let underlying_token_address = underlying_token_factory::token_address( - // underlying_token_symbol); - // vector::push_back(&mut underlying_asset_addr, underlying_token_address); - // - // // create variable tokens - // let variable_token_name = format1(&b"TEST_VAR_TOKEN_{}", i); - // let variable_token_symbol = format1(&b"VAR{}", i); - // let variable_token_decimals = 3; - // variable_token_factory::create_token(variable_tokens_admin, - // variable_token_name, - // variable_token_symbol, - // variable_token_decimals, - // utf8(b""), - // utf8(b""), - // underlying_token_address, // take random - // ); - // let underlying_token_address = variable_token_factory::token_address( - // variable_token_symbol); - // vector::push_back(&mut variable_debt_token_addr, underlying_token_address); - // - // // create a tokens - // let a_token_name = format1(&b"A_TOKEN_{}", i); - // let a_token_symbol = format1(&b"ATOKEN{}", i); - // a_token_factory::create_token(a_tokens_admin, - // a_token_name, - // a_token_symbol, - // underlying_token_decimals, - // utf8(b""), - // utf8(b""), - // underlying_token_address, // underlying asset address - // @0x64, // treasury address - // ); - // let a_token_address = a_token_factory::token_address(a_token_symbol); - // vector::push_back(&mut a_token_impl, a_token_address); - // }; - // - // // add reserves - // for (i in 0..tokens_to_create) { - // test_init_reserve(*vector::borrow(&a_token_impl, i), - // *vector::borrow(&variable_debt_token_addr, i), - // decimals, - // *vector::borrow(&underlying_asset_addr, i)); - // let total_reserves = get_reserves_count(); - // assert!(total_reserves == ((i + 1) as u256), TEST_SUCCESS); - // }; - // - // // drop some reserves - // test_drop_reserve(*vector::borrow(&underlying_asset_addr, 0)); - // test_drop_reserve(*vector::borrow(&underlying_asset_addr, 1)); - // - // // add another reserve - // test_init_reserve(@0x015, @0x025, decimals, @0x035); - // - // let total_reserves = get_reserves_count(); - // assert!(total_reserves == ((tokens_to_create - 2 + 1) as u256), TEST_SUCCESS); - // } + // create underlyings + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_reserves = 3; + for (i in 0..num_reserves) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + // test reserves count + assert!(get_reserves_count() == (num_reserves as u256), TEST_SUCCESS); + + // drop some reserves + //test_drop_reserve(*vector::borrow(&underlying_assets, 0)); + pool_configurator::drop_reserve(aave_pool, *vector::borrow(&underlying_assets, 0)); + pool_configurator::drop_reserve(aave_pool, *vector::borrow(&underlying_assets, 1)); + + // check emitted events + let emitted_events = emitted_events(); + // make sure event of type was emitted + assert!(vector::length(&emitted_events) == 2, TEST_SUCCESS); + } public fun create_reserve_with_config( account: &signer, @@ -507,42 +700,61 @@ module aave_pool::pool_tests { variable_debt_token_symbol, ); + // create reserve configuration let reserve_config_new = init(); set_ltv(&mut reserve_config_new, option::get_with_default(<v, 100)); - set_liquidation_threshold(&mut reserve_config_new, - option::get_with_default(&liquidation_threshold, 101)); - set_liquidation_bonus(&mut reserve_config_new, - option::get_with_default(&liquidation_bonus, 102)); + set_liquidation_threshold( + &mut reserve_config_new, option::get_with_default(&liquidation_threshold, 101) + ); + set_liquidation_bonus( + &mut reserve_config_new, option::get_with_default(&liquidation_bonus, 102) + ); set_decimals(&mut reserve_config_new, option::get_with_default(&decimals, 103)); set_active(&mut reserve_config_new, option::get_with_default(&active, true)); set_frozen(&mut reserve_config_new, option::get_with_default(&frozen, false)); set_paused(&mut reserve_config_new, option::get_with_default(&paused, false)); - set_borrowable_in_isolation(&mut reserve_config_new, - option::get_with_default(&borrowable_in_isolation, false)); - set_siloed_borrowing(&mut reserve_config_new, - option::get_with_default(&siloed_borrowing, false)); - set_borrowing_enabled(&mut reserve_config_new, - option::get_with_default(&borrowing_enabled, false)); - set_reserve_factor(&mut reserve_config_new, - option::get_with_default(&reserve_factor, 104)); - set_borrow_cap(&mut reserve_config_new, option::get_with_default(&borrow_cap, 105)); - set_supply_cap(&mut reserve_config_new, option::get_with_default(&supply_cap, 106)); - set_debt_ceiling(&mut reserve_config_new, - option::get_with_default(&debt_ceiling, 107)); - set_liquidation_protocol_fee(&mut reserve_config_new, - option::get_with_default(&liquidation_protocol_fee, 108)); - set_unbacked_mint_cap(&mut reserve_config_new, - option::get_with_default(&unbacked_mint_cap, 109)); - set_emode_category(&mut reserve_config_new, - option::get_with_default(&e_mode_category, 0)); - set_flash_loan_enabled(&mut reserve_config_new, - option::get_with_default(&flash_loan_enabled, true)); + set_borrowable_in_isolation( + &mut reserve_config_new, + option::get_with_default(&borrowable_in_isolation, false), + ); + set_siloed_borrowing( + &mut reserve_config_new, option::get_with_default(&siloed_borrowing, false) + ); + set_borrowing_enabled( + &mut reserve_config_new, option::get_with_default(&borrowing_enabled, false) + ); + set_reserve_factor( + &mut reserve_config_new, option::get_with_default(&reserve_factor, 104) + ); + set_borrow_cap( + &mut reserve_config_new, option::get_with_default(&borrow_cap, 105) + ); + set_supply_cap( + &mut reserve_config_new, option::get_with_default(&supply_cap, 106) + ); + set_debt_ceiling( + &mut reserve_config_new, option::get_with_default(&debt_ceiling, 107) + ); + set_liquidation_protocol_fee( + &mut reserve_config_new, + option::get_with_default(&liquidation_protocol_fee, 108), + ); + set_unbacked_mint_cap( + &mut reserve_config_new, option::get_with_default(&unbacked_mint_cap, 109) + ); + set_emode_category( + &mut reserve_config_new, option::get_with_default(&e_mode_category, 0) + ); + set_flash_loan_enabled( + &mut reserve_config_new, option::get_with_default(&flash_loan_enabled, true) + ); // set the reserve configuration test_set_reserve_configuration(underlying_asset_addr, reserve_config_new); - let reserve_index = get_reserves_count(); - reserve_index + let reserve_data = get_reserve_data(underlying_asset_addr); + + (get_reserve_liquidity_index(&reserve_data) as u256) } public fun create_user_config_for_reserve( @@ -552,11 +764,16 @@ module aave_pool::pool_tests { is_using_as_collateral: Option, ) { let user_config_map = get_user_configuration(user); - set_borrowing(&mut user_config_map, reserve_index, - option::get_with_default(&is_borrowing, false)); - set_using_as_collateral(&mut user_config_map, + set_borrowing( + &mut user_config_map, reserve_index, - option::get_with_default(&is_using_as_collateral, false)); + option::get_with_default(&is_borrowing, false), + ); + set_using_as_collateral( + &mut user_config_map, + reserve_index, + option::get_with_default(&is_using_as_collateral, false), + ); // set the user configuration set_user_configuration(user, user_config_map); } diff --git a/aave-core/tests/aave-supply-borrow/borrow_logic_tests.move b/aave-core/tests/aave-supply-borrow/borrow_logic_tests.move index 4aa57d5..4232ba1 100644 --- a/aave-core/tests/aave-supply-borrow/borrow_logic_tests.move +++ b/aave-core/tests/aave-supply-borrow/borrow_logic_tests.move @@ -3,212 +3,301 @@ module aave_pool::borrow_logic_tests { use std::features::change_feature_flags_for_testing; use std::option::Self; use std::signer; - use std::string::utf8; + use std::string::{utf8, String}; + use std::vector; + use aptos_std::debug::print; + use aptos_std::string_utils; use aptos_framework::account; - use aptos_framework::timestamp::set_time_has_started_for_testing; - use aptos_framework::timestamp::{Self, fast_forward_seconds}; - - use aave_acl::acl_manage::{Self, test_init_module}; + use aptos_framework::event::emitted_events; + use aptos_framework::timestamp::{ + set_time_has_started_for_testing, + fast_forward_seconds + }; + use aave_acl::acl_manage::{Self}; + use aave_config::reserve; + use aave_config::user::is_using_as_collateral_or_borrowing; use aave_math::wad_ray_math; - use aave_mock_oracle::oracle::test_init_oracle; + use aave_mock_oracle::oracle::Self; use aave_mock_oracle::oracle_sentinel::Self; - + use aave_pool::collector; + use aave_pool::pool_configurator; + use aave_pool::pool::{ + get_reserve_id, + get_reserve_data, + test_set_reserve_configuration, + get_reserve_liquidity_index, + get_user_configuration, + }; use aave_pool::a_token_factory::Self; use aave_pool::default_reserve_interest_rate_strategy::Self; - use aave_pool::emode_logic::Self; - use aave_pool::pool_configurator::test_init_module as pool_config_init_reserves; - use aave_pool::pool_tests::{create_reserve_with_config, create_user_config_for_reserve}; use aave_pool::supply_logic::Self; + use aave_pool::borrow_logic::Self; use aave_pool::token_base::Self; - use aave_pool::underlying_token_factory::Self; - use aave_pool::variable_token_factory::Self; + use aave_pool::mock_underlying_token_factory::Self; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; -// #[test(pool = @aave_pool, aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, aave_mock_oracle = @aave_mock_oracle, aave_std = @std, supply_user = @0x042, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aptos_framework = @0x1, collector_account = @0x55, borrower = @0x60,)] -// /// Reserve allows borrowing and being used as collateral. -// /// User config allows borrowing and collateral. -// /// User supplies and withdraws the entire amount -// /// with ltv and no debt ceiling, and not using as collateral already -// fun test_borrow_repay( -// pool: &signer, -// aave_pool: &signer, -// aave_role_super_admin: &signer, -// aave_mock_oracle: &signer, -// aave_std: &signer, -// supply_user: &signer, -// variable_tokens_admin: &signer, -// a_tokens_admin: &signer, -// underlying_tokens_admin: &signer, -// aptos_framework: &signer, -// collector_account: &signer, -// borrower: &signer, -// ) { -// // start the timer -// set_time_has_started_for_testing(aptos_framework); -// -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // create a tokens admin account -// account::create_account_for_test(signer::address_of(a_tokens_admin)); -// -// // init the acl module and make aave_pool the asset listing/pool admin -// test_init_module(aave_role_super_admin); -// acl_manage::add_asset_listing_admin(aave_role_super_admin, signer::address_of(pool)); -// acl_manage::add_pool_admin(aave_role_super_admin, signer::address_of(pool)); -// -// // init the oracle incl. sentinel -// test_init_oracle(aave_mock_oracle); -// -// // init the oracle sentinel -// let grace_period = (1000 as u64); -// oracle_sentinel::set_grace_period(pool, (grace_period as u256)); -// -// // init pool configurator and pool modules -// pool_config_init_reserves(pool); -// -// // define an emode cat for reserve and user -// let emode_cat_id1: u8 = 1; -// // configure an emode category -// let ltv1: u16 = 10000; -// let liquidation_threshold1: u16 = 10000; -// let liquidation_bonus1: u16 = 0; -// let price_source1: address = @0x01; -// let label1 = utf8(b"MODE1"); -// emode_logic::configure_emode_category(emode_cat_id1, -// ltv1, -// liquidation_threshold1, -// liquidation_bonus1, -// price_source1, -// label1); -// -// // init underlying tokens -// underlying_token_factory::test_init_module(aave_pool); -// let underlying_token_name = utf8(b"TOKEN_1"); -// let underlying_token_symbol = utf8(b"T1"); -// let underlying_token_decimals = 3; -// let underlying_token_max_supply = 10000; -// underlying_token_factory::create_token(underlying_tokens_admin, -// underlying_token_max_supply, -// underlying_token_name, -// underlying_token_symbol, -// underlying_token_decimals, -// utf8(b""), -// utf8(b""),); -// let underlying_token_address = underlying_token_factory::token_address( -// underlying_token_symbol); -// -// // init token base for tokens -// token_base::test_init_module(aave_pool); -// -// // create variable tokens -// variable_token_factory::create_token(variable_tokens_admin, -// utf8(b"TEST_VAR_TOKEN_1"), -// utf8(b"VAR1"), -// underlying_token_decimals, -// utf8(b""), -// utf8(b""), -// @0x033, // take random -// ); -// let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); -// -// //create a tokens -// let a_token_symbol = utf8(b"A1"); -// a_token_factory::create_token(a_tokens_admin, -// utf8(b"TEST_A_TOKEN_1"), -// a_token_symbol, -// underlying_token_decimals, -// utf8(b""), -// utf8(b""), -// underlying_token_address, // underlying asset address -// signer::address_of(collector_account), // treasury address -// ); -// let a_token_address = a_token_factory::token_address(utf8(b"A1")); -// -// // init the default interest rate strategy for the underlying_token_address -// let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); -// let base_variable_borrow_rate: u256 = 0; -// let variable_rate_slope1: u256 = 0; -// let variable_rate_slope2: u256 = 0; -// default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy(pool, -// underlying_token_address, -// optimal_usage_ratio, -// base_variable_borrow_rate, -// variable_rate_slope1, -// variable_rate_slope2,); -// -// // init and add a single reserve to the pool -// let reserve_index = -// create_reserve_with_config((underlying_token_decimals as u256), -// a_token_address, -// variable_token_address, -// underlying_token_address, -// option::some(5000), // NOTE: set ltv -// option::none(), // liq threshold -// option::none(), // liq bonus -// option::some((underlying_token_decimals as u256)), //decimals -// option::some(true), //active -// option::some(false), //frozen -// option::some(false), // paused -// option::some(true), // borrowable_in_isolation -// option::some(true), // siloed_borrowing -// option::some(true), // borrowing_enabled -// option::none(), // reserve_factor* -// option::none(), // borrow_cap -// option::none(), // supply_cap -// option::some(0), // NOTE: set no debt_ceiling -// option::none(), // liquidation_protocol_fee -// option::none(), // unbacked_mint_cap -// option::some((emode_cat_id1 as u256)), // e_mode_category -// option::some(true), // flash_loan_enabled -// ); -// -// // init user config for reserve index -// create_user_config_for_reserve(signer::address_of(supply_user), reserve_index, -// option::some(false), option::some(false)); -// -// // =============== MINT UNDERLYING FOR SUPPLIER ================= // -// // mint 100 underlying tokens for the user -// let mint_receiver_address = signer::address_of(supply_user); -// underlying_token_factory::mint(underlying_tokens_admin, mint_receiver_address, 100, -// underlying_token_address); -// -// // =============== SUPPLIER SUPPLIES ================= // -// // user supplies the underlying token -// let supply_receiver_address = signer::address_of(supply_user); -// let supplied_amount: u64 = 50; -// supply_logic::supply(supply_user, -// underlying_token_address, -// (supplied_amount as u256), -// supply_receiver_address, -// 0); -// -// // =============== SET ORACLE ================= // -// // set oracle to make sure borrow is allowed -// oracle_sentinel::set_answer(pool, false, (timestamp::now_seconds() as u256)); -// fast_forward_seconds((timestamp::now_seconds() + grace_period + 1)); -// assert!(oracle_sentinel::is_borrow_allowed(), TEST_SUCCESS); -// -// // =============== SET BORROWER EMODE ================= // -// // set user emode -// emode_logic::set_user_emode(borrower, emode_cat_id1); -// -// // =============== BORROWER BORROWS ================= // -// let _borrowed_amount = 30; -// let _interest_rate_mode: u8 = 2; -// // here user is expected to be in emode category of 1 -// /* -// borrow_logic::borrow( -// borrower, -// underlying_token_address, -// signer::address_of(borrower), -// borrowed_amount, -// interest_rate_mode, -// 0, -// true, -// ); -// */ -// } + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, supply_user = @0x042, underlying_tokens_admin = @underlying_tokens)] + /// Reserve allows borrowing and being used as collateral. + /// User config allows only borrowing for the reserve. + /// User supplies and withdraws parts of the supplied amount + fun test_supply_borrow( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + supply_user: &signer, + underlying_tokens_admin: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_ltv(&mut reserve_config_new, 5000); // NOTE: set ltv + reserve::set_debt_ceiling(&mut reserve_config_new, 0); // NOTE: set no debt_ceiling + reserve::set_borrowable_in_isolation(&mut reserve_config_new, false); // NOTE: no borrowing in isolation + reserve::set_siloed_borrowing(&mut reserve_config_new, false); // NOTE: no siloed borrowing + reserve::set_flash_loan_enabled(&mut reserve_config_new, false); // NOTE: no flashloans + reserve::set_borrowing_enabled(&mut reserve_config_new, true); // NOTE: enable borrowing + reserve::set_liquidation_threshold(&mut reserve_config_new, 4000); // NOTE: enable liq. threshold + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // =============== MINT UNDERLYING FOR USER & USER SUPPLIES ================= // + // mint 100 underlying tokens for the user + let mint_amount = 100; + let supplied_amount: u64 = 10; + let supply_receiver_address = signer::address_of(supply_user); + let mint_receiver_address = signer::address_of(supply_user); + for (i in 0..vector::length(&underlying_assets)) { + let underlying_token_address = *vector::borrow(&underlying_assets, i); + + // mint tokens for the user + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + mint_amount, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == mint_amount, TEST_SUCCESS); + // assert underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some((mint_amount as u128)), + TEST_SUCCESS, + ); + + // init user config for reserve index + let reserve_data = get_reserve_data(underlying_token_address); + + // let user supply + supply_logic::supply( + supply_user, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + let user_config_map = get_user_configuration(signer::address_of(supply_user)); + assert!( + is_using_as_collateral_or_borrowing( + &user_config_map, (get_reserve_id(&reserve_data) as u256) + ), + TEST_SUCCESS, + ); + + // check supplier balance of underlying + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!( + supplier_balance == initial_user_balance - supplied_amount, + TEST_SUCCESS, + ); + + // check underlying supply (must not have changed) + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some((mint_amount as u128)), + TEST_SUCCESS, + ); + + // check a_token underlying balance + let a_token_address = + a_token_factory::token_address( + signer::address_of(aave_pool), + *vector::borrow(&atokens_symbols, i), + ); + let atoken_account_address = + a_token_factory::get_token_account_address(a_token_address); + let underlying_account_balance = + mock_underlying_token_factory::balance_of( + atoken_account_address, underlying_token_address + ); + assert!(underlying_account_balance == supplied_amount, TEST_SUCCESS); + // check user a_token balance after supply + let supplied_amount_scaled = + wad_ray_math::ray_div( + (supplied_amount as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + assert!(supplier_a_token_balance == supplied_amount_scaled, TEST_SUCCESS); + }; + + // =============== ADJUST ORACLE TO ALLOW BORROW ================= // + // set new grace period + let grace_period = 1000; + oracle_sentinel::set_grace_period(aave_pool, grace_period); + // assert set grace period + assert!(oracle_sentinel::get_grace_period() == 1000, TEST_SUCCESS); + // fast forward grace_period + fast_forward_seconds(((grace_period + 5) as u64)); + // assert borrow is not allowed + assert!(oracle_sentinel::is_borrow_allowed(), TEST_SUCCESS); + + // set oracle asset prices + for (i in 0..vector::length(&underlying_assets)) { + let underlying_token_address = *vector::borrow(&underlying_assets, i); + oracle::set_asset_price(mock_oracle, underlying_token_address, 100); + }; + + // =============== USER BORROWS FIRST TWO ASSETS ================= // + // user supplies the underlying token + let borrow_receiver_address = signer::address_of(supply_user); + let borrowed_amount: u64 = 1; + for (i in 0..2) { + let underlying_token_address = *vector::borrow(&underlying_assets, i); + borrow_logic::borrow( + supply_user, + underlying_token_address, + (borrowed_amount as u256), + 2, // variable interest rate mode + 0, // referral + borrow_receiver_address, + ); + }; + + // check emitted events + let emitted_borrow_events = emitted_events(); + assert!(vector::length(&emitted_borrow_events) == 2, TEST_SUCCESS); + } } diff --git a/aave-core/tests/aave-supply-borrow/supply_logic_tests.move b/aave-core/tests/aave-supply-borrow/supply_logic_tests.move index 161cbe7..b48efea 100644 --- a/aave-core/tests/aave-supply-borrow/supply_logic_tests.move +++ b/aave-core/tests/aave-supply-borrow/supply_logic_tests.move @@ -3,632 +3,852 @@ module aave_pool::supply_logic_tests { use std::features::change_feature_flags_for_testing; use std::option::Self; use std::signer; - use std::string::utf8; + use std::string::{utf8, String}; use std::vector; + use aptos_std::string_utils; use aptos_framework::account; use aptos_framework::event::emitted_events; use aptos_framework::timestamp::set_time_has_started_for_testing; - - use aave_acl::acl_manage::{Self, test_init_module}; + use aave_acl::acl_manage::{Self}; + use aave_config::reserve; use aave_math::wad_ray_math; - use aave_mock_oracle::oracle::test_init_oracle; - + use aave_mock_oracle::oracle; + use aave_pool::collector; + use aave_pool::pool_configurator; + use aave_pool::pool::{ + get_reserve_id, + get_reserve_data, + test_set_reserve_configuration, + get_reserve_liquidity_index + }; use aave_pool::a_token_factory::Self; use aave_pool::default_reserve_interest_rate_strategy::Self; - use aave_pool::emode_logic::Self; - use aave_pool::pool_configurator::test_init_module as pool_config_init_reserves; - use aave_pool::pool_tests::{create_reserve_with_config, create_user_config_for_reserve}; + use aave_pool::emode_logic::{Self, configure_emode_category}; + use aave_pool::pool_tests::create_user_config_for_reserve; use aave_pool::supply_logic::Self; use aave_pool::token_base::Self; - use aave_pool::underlying_token_factory::Self; - use aave_pool::variable_token_factory::Self; + use aave_pool::mock_underlying_token_factory::Self; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; -// -// #[test(pool = @aave_pool, aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aave_std = @std, supply_user = @0x042, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aptos_framework = @0x1, collector_account = @0x55,)] -// /// Reserve allows borrowing and being used as collateral. -// /// User config allows only borrowing for the reserve. -// /// User supplies and withdraws parts of the supplied amount -// fun test_supply_partial_withdraw( -// pool: &signer, -// aave_pool: &signer, -// aave_role_super_admin: &signer, -// mock_oracle: &signer, -// aave_std: &signer, -// supply_user: &signer, -// variable_tokens_admin: &signer, -// a_tokens_admin: &signer, -// underlying_tokens_admin: &signer, -// aptos_framework: &signer, -// collector_account: &signer, -// ) { -// // start the timer -// set_time_has_started_for_testing(aptos_framework); -// -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // create a tokens admin account -// account::create_account_for_test(signer::address_of(a_tokens_admin)); -// -// // init the acl module and make aave_pool the asset listing/pool admin -// test_init_module(aave_role_super_admin); -// acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); -// acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); -// -// // init oracle -// test_init_oracle(mock_oracle); -// -// // init pool conigutrator and pool modules -// pool_config_init_reserves(pool); -// -// // init underlying tokens -// underlying_token_factory::test_init_module(aave_pool); -// let underlying_token_name = utf8(b"TOKEN_1"); -// let underlying_token_symbol = utf8(b"T1"); -// let underlying_token_decimals = 3; -// let underlying_token_max_supply = 10000; -// underlying_token_factory::create_token(underlying_tokens_admin, -// underlying_token_max_supply, -// underlying_token_name, -// underlying_token_symbol, -// underlying_token_decimals, -// utf8(b""), -// utf8(b""),); -// let underlying_token_address = underlying_token_factory::token_address( -// underlying_token_symbol); -// -// // init token base for tokens -// token_base::test_init_module(aave_pool); -// -// // create variable tokens -// variable_token_factory::create_token(variable_tokens_admin, -// utf8(b"TEST_VAR_TOKEN_1"), -// utf8(b"VAR1"), -// underlying_token_decimals, -// utf8(b""), -// utf8(b""), -// @0x033, // take random -// ); -// let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); -// -// //create a tokens -// let a_token_symbol = utf8(b"A1"); -// a_token_factory::create_token(a_tokens_admin, -// utf8(b"TEST_A_TOKEN_1"), -// a_token_symbol, -// underlying_token_decimals, -// utf8(b""), -// utf8(b""), -// underlying_token_address, // underlying asset address -// signer::address_of(collector_account), // treasury address -// ); -// let a_token_address = a_token_factory::token_address(utf8(b"A1")); -// -// // init and add a single reserve to the pool -// let reserve_index = -// create_reserve_with_config((underlying_token_decimals as u256), -// a_token_address, -// variable_token_address, -// underlying_token_address, -// option::none(), // ltv -// option::none(), // liq threshold -// option::none(), // liq bonus -// option::some((underlying_token_decimals as u256)), //decimals -// option::some(true), //active -// option::some(false), //frozen -// option::some(false), // paused -// option::some(true), // borrowable_in_isolation -// option::some(true), // siloed_borrowing -// option::some(true), // borrowing_enabled -// option::none(), // reserve_factor* -// option::none(), // borrow_cap -// option::none(), // supply_cap -// option::none(), // debt_ceiling -// option::none(), // liquidation_protocol_fee -// option::none(), // unbacked_mint_cap -// option::some((0 as u256)), // e_mode_category -// option::some(true), // flash_loan_enabled -// ); -// -// // init the default interest rate strategy for the underlying_token_address -// let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); -// let base_variable_borrow_rate: u256 = 0; -// let variable_rate_slope1: u256 = 0; -// let variable_rate_slope2: u256 = 0; -// default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy(pool, -// underlying_token_address, -// optimal_usage_ratio, -// base_variable_borrow_rate, -// variable_rate_slope1, -// variable_rate_slope2,); -// -// // init user config for reserve index -// create_user_config_for_reserve(signer::address_of(supply_user), reserve_index, -// option::some(false), option::some(true)); -// -// // =============== MINT UNDERLYING FOR USER ================= // -// // mint 100 underlying tokens for the user -// let mint_receiver_address = signer::address_of(supply_user); -// underlying_token_factory::mint(underlying_tokens_admin, mint_receiver_address, 100, -// underlying_token_address); -// let initial_user_balance = -// underlying_token_factory::balance_of(mint_receiver_address, -// underlying_token_address); -// // assert user balance of underlying -// assert!(initial_user_balance == 100, TEST_SUCCESS); -// // assert underlying supply -// assert!(underlying_token_factory::supply(underlying_token_address) -// == option::some(100), -// TEST_SUCCESS); -// -// // =============== USER SUPPLY ================= // -// // user supplies the underlying token -// let supply_receiver_address = signer::address_of(supply_user); -// let supplied_amount: u64 = 10; -// supply_logic::supply(supply_user, -// underlying_token_address, -// (supplied_amount as u256), -// supply_receiver_address, -// 0); -// -// // > check emitted events -// let emitted_supply_events = emitted_events(); -// assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); -// // > check supplier balance of underlying -// let supplier_balance = -// underlying_token_factory::balance_of(mint_receiver_address, -// underlying_token_address); -// assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); -// // > check underlying supply -// assert!(underlying_token_factory::supply(underlying_token_address) -// == option::some(100), -// TEST_SUCCESS); -// // > check a_token underlying balance -// let atoken_acocunt_address = a_token_factory::get_token_account_address( -// a_token_address); -// let underlying_acocunt_balance = -// underlying_token_factory::balance_of(atoken_acocunt_address, -// underlying_token_address); -// assert!(underlying_acocunt_balance == supplied_amount, TEST_SUCCESS); -// // > check user a_token balance after supply -// let supplier_a_token_balance = -// a_token_factory::balance_of(signer::address_of(supply_user), a_token_address); -// assert!(supplier_a_token_balance == (supplied_amount as u256), TEST_SUCCESS); -// -// // =============== USER WITHDRAWS ================= // -// // user withdraws a small amount of the supplied amount -// let amount_to_withdraw = 4; -// supply_logic::withdraw(supply_user, underlying_token_address, (amount_to_withdraw as u256), -// supply_receiver_address); -// -// // > check a_token balance of underlying -// let atoken_acocunt_balance = -// underlying_token_factory::balance_of(atoken_acocunt_address, -// underlying_token_address); -// assert!(atoken_acocunt_balance == supplied_amount - amount_to_withdraw, TEST_SUCCESS); -// // > check underlying supply -// assert!(underlying_token_factory::supply(underlying_token_address) -// == option::some(100), -// TEST_SUCCESS); -// // > check user a_token balance after withdrawal -// let supplier_a_token_balance = -// a_token_factory::balance_of(signer::address_of(supply_user), a_token_address); -// assert!(supplier_a_token_balance -// == ((supplied_amount - amount_to_withdraw) as u256), TEST_SUCCESS); -// // > check users underlying tokens balance -// let supplier_underlying_balance_after_withdraw = -// underlying_token_factory::balance_of(mint_receiver_address, -// underlying_token_address); -// assert!(supplier_underlying_balance_after_withdraw -// == initial_user_balance - supplied_amount + amount_to_withdraw, -// TEST_SUCCESS); -// // > check emitted events -// let emitted_withdraw_events = emitted_events(); -// assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); -// let emitted_reserve_collecteral_disabled_events = emitted_events(); -// assert!(vector::length(&emitted_reserve_collecteral_disabled_events) == 0, -// TEST_SUCCESS); -// } -// -// #[test(pool = @aave_pool, aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aave_std = @std, supply_user = @0x042, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aptos_framework = @0x1, collector_account = @0x55,)] -// /// Reserve allows borrowing and being used as collateral. -// /// User config allows borrowing and collateral. -// /// User supplies and withdraws the entire amount -// fun test_supply_full_collateral_withdraw( -// pool: &signer, -// aave_pool: &signer, -// aave_role_super_admin: &signer, -// mock_oracle: &signer, -// aave_std: &signer, -// supply_user: &signer, -// variable_tokens_admin: &signer, -// a_tokens_admin: &signer, -// underlying_tokens_admin: &signer, -// aptos_framework: &signer, -// collector_account: &signer, -// ) { -// // start the timer -// set_time_has_started_for_testing(aptos_framework); -// -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // create a tokens admin account -// account::create_account_for_test(signer::address_of(a_tokens_admin)); -// -// // init the acl module and make aave_pool the asset listing/pool admin -// test_init_module(aave_role_super_admin); -// acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); -// acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); -// -// // init oracle -// test_init_oracle(mock_oracle); -// -// // init pool conigutrator and pool modules -// pool_config_init_reserves(pool); -// -// // define an emode cat for reserve and user -// let emode_cat_id1: u8 = 1; -// // configure an emode category -// let ltv1: u16 = 10000; -// let liquidation_threshold1: u16 = 10000; -// let liquidation_bonus1: u16 = 0; -// let price_source1: address = @0x01; -// let label1 = utf8(b"MODE1"); -// emode_logic::configure_emode_category(emode_cat_id1, -// ltv1, -// liquidation_threshold1, -// liquidation_bonus1, -// price_source1, -// label1); -// -// // init underlying tokens -// underlying_token_factory::test_init_module(aave_pool); -// let underlying_token_name = utf8(b"TOKEN_1"); -// let underlying_token_symbol = utf8(b"T1"); -// let underlying_token_decimals = 3; -// let underlying_token_max_supply = 10000; -// underlying_token_factory::create_token(underlying_tokens_admin, -// underlying_token_max_supply, -// underlying_token_name, -// underlying_token_symbol, -// underlying_token_decimals, -// utf8(b""), -// utf8(b""),); -// let underlying_token_address = underlying_token_factory::token_address( -// underlying_token_symbol); -// -// // init token base for tokens -// token_base::test_init_module(aave_pool); -// -// // create variable tokens -// variable_token_factory::create_token(variable_tokens_admin, -// utf8(b"TEST_VAR_TOKEN_1"), -// utf8(b"VAR1"), -// underlying_token_decimals, -// utf8(b""), -// utf8(b""), -// @0x033, // take random -// ); -// let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); -// -// //create a tokens -// let a_token_symbol = utf8(b"A1"); -// a_token_factory::create_token(a_tokens_admin, -// utf8(b"TEST_A_TOKEN_1"), -// a_token_symbol, -// underlying_token_decimals, -// utf8(b""), -// utf8(b""), -// underlying_token_address, // underlying asset address -// signer::address_of(collector_account), // treasury address -// ); -// let a_token_address = a_token_factory::token_address(utf8(b"A1")); -// -// // init the default interest rate strategy for the underlying_token_address -// let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); -// let base_variable_borrow_rate: u256 = 0; -// let variable_rate_slope1: u256 = 0; -// let variable_rate_slope2: u256 = 0; -// default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy(pool, -// underlying_token_address, -// optimal_usage_ratio, -// base_variable_borrow_rate, -// variable_rate_slope1, -// variable_rate_slope2,); -// -// // init and add a single reserve to the pool -// let reserve_index = -// create_reserve_with_config((underlying_token_decimals as u256), -// a_token_address, -// variable_token_address, -// underlying_token_address, -// option::none(), // ltv -// option::none(), // liq threshold -// option::none(), // liq bonus -// option::some((underlying_token_decimals as u256)), //decimals -// option::some(true), //active -// option::some(false), //frozen -// option::some(false), // paused -// option::some(true), // borrowable_in_isolation -// option::some(true), // siloed_borrowing -// option::some(true), // borrowing_enabled -// option::none(), // reserve_factor* -// option::none(), // borrow_cap -// option::none(), // supply_cap -// option::none(), // debt_ceiling -// option::none(), // liquidation_protocol_fee -// option::none(), // unbacked_mint_cap -// option::some((emode_cat_id1 as u256)), // e_mode_category -// option::some(true), // flash_loan_enabled -// ); -// -// // init user config for reserve index -// create_user_config_for_reserve(signer::address_of(supply_user), reserve_index, -// option::some(true), option::some(true)); -// -// // set user emode -// emode_logic::set_user_emode(supply_user, emode_cat_id1); -// -// // =============== MINT UNDERLYING FOR USER ================= // -// // mint 100 underlying tokens for the user -// let mint_receiver_address = signer::address_of(supply_user); -// underlying_token_factory::mint(underlying_tokens_admin, mint_receiver_address, 100, -// underlying_token_address); -// let initial_user_balance = -// underlying_token_factory::balance_of(mint_receiver_address, -// underlying_token_address); -// // assert user balance of underlying -// assert!(initial_user_balance == 100, TEST_SUCCESS); -// // asser underlying supply -// assert!(underlying_token_factory::supply(underlying_token_address) -// == option::some(100), -// TEST_SUCCESS); -// -// // =============== USER SUPPLY ================= // -// // user supplies the underlying token -// let supply_receiver_address = signer::address_of(supply_user); -// let supplied_amount: u64 = 50; -// supply_logic::supply(supply_user, -// underlying_token_address, -// (supplied_amount as u256), -// supply_receiver_address, -// 0); -// -// // > check emitted events -// let emitted_supply_events = emitted_events(); -// assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); -// // > check supplier balance of underlying -// let supplier_balance = -// underlying_token_factory::balance_of(mint_receiver_address, -// underlying_token_address); -// assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); -// // > check underlying supply -// assert!(underlying_token_factory::supply(underlying_token_address) -// == option::some(100), -// TEST_SUCCESS); -// // > check underlying balance of atoken -// let atoken_account_address = a_token_factory::get_token_account_address( -// a_token_address); -// let underlying_acocunt_balance = -// underlying_token_factory::balance_of(atoken_account_address, -// underlying_token_address); -// assert!(underlying_acocunt_balance == supplied_amount, TEST_SUCCESS); -// // > check user a_token balance after supply -// let supplier_a_token_balance = -// a_token_factory::balance_of(signer::address_of(supply_user), a_token_address); -// assert!(supplier_a_token_balance == (supplied_amount as u256), TEST_SUCCESS); -// -// // =============== USER WITHDRAWS ================= // -// // user withdraws his entire supply -// let amount_to_withdraw = 50; -// supply_logic::withdraw(supply_user, underlying_token_address, (amount_to_withdraw as u256), -// supply_receiver_address); -// -// // > check underlying balance of a_token account -// let atoken_acocunt_balance = -// underlying_token_factory::balance_of(atoken_account_address, -// underlying_token_address); -// assert!(atoken_acocunt_balance == 0, TEST_SUCCESS); -// // > check underlying supply -// assert!(underlying_token_factory::supply(underlying_token_address) -// == option::some(100), -// TEST_SUCCESS); -// // > check user a_token balance after withdrawal -// let supplier_a_token_balance = -// a_token_factory::balance_of(signer::address_of(supply_user), a_token_address); -// assert!(supplier_a_token_balance == 0, TEST_SUCCESS); -// // > check users underlying tokens balance -// let supplier_underlying_balance_after_withdraw = -// underlying_token_factory::balance_of(mint_receiver_address, -// underlying_token_address); -// assert!(supplier_underlying_balance_after_withdraw -// == initial_user_balance - supplied_amount + amount_to_withdraw, -// TEST_SUCCESS); -// // > check emitted events -// let emitted_withdraw_events = emitted_events(); -// assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); -// let emitted_reserve_collecteral_disabled_events = emitted_events(); -// assert!(vector::length(&emitted_reserve_collecteral_disabled_events) == 1, -// TEST_SUCCESS); -// } -// -// #[test(pool = @aave_pool, aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aave_std = @std, supply_user = @0x042, variable_tokens_admin = @variable_tokens, a_tokens_admin = @a_tokens, underlying_tokens_admin = @underlying_tokens, aptos_framework = @0x1, collector_account = @0x55,)] -// /// Reserve allows borrowing and being used as collateral. -// /// User config allows borrowing and collateral. -// /// User supplies and withdraws the entire amount -// /// with ltv and no debt ceiling, and not using as collateral already -// fun test_supply_use_as_collateral( -// pool: &signer, -// aave_pool: &signer, -// aave_role_super_admin: &signer, -// mock_oracle: &signer, -// aave_std: &signer, -// supply_user: &signer, -// variable_tokens_admin: &signer, -// a_tokens_admin: &signer, -// underlying_tokens_admin: &signer, -// aptos_framework: &signer, -// collector_account: &signer, -// ) { -// // start the timer -// set_time_has_started_for_testing(aptos_framework); -// -// // add the test events feature flag -// change_feature_flags_for_testing(aave_std, vector[26], vector[]); -// -// // create a tokens admin account -// account::create_account_for_test(signer::address_of(a_tokens_admin)); -// -// // init the acl module and make aave_pool the asset listing/pool admin -// test_init_module(aave_role_super_admin); -// acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); -// acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); -// -// // init oracle -// test_init_oracle(mock_oracle); -// -// // init pool conigutrator and pool modules -// pool_config_init_reserves(pool); -// -// // init underlying tokens -// underlying_token_factory::test_init_module(aave_pool); -// let underlying_token_name = utf8(b"TOKEN_1"); -// let underlying_token_symbol = utf8(b"T1"); -// let underlying_token_decimals = 3; -// let underlying_token_max_supply = 10000; -// underlying_token_factory::create_token(underlying_tokens_admin, -// underlying_token_max_supply, -// underlying_token_name, -// underlying_token_symbol, -// underlying_token_decimals, -// utf8(b""), -// utf8(b""),); -// let underlying_token_address = underlying_token_factory::token_address( -// underlying_token_symbol); -// -// // init token base for tokens -// token_base::test_init_module(aave_pool); -// -// // create variable tokens -// variable_token_factory::create_token(variable_tokens_admin, -// utf8(b"TEST_VAR_TOKEN_1"), -// utf8(b"VAR1"), -// underlying_token_decimals, -// utf8(b""), -// utf8(b""), -// @0x033, // take random -// ); -// let variable_token_address = variable_token_factory::token_address(utf8(b"VAR1")); -// -// //create a tokens -// let a_token_symbol = utf8(b"A1"); -// a_token_factory::create_token(a_tokens_admin, -// utf8(b"TEST_A_TOKEN_1"), -// a_token_symbol, -// underlying_token_decimals, -// utf8(b""), -// utf8(b""), -// underlying_token_address, // underlying asset address -// signer::address_of(collector_account), // treasury address -// ); -// let a_token_address = a_token_factory::token_address(utf8(b"A1")); -// -// // init the default interest rate strategy for the underlying_token_address -// let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); -// let base_variable_borrow_rate: u256 = 0; -// let variable_rate_slope1: u256 = 0; -// let variable_rate_slope2: u256 = 0; -// default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy(pool, -// underlying_token_address, -// optimal_usage_ratio, -// base_variable_borrow_rate, -// variable_rate_slope1, -// variable_rate_slope2,); -// -// // init and add a single reserve to the pool -// let reserve_index = -// create_reserve_with_config((underlying_token_decimals as u256), -// a_token_address, -// variable_token_address, -// underlying_token_address, -// option::some(5000), // NOTE: set ltv -// option::none(), // liq threshold -// option::none(), // liq bonus -// option::some((underlying_token_decimals as u256)), //decimals -// option::some(true), //active -// option::some(false), //frozen -// option::some(false), // paused -// option::some(true), // borrowable_in_isolation -// option::some(true), // siloed_borrowing -// option::some(true), // borrowing_enabled -// option::none(), // reserve_factor* -// option::none(), // borrow_cap -// option::none(), // supply_cap -// option::some(0), // NOTE: set no debt_ceiling -// option::none(), // liquidation_protocol_fee -// option::none(), // unbacked_mint_cap -// option::some((0 as u256)), // e_mode_category -// option::some(true), // flash_loan_enabled -// ); -// -// // init user config for reserve index -// create_user_config_for_reserve(signer::address_of(supply_user), reserve_index, -// option::some(true), option::some(false) // NOTE: not using any as collateral already -// ); -// -// // =============== MINT UNDERLYING FOR USER ================= // -// // mint 100 underlying tokens for the user -// let mint_receiver_address = signer::address_of(supply_user); -// underlying_token_factory::mint(underlying_tokens_admin, mint_receiver_address, 100, -// underlying_token_address); -// let initial_user_balance = -// underlying_token_factory::balance_of(mint_receiver_address, -// underlying_token_address); -// // assert user balance of underlying -// assert!(initial_user_balance == 100, TEST_SUCCESS); -// // asser underlying supply -// assert!(underlying_token_factory::supply(underlying_token_address) -// == option::some(100), -// TEST_SUCCESS); -// -// // =============== USER SUPPLY ================= // -// // user supplies the underlying token -// let supply_receiver_address = signer::address_of(supply_user); -// let supplied_amount: u64 = 50; -// supply_logic::supply(supply_user, -// underlying_token_address, -// (supplied_amount as u256), -// supply_receiver_address, -// 0); -// -// // > check emitted events -// let emitted_supply_events = emitted_events(); -// assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); -// let emitted_reserve_used_as_collateral_events = emitted_events(); -// assert!(vector::length(&emitted_reserve_used_as_collateral_events) == 1, -// TEST_SUCCESS); -// // > check supplier balance of underlying -// let supplier_balance = -// underlying_token_factory::balance_of(mint_receiver_address, -// underlying_token_address); -// assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); -// // > check underlying supply -// assert!(underlying_token_factory::supply(underlying_token_address) -// == option::some(100), -// TEST_SUCCESS); -// // > check a_token balance of underlying -// let atoken_account_address = a_token_factory::get_token_account_address( -// a_token_address); -// let atoken_acocunt_balance = -// underlying_token_factory::balance_of(atoken_account_address, -// underlying_token_address); -// assert!(atoken_acocunt_balance == supplied_amount, TEST_SUCCESS); -// // > check user a_token balance after supply -// let supplier_a_token_balance = -// a_token_factory::balance_of(signer::address_of(supply_user), a_token_address); -// assert!(supplier_a_token_balance == (supplied_amount as u256), TEST_SUCCESS); -// } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, supply_user = @0x042, underlying_tokens_admin = @underlying_tokens)] + /// Reserve allows borrowing and being used as collateral. + /// User config allows only borrowing for the reserve. + /// User supplies and withdraws parts of the supplied amount + fun test_supply_partial_withdraw( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + supply_user: &signer, + underlying_tokens_admin: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, false); // NOTE: disable flashloan enabled + reserve::set_ltv(&mut reserve_config_new, 5000); // NOTE: set ltv + reserve::set_debt_ceiling(&mut reserve_config_new, 0); // NOTE: set no debt ceiling + reserve::set_borrowable_in_isolation(&mut reserve_config_new, false); // NOTE: set no borrowable in isolation + reserve::set_siloed_borrowing(&mut reserve_config_new, false); // NOTE: set no sillowed borrowing + reserve::set_borrowing_enabled(&mut reserve_config_new, true); // NOTE: set borrowing enabled + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + // get the reserve config for it + let reserve_data = get_reserve_data(underlying_token_address); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(supply_user), + (get_reserve_id(&reserve_data) as u256), + option::some(false), + option::some(true), + ); + + // =============== MINT UNDERLYING FOR USER ================= // + // mint 100 underlying tokens for the user + let mint_receiver_address = signer::address_of(supply_user); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + 100, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == 100, TEST_SUCCESS); + // assert underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + + // =============== USER SUPPLY ================= // + // user supplies the underlying token + let supply_receiver_address = signer::address_of(supply_user); + let supplied_amount: u64 = 10; + supply_logic::supply( + supply_user, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + // > check supplier balance of underlying + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); + // > check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + // > check a_token underlying balance + let a_token_address = + a_token_factory::token_address( + signer::address_of(aave_pool), + *vector::borrow(&atokens_symbols, 0), + ); + let atoken_acocunt_address = + a_token_factory::get_token_account_address(a_token_address); + let underlying_acocunt_balance = + mock_underlying_token_factory::balance_of( + atoken_acocunt_address, underlying_token_address + ); + assert!(underlying_acocunt_balance == supplied_amount, TEST_SUCCESS); + // > check user a_token balance after supply + let supplied_amount_scaled = + wad_ray_math::ray_div( + (supplied_amount as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + assert!(supplier_a_token_balance == supplied_amount_scaled, TEST_SUCCESS); + + // =============== USER WITHDRAWS ================= // + // user withdraws a small amount of the supplied amount + let amount_to_withdraw = 4; + supply_logic::withdraw( + supply_user, + underlying_token_address, + (amount_to_withdraw as u256), + supply_receiver_address, + ); + + // > check a_token balance of underlying + let atoken_acocunt_balance = + mock_underlying_token_factory::balance_of( + atoken_acocunt_address, underlying_token_address + ); + assert!( + atoken_acocunt_balance == supplied_amount - amount_to_withdraw, + TEST_SUCCESS, + ); + // > check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + // > check user a_token balance after withdrawal + let supplied_amount_scaled = + wad_ray_math::ray_div( + (supplied_amount - amount_to_withdraw as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + assert!(supplier_a_token_balance == supplied_amount_scaled, TEST_SUCCESS); + // > check users underlying tokens balance + let supplier_underlying_balance_after_withdraw = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!( + supplier_underlying_balance_after_withdraw + == initial_user_balance - supplied_amount + amount_to_withdraw, + TEST_SUCCESS, + ); + // > check emitted events + let emitted_withdraw_events = emitted_events(); + assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); + let emitted_reserve_collecteral_disabled_events = + emitted_events(); + assert!( + vector::length(&emitted_reserve_collecteral_disabled_events) == 0, + TEST_SUCCESS, + ); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, supply_user = @0x042, underlying_tokens_admin = @underlying_tokens)] + /// Reserve allows borrowing and being used as collateral. + /// User config allows borrowing and collateral. + /// User supplies and withdraws the entire amount + fun test_supply_full_collateral_withdraw( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + supply_user: &signer, + underlying_tokens_admin: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // define an emode cat for reserve and user + let emode_cat_id: u8 = 1; + // configure an emode category + let ltv: u16 = 100; + let liquidation_threshold: u16 = 200; + let liquidation_bonus: u16 = 300; + let price_source: address = signer::address_of(mock_oracle); + let label = utf8(b"MODE1"); + configure_emode_category( + emode_cat_id, + ltv, + liquidation_threshold, + liquidation_bonus, + price_source, + label, + ); + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, false); // NOTE: disable flashloan enabled + reserve::set_ltv(&mut reserve_config_new, 5000); // NOTE: set ltv + reserve::set_debt_ceiling(&mut reserve_config_new, 0); // NOTE: set no debt ceiling + reserve::set_borrowable_in_isolation(&mut reserve_config_new, false); // NOTE: set no borrowable in isolation + reserve::set_siloed_borrowing(&mut reserve_config_new, false); // NOTE: set no sillowed borrowing + reserve::set_borrowing_enabled(&mut reserve_config_new, true); // NOTE: set borrowing enabled + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + // set underlying emode category + pool_configurator::set_asset_emode_category( + aave_pool, underlying_token_address, emode_cat_id + ); + + // get the reserve config for it + let reserve_data = get_reserve_data(underlying_token_address); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(supply_user), + (get_reserve_id(&reserve_data) as u256), + option::some(true), + option::some(true), + ); + + // =============== MINT UNDERLYING FOR USER ================= // + // set user emode + emode_logic::set_user_emode(supply_user, emode_cat_id); + + // mint 100 underlying tokens for the user + let mint_receiver_address = signer::address_of(supply_user); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + 100, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == 100, TEST_SUCCESS); + // asser underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + + // =============== USER SUPPLY ================= // + // user supplies the underlying token + let supply_receiver_address = signer::address_of(supply_user); + let supplied_amount: u64 = 50; + supply_logic::supply( + supply_user, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + // > check supplier balance of underlying + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); + // > check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + // > check underlying balance of atoken + let a_token_address = + a_token_factory::token_address( + signer::address_of(aave_pool), + *vector::borrow(&atokens_symbols, 0), + ); + let atoken_account_address = + a_token_factory::get_token_account_address(a_token_address); + let underlying_acocunt_balance = + mock_underlying_token_factory::balance_of( + atoken_account_address, underlying_token_address + ); + assert!(underlying_acocunt_balance == supplied_amount, TEST_SUCCESS); + // > check user a_token balance after supply + let supplied_amount_scaled = + wad_ray_math::ray_div( + (supplied_amount as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + assert!(supplier_a_token_balance == supplied_amount_scaled, TEST_SUCCESS); + + // =============== USER WITHDRAWS ================= // + // user withdraws his entire supply + let amount_to_withdraw = 50; + supply_logic::withdraw( + supply_user, + underlying_token_address, + (amount_to_withdraw as u256), + supply_receiver_address, + ); + + // > check underlying balance of a_token account + let atoken_acocunt_balance = + mock_underlying_token_factory::balance_of( + atoken_account_address, underlying_token_address + ); + assert!(atoken_acocunt_balance == 0, TEST_SUCCESS); + // > check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + // > check user a_token balance after withdrawal + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + assert!(supplier_a_token_balance == 0, TEST_SUCCESS); + // > check users underlying tokens balance + let supplier_underlying_balance_after_withdraw = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!( + supplier_underlying_balance_after_withdraw + == initial_user_balance - supplied_amount + amount_to_withdraw, + TEST_SUCCESS, + ); + // > check emitted events + let emitted_withdraw_events = emitted_events(); + assert!(vector::length(&emitted_withdraw_events) == 1, TEST_SUCCESS); + let emitted_reserve_collecteral_disabled_events = + emitted_events(); + assert!( + vector::length(&emitted_reserve_collecteral_disabled_events) == 1, + TEST_SUCCESS, + ); + } + + #[test(aave_pool = @aave_pool, aave_role_super_admin = @aave_acl, mock_oracle = @aave_mock_oracle, aptos_std = @aptos_std, supply_user = @0x042, underlying_tokens_admin = @underlying_tokens)] + /// Reserve allows borrowing and being used as collateral. + /// User config allows borrowing and collateral. + /// User supplies and withdraws the entire amount + /// with ltv and no debt ceiling, and not using as collateral already + fun test_supply_use_as_collateral( + aave_pool: &signer, + aave_role_super_admin: &signer, + mock_oracle: &signer, + aptos_std: &signer, + supply_user: &signer, + underlying_tokens_admin: &signer, + ) { + // start the timer + set_time_has_started_for_testing(aptos_std); + + // add the test events feature flag + change_feature_flags_for_testing(aptos_std, vector[26], vector[]); + + // create test accounts + account::create_account_for_test(signer::address_of(aave_pool)); + + // init the acl module and make aave_pool the asset listing/pool admin + acl_manage::test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin(aave_role_super_admin, @aave_pool); + acl_manage::add_pool_admin(aave_role_super_admin, @aave_pool); + + // init collector + collector::init_module_test(aave_pool); + let collector_address = collector::collector_address(); + + // init token base (a tokens and var tokens) + token_base::test_init_module(aave_pool); + + // init underlying tokens + mock_underlying_token_factory::test_init_module(aave_pool); + + // init oracle module + oracle::test_init_oracle(mock_oracle); + + // init pool_configurator & reserves module + pool_configurator::test_init_module(aave_pool); + + // init input data for creating pool reserves + let treasuries: vector
= vector[]; + + // define an emode cat for reserve and user + let emode_cat_id: u8 = 1; + // configure an emode category + let ltv: u16 = 100; + let liquidation_threshold: u16 = 200; + let liquidation_bonus: u16 = 300; + let price_source: address = signer::address_of(mock_oracle); + let label = utf8(b"MODE1"); + configure_emode_category( + emode_cat_id, + ltv, + liquidation_threshold, + liquidation_bonus, + price_source, + label, + ); + + // prepare pool reserves + let underlying_assets: vector
= vector[]; + let underlying_asset_decimals: vector = vector[]; + let atokens_names: vector = vector[]; + let atokens_symbols: vector = vector[]; + let var_tokens_names: vector = vector[]; + let var_tokens_symbols: vector = vector[]; + let num_assets = 3; + for (i in 0..num_assets) { + let name = string_utils::format1(&b"APTOS_UNDERLYING_{}", i); + let symbol = string_utils::format1(&b"U_{}", i); + let decimals = 2 + i; + let max_supply = 10000; + mock_underlying_token_factory::create_token( + underlying_tokens_admin, + max_supply, + name, + symbol, + decimals, + utf8(b""), + utf8(b""), + ); + + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + + // init the default interest rate strategy for the underlying_token_address + let optimal_usage_ratio: u256 = wad_ray_math::get_half_ray_for_testing(); + let base_variable_borrow_rate: u256 = 0; + let variable_rate_slope1: u256 = 0; + let variable_rate_slope2: u256 = 0; + default_reserve_interest_rate_strategy::set_reserve_interest_rate_strategy( + aave_pool, + underlying_token_address, + optimal_usage_ratio, + base_variable_borrow_rate, + variable_rate_slope1, + variable_rate_slope2, + ); + + // prepare the data for reserve's atokens and variable tokens + vector::push_back(&mut underlying_assets, underlying_token_address); + vector::push_back(&mut underlying_asset_decimals, decimals); + vector::push_back(&mut treasuries, collector_address); + vector::push_back( + &mut atokens_names, string_utils::format1(&b"APTOS_A_TOKEN_{}", i) + ); + vector::push_back(&mut atokens_symbols, string_utils::format1(&b"A_{}", i)); + vector::push_back( + &mut var_tokens_names, string_utils::format1(&b"APTOS_VAR_TOKEN_{}", i) + ); + vector::push_back(&mut var_tokens_symbols, string_utils::format1(&b"V_{}", i)); + }; + + // create pool reserves + pool_configurator::init_reserves( + aave_pool, + underlying_assets, + underlying_asset_decimals, + treasuries, + atokens_names, + atokens_symbols, + var_tokens_names, + var_tokens_symbols, + ); + + // create reserve configurations + for (j in 0..num_assets) { + let reserve_config_new = reserve::init(); + let decimals = ( + *vector::borrow(&underlying_asset_decimals, (j as u64)) as u256 + ); + reserve::set_decimals(&mut reserve_config_new, decimals); + reserve::set_active(&mut reserve_config_new, true); + reserve::set_frozen(&mut reserve_config_new, false); + reserve::set_paused(&mut reserve_config_new, false); + reserve::set_flash_loan_enabled(&mut reserve_config_new, false); // NOTE: disable flashloan enabled + reserve::set_ltv(&mut reserve_config_new, 5000); // NOTE: set ltv + reserve::set_debt_ceiling(&mut reserve_config_new, 0); // NOTE: set no debt ceiling + reserve::set_borrowable_in_isolation(&mut reserve_config_new, false); // NOTE: set no borrowable in isolation + reserve::set_siloed_borrowing(&mut reserve_config_new, false); // NOTE: set no sillowed borrowing + reserve::set_borrowing_enabled(&mut reserve_config_new, true); // NOTE: set borrowing enabled + test_set_reserve_configuration( + *vector::borrow(&underlying_assets, (j as u64)), reserve_config_new + ); + }; + + // get one underlying asset data + let underlying_token_address = *vector::borrow(&underlying_assets, 0); + + // set underlying emode category + pool_configurator::set_asset_emode_category( + aave_pool, underlying_token_address, emode_cat_id + ); + + // get the reserve config for it + let reserve_data = get_reserve_data(underlying_token_address); + + // init user config for reserve index + create_user_config_for_reserve( + signer::address_of(supply_user), + (get_reserve_id(&reserve_data) as u256), + option::some(true), + option::some(false), // NOTE: not using any as collateral already + ); + + // =============== MINT UNDERLYING FOR USER ================= // + // mint 100 underlying tokens for the user + let mint_receiver_address = signer::address_of(supply_user); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + mint_receiver_address, + 100, + underlying_token_address, + ); + let initial_user_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + // assert user balance of underlying + assert!(initial_user_balance == 100, TEST_SUCCESS); + // asser underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + + // =============== USER SUPPLY ================= // + // user supplies the underlying token + let supply_receiver_address = signer::address_of(supply_user); + let supplied_amount: u64 = 50; + supply_logic::supply( + supply_user, + underlying_token_address, + (supplied_amount as u256), + supply_receiver_address, + 0, + ); + + // > check emitted events + let emitted_supply_events = emitted_events(); + assert!(vector::length(&emitted_supply_events) == 1, TEST_SUCCESS); + let emitted_reserve_used_as_collateral_events = + emitted_events(); + assert!( + vector::length(&emitted_reserve_used_as_collateral_events) == 1, TEST_SUCCESS + ); + // > check supplier balance of underlying + let supplier_balance = + mock_underlying_token_factory::balance_of( + mint_receiver_address, underlying_token_address + ); + assert!(supplier_balance == initial_user_balance - supplied_amount, TEST_SUCCESS); + // > check underlying supply + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); + // > check a_token balance of underlying + let a_token_address = + a_token_factory::token_address( + signer::address_of(aave_pool), + *vector::borrow(&atokens_symbols, 0), + ); + let atoken_account_address = + a_token_factory::get_token_account_address(a_token_address); + let atoken_acocunt_balance = + mock_underlying_token_factory::balance_of( + atoken_account_address, underlying_token_address + ); + assert!(atoken_acocunt_balance == supplied_amount, TEST_SUCCESS); + // > check user a_token balance after supply + let supplied_amount_scaled = + wad_ray_math::ray_div( + (supplied_amount as u256), + (get_reserve_liquidity_index(&reserve_data) as u256), + ); + let supplier_a_token_balance = + a_token_factory::scaled_balance_of( + signer::address_of(supply_user), a_token_address + ); + assert!(supplier_a_token_balance == supplied_amount_scaled, TEST_SUCCESS); + } } diff --git a/aave-core/tests/aave-tokens/a_token_factory_tests.move b/aave-core/tests/aave-tokens/a_token_factory_tests.move index d34039b..f4adf32 100644 --- a/aave-core/tests/aave-tokens/a_token_factory_tests.move +++ b/aave-core/tests/aave-tokens/a_token_factory_tests.move @@ -1,7 +1,6 @@ #[test_only] module aave_pool::a_token_factory_tests { use std::features::change_feature_flags_for_testing; - use std::option::Self; use std::signer; use std::string; use std::string::utf8; @@ -16,9 +15,9 @@ module aave_pool::a_token_factory_tests { use aave_math::wad_ray_math; use aave_pool::a_token_factory::Self; + use aave_pool::mock_underlying_token_factory::Self; use aave_pool::token_base; use aave_pool::token_base::{Burn, Mint, Transfer}; - use aave_pool::underlying_token_factory::Self; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; @@ -48,40 +47,58 @@ module aave_pool::a_token_factory_tests { let decimals = 3; let underlying_asset_address = @0x033; let treasury_address = @0x034; - a_token_factory::create_token(a_tokens_admin, + a_token_factory::create_token( + a_tokens_admin, name, symbol, decimals, utf8(b""), utf8(b""), underlying_asset_address, - treasury_address,); + treasury_address, + ); // check emitted events let emitted_events = emitted_events(); // make sure event of type was emitted assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); - let a_token_address = a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); - let a_token_metadata = a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin), symbol); + let a_token_address = + a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); + let a_token_metadata = + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ); let seed = *string::bytes(&symbol); let resource_account = account::create_resource_address(&signer::address_of(a_tokens_admin), seed); - assert!(object::address_to_object(a_token_address) == a_token_metadata, - TEST_SUCCESS); + assert!( + object::address_to_object(a_token_address) == a_token_metadata, + TEST_SUCCESS, + ); assert!(a_token_factory::get_revision() == 1, TEST_SUCCESS); - assert!(a_token_factory::supply(a_token_address) == 0, TEST_SUCCESS); assert!(a_token_factory::decimals(a_token_address) == decimals, TEST_SUCCESS); assert!(a_token_factory::symbol(a_token_address) == symbol, TEST_SUCCESS); assert!(a_token_factory::name(a_token_address) == name, TEST_SUCCESS); - assert!(a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin), symbol) == a_token_metadata, - TEST_SUCCESS); - assert!(a_token_factory::get_underlying_asset_address(a_token_address) - == underlying_asset_address, - TEST_SUCCESS); - assert!(a_token_factory::get_reserve_treasury_address(a_token_address) == treasury_address, - TEST_SUCCESS); - assert!(a_token_factory::get_token_account_address(a_token_address) == resource_account, - TEST_SUCCESS); + assert!( + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ) == a_token_metadata, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_underlying_asset_address(a_token_address) + == underlying_asset_address, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_reserve_treasury_address(a_token_address) + == treasury_address, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_token_account_address(a_token_address) == resource_account, + TEST_SUCCESS, + ); } #[test(aave_pool = @aave_pool, a_tokens_admin = @a_tokens, aave_std = @std, aptos_framework = @0x1, token_receiver = @0x42, caller = @0x41, underlying_tokens_admin = @underlying_tokens)] @@ -104,30 +121,37 @@ module aave_pool::a_token_factory_tests { account::create_account_for_test(signer::address_of(a_tokens_admin)); // init token base - underlying_token_factory::test_init_module(aave_pool); + mock_underlying_token_factory::test_init_module(aave_pool); token_base::test_init_module(aave_pool); let name = utf8(b"TOKEN_1"); let symbol = utf8(b"T1"); let decimals = 3; let max_supply = 10000; - underlying_token_factory::create_token(underlying_tokens_admin, + mock_underlying_token_factory::create_token( + underlying_tokens_admin, max_supply, name, symbol, decimals, utf8(b""), - utf8(b""),); - let underlying_asset_address = underlying_token_factory::token_address(symbol); + utf8(b""), + ); + let underlying_asset_address = + mock_underlying_token_factory::token_address(symbol); let amount_to_mint: u256 = 100; let seed = *string::bytes(&utf8(b"A2")); let resource_account = account::create_resource_address(&signer::address_of(a_tokens_admin), seed); // mint resource_account - underlying_token_factory::mint(underlying_tokens_admin, resource_account, + mock_underlying_token_factory::mint( + underlying_tokens_admin, + resource_account, // a_token_factory::get_token_account_address(a_token_address), - (amount_to_mint as u64), underlying_asset_address); + (amount_to_mint as u64), + underlying_asset_address, + ); // create a_tokens let name = utf8(b"TEST_A_TOKEN_2"); @@ -135,58 +159,79 @@ module aave_pool::a_token_factory_tests { let decimals = 3; let treasury_address = @0x034; - a_token_factory::create_token(a_tokens_admin, + a_token_factory::create_token( + a_tokens_admin, name, symbol, decimals, utf8(b""), utf8(b""), underlying_asset_address, - treasury_address,); + treasury_address, + ); // check emitted events let emitted_events = emitted_events(); // make sure event of type was emitted assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); - let a_token_address = a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); - let a_token_metadata = a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin), symbol); + let a_token_address = + a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); + let a_token_metadata = + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ); let seed = *string::bytes(&symbol); let resource_account = account::create_resource_address(&signer::address_of(a_tokens_admin), seed); - assert!(a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin), symbol) == a_token_metadata, - TEST_SUCCESS); - assert!(a_token_factory::get_underlying_asset_address(a_token_address) - == underlying_asset_address, - TEST_SUCCESS); - assert!(a_token_factory::get_reserve_treasury_address(a_token_address) == treasury_address, - TEST_SUCCESS); - assert!(a_token_factory::get_token_account_address(a_token_address) == resource_account, - TEST_SUCCESS); + assert!( + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ) == a_token_metadata, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_underlying_asset_address(a_token_address) + == underlying_asset_address, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_reserve_treasury_address(a_token_address) + == treasury_address, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_token_account_address(a_token_address) == resource_account, + TEST_SUCCESS, + ); // ============= MINT ATOKENS ============== // let amount_to_mint: u256 = 100; let reserve_index: u256 = 1; - a_token_factory::mint(signer::address_of(caller), + a_token_factory::mint( + signer::address_of(caller), signer::address_of(token_receiver), amount_to_mint, reserve_index, - a_token_address); + a_token_address, + ); + + // get atoken scaled amount + let atoken_amount_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); // assert a token supply - assert!(a_token_factory::supply(a_token_address) == amount_to_mint, TEST_SUCCESS); - assert!(a_token_factory::maximum(a_token_address) - == option::none(), TEST_SUCCESS); + assert!( + a_token_factory::scaled_total_supply(a_token_address) == atoken_amount_scaled, + TEST_SUCCESS, + ); // assert a_tokens receiver balance - let atoken_amount_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); - assert!(a_token_factory::scale_balance_of(signer::address_of(token_receiver), - a_token_address) - == atoken_amount_scaled, - TEST_SUCCESS); - assert!(a_token_factory::balance_of(signer::address_of(token_receiver), - a_token_address) == amount_to_mint, - TEST_SUCCESS); + assert!( + a_token_factory::scaled_balance_of( + signer::address_of(token_receiver), a_token_address + ) == atoken_amount_scaled, + TEST_SUCCESS, + ); // check emitted events let emitted_transfer_events = emitted_events(); @@ -197,28 +242,33 @@ module aave_pool::a_token_factory_tests { // ============= BURN ATOKENS ============== // // now burn the atokens let amount_to_burn = amount_to_mint / 2; - a_token_factory::burn(signer::address_of(token_receiver), + + // burn + a_token_factory::burn( + signer::address_of(token_receiver), signer::address_of(token_receiver), amount_to_burn, reserve_index, - a_token_address); + a_token_address, + ); + + let remaining_amount = amount_to_mint - amount_to_burn; + let remaining_amount_scaled = + wad_ray_math::ray_div(remaining_amount, reserve_index); // assert a token supply - assert!(a_token_factory::supply(a_token_address) - == amount_to_mint - amount_to_burn, TEST_SUCCESS); - assert!(a_token_factory::maximum(a_token_address) - == option::none(), TEST_SUCCESS); + assert!( + a_token_factory::scaled_total_supply(a_token_address) == remaining_amount_scaled, + TEST_SUCCESS, + ); // assert a_tokens receiver balance - let atoken_amount_scaled = wad_ray_math::ray_div(amount_to_burn, reserve_index); - assert!(a_token_factory::balance_of(signer::address_of(token_receiver), - a_token_address) - == (amount_to_mint - amount_to_burn), - TEST_SUCCESS); - assert!(a_token_factory::scale_balance_of(signer::address_of(token_receiver), - a_token_address) - == atoken_amount_scaled, - TEST_SUCCESS); + assert!( + a_token_factory::scaled_balance_of( + signer::address_of(token_receiver), a_token_address + ) == remaining_amount_scaled, + TEST_SUCCESS, + ); // check emitted events let emitted_transfer_events = emitted_events(); @@ -229,23 +279,32 @@ module aave_pool::a_token_factory_tests { // ============= TRANSFER ATOKENS ============== // let transfer_receiver = @0x45; let transfer_amount: u256 = 20; + let transfer_receiver_amount_scaled = + wad_ray_math::ray_div(transfer_amount, reserve_index); // assert transfer receiver - a_token_factory::transfer_on_liquidation(signer::address_of(token_receiver), + a_token_factory::transfer_on_liquidation( + signer::address_of(token_receiver), transfer_receiver, 20, reserve_index, - a_token_address); - assert!(a_token_factory::balance_of(transfer_receiver, a_token_address) == transfer_amount, - TEST_SUCCESS); + a_token_address, + ); + assert!( + a_token_factory::scaled_balance_of(transfer_receiver, a_token_address) + == transfer_receiver_amount_scaled, + TEST_SUCCESS, + ); // assert token sender let transfer_sender_scaled_balance = wad_ray_math::ray_div(amount_to_burn - transfer_amount, reserve_index); - assert!(a_token_factory::scale_balance_of(signer::address_of(token_receiver), - a_token_address) - == transfer_sender_scaled_balance, - TEST_SUCCESS); + assert!( + a_token_factory::scaled_balance_of( + signer::address_of(token_receiver), a_token_address + ) == transfer_sender_scaled_balance, + TEST_SUCCESS, + ); // check emitted events let emitted_transfer_events = emitted_events(); @@ -279,57 +338,87 @@ module aave_pool::a_token_factory_tests { let decimals = 3; let underlying_asset_address = @0x033; let treasury_address = @0x034; - a_token_factory::create_token(a_tokens_admin, + a_token_factory::create_token( + a_tokens_admin, name, symbol, decimals, utf8(b""), utf8(b""), underlying_asset_address, - treasury_address,); + treasury_address, + ); + // check emitted events let emitted_events = emitted_events(); + // make sure event of type was emitted assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); - let a_token_metadata = a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin),symbol); - let a_token_address = a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); + + // check addresses + let a_token_metadata = + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ); + let a_token_address = + a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); let seed = *string::bytes(&symbol); let resource_account = account::create_resource_address(&signer::address_of(a_tokens_admin), seed); - assert!(a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin), symbol) == a_token_metadata, - TEST_SUCCESS); - assert!(a_token_factory::get_underlying_asset_address(a_token_address) - == underlying_asset_address, - TEST_SUCCESS); - assert!(a_token_factory::get_reserve_treasury_address(a_token_address) == treasury_address, - TEST_SUCCESS); - assert!(a_token_factory::get_token_account_address(a_token_address) == resource_account, - TEST_SUCCESS); + assert!( + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ) == a_token_metadata, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_underlying_asset_address(a_token_address) + == underlying_asset_address, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_reserve_treasury_address(a_token_address) + == treasury_address, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_token_account_address(a_token_address) == resource_account, + TEST_SUCCESS, + ); // ============= MINT ATOKENS ============== // let amount_to_mint: u256 = 100; let reserve_index: u256 = 1; - a_token_factory::mint(signer::address_of(caller), + let amount_to_mint_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); + + a_token_factory::mint( + signer::address_of(caller), signer::address_of(token_receiver), amount_to_mint, reserve_index, - a_token_address); + a_token_address, + ); // assert a token supply - assert!(a_token_factory::supply(a_token_address) == amount_to_mint, TEST_SUCCESS); - assert!(a_token_factory::maximum(a_token_address) - == option::none(), TEST_SUCCESS); + assert!( + a_token_factory::scaled_total_supply(a_token_address) == amount_to_mint_scaled, + TEST_SUCCESS, + ); // assert a_tokens receiver balance - let atoken_amount_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); - assert!(a_token_factory::scale_balance_of(signer::address_of(token_receiver), - a_token_address) - == atoken_amount_scaled, - TEST_SUCCESS); - assert!(a_token_factory::balance_of(signer::address_of(token_receiver), - a_token_address) == amount_to_mint, - TEST_SUCCESS); + assert!( + a_token_factory::scaled_balance_of( + signer::address_of(token_receiver), a_token_address + ) == amount_to_mint_scaled, + TEST_SUCCESS, + ); + assert!( + a_token_factory::scaled_balance_of( + signer::address_of(token_receiver), a_token_address + ) == amount_to_mint_scaled, + TEST_SUCCESS, + ); // check emitted events let emitted_transfer_events = emitted_events(); @@ -340,23 +429,31 @@ module aave_pool::a_token_factory_tests { // ============= TRANSFER ATOKENS ON LIQUIDATION ============== // let transfer_receiver = @0x45; let transfer_amount: u256 = 20; - + let transfer_receiver_amount_scaled = + wad_ray_math::ray_div(transfer_amount, reserve_index); // assert transfer receiver - a_token_factory::transfer_on_liquidation(signer::address_of(token_receiver), + a_token_factory::transfer_on_liquidation( + signer::address_of(token_receiver), transfer_receiver, 20, 1, - a_token_address); - assert!(a_token_factory::balance_of(transfer_receiver, a_token_address) == transfer_amount, - TEST_SUCCESS); + a_token_address, + ); + assert!( + a_token_factory::scaled_balance_of(transfer_receiver, a_token_address) + == transfer_receiver_amount_scaled, + TEST_SUCCESS, + ); // assert token sender let transfer_sender_scaled_balance = wad_ray_math::ray_div(amount_to_mint - transfer_amount, reserve_index); - assert!(a_token_factory::scale_balance_of(signer::address_of(token_receiver), - a_token_address) - == transfer_sender_scaled_balance, - TEST_SUCCESS); + assert!( + a_token_factory::scaled_balance_of( + signer::address_of(token_receiver), a_token_address + ) == transfer_sender_scaled_balance, + TEST_SUCCESS, + ); // check emitted events let emitted_transfer_events = emitted_events(); @@ -388,31 +485,49 @@ module aave_pool::a_token_factory_tests { let decimals = 3; let underlying_asset_address = @0x033; let treasury_address = @0x034; - a_token_factory::create_token(a_tokens_admin, + a_token_factory::create_token( + a_tokens_admin, name, symbol, decimals, utf8(b""), utf8(b""), underlying_asset_address, - treasury_address,); + treasury_address, + ); + // check emitted events let emitted_events = emitted_events(); + // make sure event of type was emitted assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); - let a_token_address = a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); - let _a_token_metadata = a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin), symbol); + let a_token_address = + a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); + let _a_token_metadata = + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ); // ============= MINT TO TREASURY ============== // let amount_to_mint: u256 = 100; let reserve_index: u256 = 1; + let amount_to_mint_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); + + // mint to treasury a_token_factory::mint_to_treasury(amount_to_mint, reserve_index, a_token_address); - assert!(a_token_factory::balance_of(treasury_address, a_token_address) == amount_to_mint, - TEST_SUCCESS); - let treasury_scaled_balance = wad_ray_math::ray_div(amount_to_mint, reserve_index); - assert!(a_token_factory::scale_balance_of(treasury_address, a_token_address) - == treasury_scaled_balance, - TEST_SUCCESS); + + // check balances + assert!( + a_token_factory::scaled_balance_of(treasury_address, a_token_address) + == amount_to_mint_scaled, + TEST_SUCCESS, + ); + + assert!( + a_token_factory::scaled_balance_of(treasury_address, a_token_address) + == amount_to_mint_scaled, + TEST_SUCCESS, + ); } #[test(aave_pool = @aave_pool, a_tokens_admin = @a_tokens, aave_std = @std, aptos_framework = @0x1, underlying_tokens_admin = @underlying_tokens,)] @@ -433,22 +548,24 @@ module aave_pool::a_token_factory_tests { account::create_account_for_test(signer::address_of(a_tokens_admin)); // init underlying tokens - underlying_token_factory::test_init_module(aave_pool); + mock_underlying_token_factory::test_init_module(aave_pool); // create underlying token let underlying_token_name = utf8(b"TOKEN_5"); let underlying_token_symbol = utf8(b"T5"); let underlying_token_decimals = 3; let underlying_token_max_supply = 10000; - underlying_token_factory::create_token(underlying_tokens_admin, + mock_underlying_token_factory::create_token( + underlying_tokens_admin, underlying_token_max_supply, underlying_token_name, underlying_token_symbol, underlying_token_decimals, utf8(b""), - utf8(b""),); - let underlying_token_address = underlying_token_factory::token_address( - underlying_token_symbol); + utf8(b""), + ); + let underlying_token_address = + mock_underlying_token_factory::token_address(underlying_token_symbol); // init token base token_base::test_init_module(aave_pool); @@ -458,56 +575,76 @@ module aave_pool::a_token_factory_tests { let symbol = utf8(b"A6"); let decimals = 3; let treasury_address = @0x034; - a_token_factory::create_token(a_tokens_admin, + a_token_factory::create_token( + a_tokens_admin, name, symbol, decimals, utf8(b""), utf8(b""), underlying_token_address, - treasury_address,); + treasury_address, + ); + // check emitted events let emitted_events = emitted_events(); + // make sure event of type was emitted assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); - let a_token_address = a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); - let _a_token_metadata = a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin), symbol); + let a_token_address = + a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); + let _a_token_metadata = + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ); // =============== MINT UNDERLYING FOR ACCOUNT ================= // // mint 100 underlying tokens for some address let underlying_amount: u256 = 100; - underlying_token_factory::mint(underlying_tokens_admin, + mock_underlying_token_factory::mint( + underlying_tokens_admin, a_token_factory::get_token_account_address(a_token_address), (underlying_amount as u64), - underlying_token_address); + underlying_token_address, + ); // ============= TRANSFER THE UNDERLYING TIED TO THE ATOKENS ACCOUNT TO ANOTHER ACCOUNT ============== // let underlying_receiver_address = @0x7; let transfer_amount: u256 = 40; - a_token_factory::transfer_underlying_to(underlying_receiver_address, transfer_amount, - a_token_address); + a_token_factory::transfer_underlying_to( + underlying_receiver_address, transfer_amount, a_token_address + ); + // check the receiver balance assert!( - (underlying_token_factory::balance_of(underlying_receiver_address, - underlying_token_address) as u256) == transfer_amount, - TEST_SUCCESS); + ( + mock_underlying_token_factory::balance_of( + underlying_receiver_address, underlying_token_address + ) as u256 + ) == transfer_amount, + TEST_SUCCESS, + ); + // check the underlying account assert!( - (underlying_token_factory::balance_of(a_token_factory::get_token_account_address( - a_token_address), underlying_token_address) as u256) - == underlying_amount - transfer_amount, - TEST_SUCCESS); + ( + mock_underlying_token_factory::balance_of( + a_token_factory::get_token_account_address(a_token_address), + underlying_token_address, + ) as u256 + ) == underlying_amount - transfer_amount, + TEST_SUCCESS, + ); } - #[test(aave_pool = @aave_pool, a_tokens_admin = @a_tokens, aave_role_super_admin = @aave_acl, aave_std = @std, aptos_framework = @0x1, pool = @aave_pool, token_receiver = @0x42, caller = @0x41,)] + #[test(aave_pool = @aave_pool, a_tokens_admin = @a_tokens, aave_role_super_admin = @aave_acl, aave_std = @std, aptos_framework = @0x1, rescue_receiver = @0x42, caller = @0x41,)] fun test_atoken_rescue( aave_pool: &signer, a_tokens_admin: &signer, aave_role_super_admin: &signer, aave_std: &signer, aptos_framework: &signer, - pool: &signer, - token_receiver: &signer, + rescue_receiver: &signer, caller: &signer, ) { // start the timer @@ -519,91 +656,103 @@ module aave_pool::a_token_factory_tests { // create a tokens admin account account::create_account_for_test(signer::address_of(a_tokens_admin)); + // init the acl module and make aave_pool the asset listing/pool admin + test_init_module(aave_role_super_admin); + acl_manage::add_asset_listing_admin( + aave_role_super_admin, signer::address_of(aave_pool) + ); + acl_manage::add_pool_admin(aave_role_super_admin, signer::address_of(aave_pool)); + // init token base token_base::test_init_module(aave_pool); // create a_tokens - let name = utf8(b"TEST_A_TOKEN_7"); - let symbol = utf8(b"A7"); + let name = utf8(b"TEST_A_TOKEN"); + let symbol = utf8(b"A"); let decimals = 3; - let underlying_asset_address = @0x033; let treasury_address = @0x034; - a_token_factory::create_token(a_tokens_admin, + let underlying_asset_address = @0x033; + a_token_factory::create_token( + a_tokens_admin, name, symbol, decimals, utf8(b""), utf8(b""), underlying_asset_address, - treasury_address,); + treasury_address, + ); + // check emitted events let emitted_events = emitted_events(); + // make sure event of type was emitted assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); - let a_token_address = a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); - let a_token_metadata = a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin), symbol); + let a_token_address = + a_token_factory::token_address(signer::address_of(a_tokens_admin), symbol); + let a_token_metadata = + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ); let seed = *string::bytes(&symbol); let resource_account = account::create_resource_address(&signer::address_of(a_tokens_admin), seed); - assert!(a_token_factory::get_metadata_by_symbol(signer::address_of(a_tokens_admin), symbol) == a_token_metadata, - TEST_SUCCESS); - assert!(a_token_factory::get_underlying_asset_address(a_token_address) - == underlying_asset_address, - TEST_SUCCESS); - assert!(a_token_factory::get_reserve_treasury_address(a_token_address) == treasury_address, - TEST_SUCCESS); - assert!(a_token_factory::get_token_account_address(a_token_address) == resource_account, - TEST_SUCCESS); - - // ============= SET ACL POOL ADMIN ============== // - // init the acl module and make aave_pool the asset listing/pool admin - test_init_module(aave_role_super_admin); - acl_manage::add_asset_listing_admin(aave_role_super_admin, signer::address_of(pool)); - acl_manage::add_pool_admin(aave_role_super_admin, signer::address_of(pool)); + // check addresses + assert!( + a_token_factory::get_metadata_by_symbol( + signer::address_of(a_tokens_admin), symbol + ) == a_token_metadata, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_underlying_asset_address(a_token_address) + == underlying_asset_address, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_reserve_treasury_address(a_token_address) + == treasury_address, + TEST_SUCCESS, + ); + assert!( + a_token_factory::get_token_account_address(a_token_address) == resource_account, + TEST_SUCCESS, + ); - // ============= MINT ATOKENS ============== // + // ============= RESCUE TRANSFER ATOKENS ============== // let amount_to_mint: u256 = 100; let reserve_index: u256 = 1; - a_token_factory::mint(signer::address_of(caller), - signer::address_of(token_receiver), - amount_to_mint, - reserve_index, - a_token_address); + let _amount_to_mint_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); - // assert a token supply - assert!(a_token_factory::supply(a_token_address) == amount_to_mint, TEST_SUCCESS); - assert!(a_token_factory::maximum(a_token_address) - == option::none(), TEST_SUCCESS); + let rescue_amount: u256 = 20; + let _rescue_amount_scaled = wad_ray_math::ray_div(rescue_amount, reserve_index); - // assert a_tokens receiver balance - let atoken_amount_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); - assert!(a_token_factory::scale_balance_of(signer::address_of(token_receiver), - a_token_address) - == atoken_amount_scaled, - TEST_SUCCESS); - assert!(a_token_factory::balance_of(signer::address_of(token_receiver), - a_token_address) == amount_to_mint, - TEST_SUCCESS); + // mint some tokens to the pool + a_token_factory::mint( + signer::address_of(caller), + signer::address_of(aave_pool), + amount_to_mint, + reserve_index, + a_token_address, + ); - // check emitted events + // check events let emitted_transfer_events = emitted_events(); assert!(vector::length(&emitted_transfer_events) == 1, TEST_SUCCESS); let emitted_mint_events = emitted_events(); assert!(vector::length(&emitted_mint_events) == 1, TEST_SUCCESS); - // ============= RESCUE TRANSFER ATOKENS ============== // - let rescue_transfer_receiver = @0x45; - let transfer_amount: u256 = 20; - - a_token_factory::mint(signer::address_of(caller), - signer::address_of(pool), - amount_to_mint, - reserve_index, - a_token_address); - // assert rescue transfer - a_token_factory::rescue_tokens(pool, a_token_address, rescue_transfer_receiver, 20,); - assert!(a_token_factory::balance_of(rescue_transfer_receiver, a_token_address) == transfer_amount, - TEST_SUCCESS); + // do rescue transfer. Singer is pool admin = aave_pool + a_token_factory::rescue_tokens( + aave_pool, + a_token_address, + signer::address_of(rescue_receiver), + rescue_amount, + ); + + // assert rescue receiver balance + // assert!(a_token_factory::scaled_balance_of(signer::address_of(rescue_receiver), a_token_address) == rescue_amount_scaled, + // TEST_SUCCESS); } } diff --git a/aave-core/tests/aave-tokens/standard_token_tests.move b/aave-core/tests/aave-tokens/standard_token_tests.move index e953493..325c51d 100644 --- a/aave-core/tests/aave-tokens/standard_token_tests.move +++ b/aave-core/tests/aave-tokens/standard_token_tests.move @@ -21,7 +21,8 @@ module aave_pool::standard_token_tests { fun create_test_mfa(creator: &signer): Object { let test_symbol = b"TEST"; - initialize(creator, + initialize( + creator, 0, utf8(b"Test Token"), /* name */ utf8(test_symbol), /* symbol */ @@ -30,9 +31,10 @@ module aave_pool::standard_token_tests { utf8(b"http://example.com"), /* project */ vector[true, true, true], @0x123, - false,); - let metadata_address = object::create_object_address(&signer::address_of(creator), - test_symbol); + false, + ); + let metadata_address = + object::create_object_address(&signer::address_of(creator), test_symbol); object::address_to_object(metadata_address) } @@ -42,49 +44,83 @@ module aave_pool::standard_token_tests { let creator_address = signer::address_of(creator); let aaron_address = @0x111; - mint_to_primary_stores(creator, + mint_to_primary_stores( + creator, metadata, vector[creator_address, aaron_address], - vector[100, 50]); - assert!(primary_fungible_store::balance(creator_address, metadata) == 100, - TEST_SUCCESS); - assert!(primary_fungible_store::balance(aaron_address, metadata) == 50, TEST_SUCCESS); + vector[100, 50], + ); + assert!( + primary_fungible_store::balance(creator_address, metadata) == 100, TEST_SUCCESS + ); + assert!( + primary_fungible_store::balance(aaron_address, metadata) == 50, TEST_SUCCESS + ); - set_primary_stores_frozen_status(creator, metadata, vector[creator_address, aaron_address], true); - assert!(primary_fungible_store::is_frozen(creator_address, metadata), TEST_SUCCESS); + set_primary_stores_frozen_status( + creator, + metadata, + vector[creator_address, aaron_address], + true, + ); + assert!( + primary_fungible_store::is_frozen(creator_address, metadata), TEST_SUCCESS + ); assert!(primary_fungible_store::is_frozen(aaron_address, metadata), TEST_SUCCESS); - transfer_between_primary_stores(creator, + transfer_between_primary_stores( + creator, metadata, vector[creator_address, aaron_address], vector[aaron_address, creator_address], - vector[10, 5]); - assert!(primary_fungible_store::balance(creator_address, metadata) == 95, - TEST_SUCCESS); - assert!(primary_fungible_store::balance(aaron_address, metadata) == 55, TEST_SUCCESS); + vector[10, 5], + ); + assert!( + primary_fungible_store::balance(creator_address, metadata) == 95, TEST_SUCCESS + ); + assert!( + primary_fungible_store::balance(aaron_address, metadata) == 55, TEST_SUCCESS + ); - set_primary_stores_frozen_status(creator, metadata, vector[creator_address, aaron_address], - false); - assert!(!primary_fungible_store::is_frozen(creator_address, metadata), TEST_SUCCESS); + set_primary_stores_frozen_status( + creator, + metadata, + vector[creator_address, aaron_address], + false, + ); + assert!( + !primary_fungible_store::is_frozen(creator_address, metadata), TEST_SUCCESS + ); assert!(!primary_fungible_store::is_frozen(aaron_address, metadata), TEST_SUCCESS); let fa = - withdraw_from_primary_stores(creator, + withdraw_from_primary_stores( + creator, metadata, vector[creator_address, aaron_address], - vector[25, 15]); + vector[25, 15], + ); assert!(fungible_asset::amount(&fa) == 40, TEST_SUCCESS); - deposit_to_primary_stores(creator, &mut fa, vector[creator_address, aaron_address], - vector[30, 10]); + deposit_to_primary_stores( + creator, + &mut fa, + vector[creator_address, aaron_address], + vector[30, 10], + ); fungible_asset::destroy_zero(fa); - burn_from_primary_stores(creator, + burn_from_primary_stores( + creator, metadata, vector[creator_address, aaron_address], - vector[100, 50]); - assert!(primary_fungible_store::balance(creator_address, metadata) == 0, - TEST_SUCCESS); - assert!(primary_fungible_store::balance(aaron_address, metadata) == 0, TEST_SUCCESS); + vector[100, 50], + ); + assert!( + primary_fungible_store::balance(creator_address, metadata) == 0, TEST_SUCCESS + ); + assert!( + primary_fungible_store::balance(aaron_address, metadata) == 0, TEST_SUCCESS + ); } #[test(creator = @aave_pool, aaron = @0x111)] diff --git a/aave-core/tests/aave-tokens/underlying_token_factory_tests.move b/aave-core/tests/aave-tokens/underlying_token_factory_tests.move index 5d481ca..cd005d0 100644 --- a/aave-core/tests/aave-tokens/underlying_token_factory_tests.move +++ b/aave-core/tests/aave-tokens/underlying_token_factory_tests.move @@ -6,7 +6,7 @@ module aave_pool::underlying_token_factory_tests { use std::string::utf8; use aptos_framework::fungible_asset::Metadata; use aptos_framework::object::Self; - use aave_pool::underlying_token_factory::Self; + use aave_pool::mock_underlying_token_factory::Self; const TEST_SUCCESS: u64 = 1; const TEST_FAILED: u64 = 2; @@ -19,32 +19,58 @@ module aave_pool::underlying_token_factory_tests { change_feature_flags_for_testing(aave_std, vector[26], vector[]); // init underlying tokens - underlying_token_factory::test_init_module(aave_pool); + mock_underlying_token_factory::test_init_module(aave_pool); // create underlying tokens let name = utf8(b"TOKEN_1"); let symbol = utf8(b"T1"); let decimals = 3; let max_supply = 10000; - underlying_token_factory::create_token(underlying_tokens_admin, + mock_underlying_token_factory::create_token( + underlying_tokens_admin, max_supply, name, symbol, decimals, utf8(b""), - utf8(b""),); - let underlying_token_metadata = underlying_token_factory::get_metadata_by_symbol(symbol); - let underlying_token_address = underlying_token_factory::token_address(symbol); - assert!(object::address_to_object(underlying_token_address) - == underlying_token_metadata, - TEST_SUCCESS); - assert!(underlying_token_factory::get_token_account_address() - == signer::address_of(underlying_tokens_admin), TEST_SUCCESS); - assert!(underlying_token_factory::supply(underlying_token_address) == option::some(0), TEST_SUCCESS); - assert!(underlying_token_factory::decimals(underlying_token_address) == decimals, TEST_SUCCESS); - assert!(underlying_token_factory::maximum(underlying_token_address) == option::some(max_supply), TEST_SUCCESS); - assert!(underlying_token_factory::symbol(underlying_token_address) == symbol, TEST_SUCCESS); - assert!(underlying_token_factory::name(underlying_token_address) == name, TEST_SUCCESS); + utf8(b""), + ); + let underlying_token_metadata = + mock_underlying_token_factory::get_metadata_by_symbol(symbol); + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); + assert!( + object::address_to_object(underlying_token_address) + == underlying_token_metadata, + TEST_SUCCESS, + ); + assert!( + mock_underlying_token_factory::get_token_account_address() + == signer::address_of(underlying_tokens_admin), + TEST_SUCCESS, + ); + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(0), + TEST_SUCCESS, + ); + assert!( + mock_underlying_token_factory::decimals(underlying_token_address) == decimals, + TEST_SUCCESS, + ); + assert!( + mock_underlying_token_factory::maximum(underlying_token_address) + == option::some(max_supply), + TEST_SUCCESS, + ); + assert!( + mock_underlying_token_factory::symbol(underlying_token_address) == symbol, + TEST_SUCCESS, + ); + assert!( + mock_underlying_token_factory::name(underlying_token_address) == name, + TEST_SUCCESS, + ); } #[test(aave_pool = @aave_pool, underlying_tokens_admin = @underlying_tokens, aave_std = @std,)] @@ -55,33 +81,57 @@ module aave_pool::underlying_token_factory_tests { change_feature_flags_for_testing(aave_std, vector[26], vector[]); // init underlying tokens - underlying_token_factory::test_init_module(aave_pool); + mock_underlying_token_factory::test_init_module(aave_pool); // create underlying tokens let name = utf8(b"TOKEN_1"); let symbol = utf8(b"T1"); let decimals = 3; let max_supply = 10000; - underlying_token_factory::create_token(underlying_tokens_admin, + mock_underlying_token_factory::create_token( + underlying_tokens_admin, max_supply, name, symbol, decimals, utf8(b""), - utf8(b""),); - let underlying_token_address = underlying_token_factory::token_address(symbol); + utf8(b""), + ); + let underlying_token_address = + mock_underlying_token_factory::token_address(symbol); let receiver_address = @0x42; // mint 100 tokens - underlying_token_factory::mint(underlying_tokens_admin, receiver_address, 100, underlying_token_address); - let user_balance = underlying_token_factory::balance_of(receiver_address, underlying_token_address); + mock_underlying_token_factory::mint( + underlying_tokens_admin, + receiver_address, + 100, + underlying_token_address, + ); + let user_balance = + mock_underlying_token_factory::balance_of( + receiver_address, underlying_token_address + ); assert!(user_balance == 100, TEST_SUCCESS); - assert!(underlying_token_factory::supply(underlying_token_address) == option::some(100), TEST_SUCCESS); + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(100), + TEST_SUCCESS, + ); // burn half of the tokens - underlying_token_factory::burn(receiver_address, 50, underlying_token_address); - let user_balance = underlying_token_factory::balance_of(receiver_address, underlying_token_address); + mock_underlying_token_factory::burn( + receiver_address, 50, underlying_token_address + ); + let user_balance = + mock_underlying_token_factory::balance_of( + receiver_address, underlying_token_address + ); assert!(user_balance == 50, TEST_SUCCESS); - assert!(underlying_token_factory::supply(underlying_token_address) == option::some(50), TEST_SUCCESS); + assert!( + mock_underlying_token_factory::supply(underlying_token_address) + == option::some(50), + TEST_SUCCESS, + ); } } diff --git a/aave-core/tests/aave-tokens/variable_token_factory_tests.move b/aave-core/tests/aave-tokens/variable_token_factory_tests.move index a006487..f851cb2 100644 --- a/aave-core/tests/aave-tokens/variable_token_factory_tests.move +++ b/aave-core/tests/aave-tokens/variable_token_factory_tests.move @@ -1,7 +1,6 @@ #[test_only] -module aave_pool::variable_token_factory_tests { +module aave_pool::variable_debt_token_factory_tests { use std::features::change_feature_flags_for_testing; - use std::option::Self; use std::signer::Self; use std::string::utf8; use std::vector::Self; @@ -9,10 +8,12 @@ module aave_pool::variable_token_factory_tests { use aptos_framework::fungible_asset::Metadata; use aptos_framework::object::Self; use aptos_framework::timestamp::set_time_has_started_for_testing; + use aave_math::wad_ray_math; + use aave_pool::token_base::Self; use aave_pool::token_base::{Burn, Mint, Transfer}; - use aave_pool::variable_token_factory::Self; + use aave_pool::variable_debt_token_factory::Self; use aave_acl::acl_manage::{Self}; const TEST_SUCCESS: u64 = 1; @@ -27,39 +28,57 @@ module aave_pool::variable_token_factory_tests { // set asset listing admin acl_manage::test_init_module(aave_acl); - acl_manage::add_asset_listing_admin(aave_acl, signer::address_of(variable_tokens_admin)); + acl_manage::add_asset_listing_admin( + aave_acl, signer::address_of(variable_tokens_admin) + ); // create variable tokens let name = utf8(b"TEST_VAR_TOKEN_1"); let symbol = utf8(b"VAR1"); let decimals = 3; - variable_token_factory::create_token(variable_tokens_admin, + variable_debt_token_factory::create_token( + variable_tokens_admin, name, symbol, decimals, utf8(b""), utf8(b""), @0x033, - ); + ); // check emitted events - let emitted_events = emitted_events(); + let emitted_events = emitted_events(); // make sure event of type was emitted assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); - let variable_token_address = variable_token_factory::token_address(signer::address_of(variable_tokens_admin), symbol); - let variable_token_metadata = variable_token_factory::asset_metadata(signer::address_of(variable_tokens_admin), symbol); - assert!(object::address_to_object(variable_token_address) - == variable_token_metadata, - TEST_SUCCESS); - assert!(variable_token_factory::get_revision() == 1, TEST_SUCCESS); - assert!(variable_token_factory::supply(variable_token_address) == 0, TEST_SUCCESS); - assert!(variable_token_factory::decimals(variable_token_address) == decimals, - TEST_SUCCESS); - assert!(variable_token_factory::maximum(variable_token_address) - == option::none(), - TEST_SUCCESS); - assert!(variable_token_factory::symbol(variable_token_address) == symbol, - TEST_SUCCESS); - assert!(variable_token_factory::name(variable_token_address) == name, TEST_SUCCESS); + let variable_token_address = + variable_debt_token_factory::token_address( + signer::address_of(variable_tokens_admin), symbol + ); + let variable_token_metadata = + variable_debt_token_factory::asset_metadata( + signer::address_of(variable_tokens_admin), symbol + ); + assert!( + object::address_to_object(variable_token_address) + == variable_token_metadata, + TEST_SUCCESS, + ); + assert!(variable_debt_token_factory::get_revision() == 1, TEST_SUCCESS); + assert!( + variable_debt_token_factory::scaled_total_supply(variable_token_address) == 0, + TEST_SUCCESS, + ); + assert!( + variable_debt_token_factory::decimals(variable_token_address) == decimals, + TEST_SUCCESS, + ); + assert!( + variable_debt_token_factory::symbol(variable_token_address) == symbol, + TEST_SUCCESS, + ); + assert!( + variable_debt_token_factory::name(variable_token_address) == name, + TEST_SUCCESS, + ); } #[test(aave_pool = @aave_pool, variable_tokens_admin = @variable_tokens, aave_acl = @aave_acl, aave_std = @std, aptos_framework = @0x1, token_receiver = @0x42, caller = @0x41,)] @@ -83,52 +102,65 @@ module aave_pool::variable_token_factory_tests { // set asset listing admin acl_manage::test_init_module(aave_acl); - acl_manage::add_asset_listing_admin(aave_acl, signer::address_of(variable_tokens_admin)); + acl_manage::add_asset_listing_admin( + aave_acl, signer::address_of(variable_tokens_admin) + ); // create var tokens let name = utf8(b"TEST_VAR_TOKEN_1"); let symbol = utf8(b"VAR1"); let decimals = 3; let underlying_asset_address = @0x033; - variable_token_factory::create_token(variable_tokens_admin, + variable_debt_token_factory::create_token( + variable_tokens_admin, name, symbol, decimals, utf8(b""), utf8(b""), underlying_asset_address, - ); + ); // check emitted events - let emitted_events = emitted_events(); + let emitted_events = emitted_events(); // make sure event of type was emitted assert!(vector::length(&emitted_events) == 1, TEST_SUCCESS); - let var_token_address = variable_token_factory::token_address(signer::address_of(variable_tokens_admin), symbol); - let _var_token_metadata = variable_token_factory::get_metadata_by_symbol(signer::address_of(variable_tokens_admin), symbol); + let var_token_address = + variable_debt_token_factory::token_address( + signer::address_of(variable_tokens_admin), symbol + ); + let _var_token_metadata = + variable_debt_token_factory::get_metadata_by_symbol( + signer::address_of(variable_tokens_admin), symbol + ); // ============= MINT ============== // let amount_to_mint: u256 = 100; let reserve_index: u256 = 1; - variable_token_factory::mint(signer::address_of(caller), + let amount_to_mint_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); + + variable_debt_token_factory::mint( + signer::address_of(caller), signer::address_of(token_receiver), amount_to_mint, reserve_index, - var_token_address); + var_token_address, + ); // assert a token supply - assert!(variable_token_factory::supply(var_token_address) == amount_to_mint, - TEST_SUCCESS); - assert!(variable_token_factory::maximum(var_token_address) - == option::none(), TEST_SUCCESS); + assert!( + variable_debt_token_factory::scaled_total_supply(var_token_address) + == amount_to_mint_scaled, + TEST_SUCCESS, + ); // assert var_tokens receiver balance let var_token_amount_scaled = wad_ray_math::ray_div(amount_to_mint, reserve_index); - assert!(variable_token_factory::balance_of(signer::address_of(token_receiver), - var_token_address) == amount_to_mint, - TEST_SUCCESS); - assert!(variable_token_factory::scale_balance_of(signer::address_of(token_receiver), - var_token_address) - == var_token_amount_scaled, - TEST_SUCCESS); + assert!( + variable_debt_token_factory::scaled_balance_of( + signer::address_of(token_receiver), var_token_address + ) == var_token_amount_scaled, + TEST_SUCCESS, + ); // check emitted events let emitted_transfer_events = emitted_events(); @@ -139,26 +171,30 @@ module aave_pool::variable_token_factory_tests { // ============= BURN ============== // // now burn the variable tokens let amount_to_burn = amount_to_mint / 2; - variable_token_factory::burn(signer::address_of(token_receiver), amount_to_burn, - reserve_index, var_token_address); + variable_debt_token_factory::burn( + signer::address_of(token_receiver), + amount_to_burn, + reserve_index, + var_token_address, + ); // assert var token supply - assert!(variable_token_factory::supply(var_token_address) - == amount_to_mint - amount_to_burn, - TEST_SUCCESS); - assert!(variable_token_factory::maximum(var_token_address) - == option::none(), TEST_SUCCESS); + let expected_var_token_scaled_total_supply = + wad_ray_math::ray_div(amount_to_mint - amount_to_burn, reserve_index); + assert!( + variable_debt_token_factory::scaled_total_supply(var_token_address) + == expected_var_token_scaled_total_supply, + TEST_SUCCESS, + ); // assert var_tokens receiver balance let var_token_amount_scaled = wad_ray_math::ray_div(amount_to_burn, reserve_index); - assert!(variable_token_factory::balance_of(signer::address_of(token_receiver), - var_token_address) - == (amount_to_mint - amount_to_burn), - TEST_SUCCESS); - assert!(variable_token_factory::scale_balance_of(signer::address_of(token_receiver), - var_token_address) - == var_token_amount_scaled, - TEST_SUCCESS); + assert!( + variable_debt_token_factory::scaled_balance_of( + signer::address_of(token_receiver), var_token_address + ) == var_token_amount_scaled, + TEST_SUCCESS, + ); // check emitted events let emitted_transfer_events = emitted_events(); diff --git a/movefmt.toml b/movefmt.toml index 61005f0..bcc50f1 100644 --- a/movefmt.toml +++ b/movefmt.toml @@ -2,5 +2,5 @@ max_width = 90 indent_size = 4 hard_tabs = false tab_spaces = 4 -emit_mode = "Files" +emit_mode = "Overwrite" verbose = "Normal" diff --git a/test-suites/clients/aTokensClient.ts b/test-suites/clients/aTokensClient.ts index 40fdfc1..93f07d7 100644 --- a/test-suites/clients/aTokensClient.ts +++ b/test-suites/clients/aTokensClient.ts @@ -3,25 +3,23 @@ import { BigNumber } from "ethers"; import { AptosContractWrapperBaseClass } from "./baseClass"; import { ATokenAssetMetadataFuncAddr, - ATokenBalanceOfFuncAddr, ATokenCreateTokenFuncAddr, ATokenDecimalsFuncAddr, ATokenGetGetPreviousIndexFuncAddr, ATokenGetMetadataBySymbolFuncAddr, ATokenGetReserveTreasuryAddressFuncAddr, ATokenGetRevisionFuncAddr, + ATokenGetScaledUserBalanceAndSupplyFuncAddr, ATokenGetTokenAccountAddressFuncAddr, ATokenGetUnderlyingAssetAddressFuncAddr, - ATokenMaximumFuncAddr, ATokenNameFuncAddr, ATokenRescueTokensFuncAddr, - ATokenScaleBalanceOfFuncAddr, - ATokenScaleTotalSupplyFuncAddr, - ATokenSupplyFuncAddr, + ATokenScaledBalanceOfFuncAddr, + ATokenScaledTotalSupplyFuncAddr, ATokenSymbolFuncAddr, ATokenTokenAddressFuncAddr, } from "../configs/tokens"; -import { mapToBN } from "../helpers/contract_helper"; +import { mapToBN } from "../helpers/contractHelper"; import { Metadata } from "../helpers/interfaces"; export class ATokensClient extends AptosContractWrapperBaseClass { @@ -60,53 +58,43 @@ export class ATokensClient extends AptosContractWrapperBaseClass { return resp as number; } - public async getMetadataBySymbol(symbol: string): Promise { - const [resp] = await this.callViewMethod(ATokenGetMetadataBySymbolFuncAddr, [symbol]); - return (resp as Metadata).inner; + public async getMetadataBySymbol(owner: AccountAddress, symbol: string): Promise { + const [resp] = await this.callViewMethod(ATokenGetMetadataBySymbolFuncAddr, [owner, symbol]); + return AccountAddress.fromString((resp as Metadata).inner); } public async getTokenAccountAddress(metadataAddress: AccountAddress): Promise { const [resp] = await this.callViewMethod(ATokenGetTokenAccountAddressFuncAddr, [metadataAddress]); - return AccountAddress.fromString((resp as Metadata).inner); - } - - public async tokenAddress(symbol: string): Promise { - const [resp] = await this.callViewMethod(ATokenTokenAddressFuncAddr, [symbol]); - return AccountAddress.fromString((resp as Metadata).inner); - } - - public async assetMetadata(symbol: string): Promise { - const [resp] = await this.callViewMethod(ATokenAssetMetadataFuncAddr, [symbol]); - return AccountAddress.fromString((resp as Metadata).inner); + return AccountAddress.fromString(resp as string); } - public async getReserveTreasuryAddress(symbol: string): Promise { - const [resp] = await this.callViewMethod(ATokenGetReserveTreasuryAddressFuncAddr, [symbol]); - return AccountAddress.fromString((resp as Metadata).inner); + public async getTokenAddress(owner: AccountAddress, symbol: string): Promise { + const [resp] = await this.callViewMethod(ATokenTokenAddressFuncAddr, [owner, symbol]); + return AccountAddress.fromString(resp as string); } - public async getUnderlyingAssetAddress(symbol: string): Promise { - const [resp] = await this.callViewMethod(ATokenGetUnderlyingAssetAddressFuncAddr, [symbol]); + public async assetMetadata(owner: AccountAddress, symbol: string): Promise { + const [resp] = await this.callViewMethod(ATokenAssetMetadataFuncAddr, [owner, symbol]); return AccountAddress.fromString((resp as Metadata).inner); } - public async balanceOf(owner: AccountAddress, metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(ATokenBalanceOfFuncAddr, [owner, metadataAddress])).map(mapToBN); - return resp; + public async getReserveTreasuryAddress(metadataAddress: AccountAddress): Promise { + const [resp] = await this.callViewMethod(ATokenGetReserveTreasuryAddressFuncAddr, [metadataAddress]); + return AccountAddress.fromString(resp as string); } - public async scaleBalanceOf(owner: AccountAddress, metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(ATokenScaleBalanceOfFuncAddr, [owner, metadataAddress])).map(mapToBN); - return resp; + public async getUnderlyingAssetAddress(metadataAddress: AccountAddress): Promise { + const [resp] = await this.callViewMethod(ATokenGetUnderlyingAssetAddressFuncAddr, [metadataAddress]); + return AccountAddress.fromString(resp as string); } - public async supply(metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(ATokenSupplyFuncAddr, [metadataAddress])).map(mapToBN); + public async scaledBalanceOf(owner: AccountAddress, metadataAddress: AccountAddress): Promise { + const [resp] = (await this.callViewMethod(ATokenScaledBalanceOfFuncAddr, [owner, metadataAddress])).map(mapToBN); return resp; } - public async scaleTotalSupply(metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(ATokenScaleTotalSupplyFuncAddr, [metadataAddress])).map(mapToBN); + public async scaledTotalSupply(metadataAddress: AccountAddress): Promise { + const [resp] = (await this.callViewMethod(ATokenScaledTotalSupplyFuncAddr, [metadataAddress])).map(mapToBN); return resp; } @@ -116,21 +104,15 @@ export class ATokensClient extends AptosContractWrapperBaseClass { } public async getScaledUserBalanceAndSupply( - user: AccountAddress, + owner: AccountAddress, metadataAddress: AccountAddress, ): Promise<{ scaledUserBalance: BigNumber; supply: BigNumber }> { const [scaledUserBalance, supply] = ( - await this.callViewMethod(ATokenGetGetPreviousIndexFuncAddr, [user, metadataAddress]) + await this.callViewMethod(ATokenGetScaledUserBalanceAndSupplyFuncAddr, [owner, metadataAddress]) ).map(mapToBN); return { scaledUserBalance, supply }; } - // Get the maximum supply from the metadata object. - public async maximum(metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(ATokenMaximumFuncAddr, [metadataAddress])).map(mapToBN); - return resp; - } - // Get the name of the fungible asset from the metadata object. public async name(metadataAddress: AccountAddress): Promise { const [resp] = await this.callViewMethod(ATokenNameFuncAddr, [metadataAddress]); diff --git a/test-suites/clients/aclClient.ts b/test-suites/clients/aclClient.ts index a787fea..c00c897 100644 --- a/test-suites/clients/aclClient.ts +++ b/test-suites/clients/aclClient.ts @@ -1,7 +1,7 @@ import { AccountAddress, CommittedTransactionResponse } from "@aptos-labs/ts-sdk"; import { AptosContractWrapperBaseClass } from "./baseClass"; import { - AddPoolAdminFuncAddr, + addPoolAdminFuncAddr, addAssetListingAdminFuncAddr, addBridgeFuncAddr, addEmergencyAdminFuncAddr, @@ -27,8 +27,13 @@ import { removeFlashBorrowerFuncAddr, removePoolAdminFuncAddr, removeRiskAdminFuncAddr, + renounceRoleFuncAddr, revokeRoleFuncAddr, -} from "../configs/acl_manage"; + grantDefaultAdminRole, + defaultAdminRole, + getRoleAdmin, + setRoleAdmin, +} from "../configs/aclManage"; export class AclClient extends AptosContractWrapperBaseClass { public async hasRole(role: string, user: AccountAddress): Promise { @@ -40,12 +45,16 @@ export class AclClient extends AptosContractWrapperBaseClass { return this.sendTxAndAwaitResponse(grantRoleFuncAddr, [role, user]); } + public async renounceRole(role: string, user: AccountAddress): Promise { + return this.sendTxAndAwaitResponse(renounceRoleFuncAddr, [role, user]); + } + public async revokeRole(role: string, user: AccountAddress): Promise { return this.sendTxAndAwaitResponse(revokeRoleFuncAddr, [role, user]); } public async addPoolAdmin(user: AccountAddress): Promise { - return this.sendTxAndAwaitResponse(AddPoolAdminFuncAddr, [user]); + return this.sendTxAndAwaitResponse(addPoolAdminFuncAddr, [user]); } public async removePoolAdmin(user: AccountAddress): Promise { @@ -151,4 +160,22 @@ export class AclClient extends AptosContractWrapperBaseClass { const [resp] = await this.callViewMethod(getAssetListingAdminRoleFuncAddr, []); return resp as string; } + + public async grantDefaultRoleAdmin(): Promise { + return this.sendTxAndAwaitResponse(grantDefaultAdminRole, []); + } + + public async getDefaultAdminRole(): Promise { + const [resp] = await this.callViewMethod(defaultAdminRole, []); + return resp as string; + } + + public async getRoleAdmin(role: string): Promise { + const [resp] = await this.callViewMethod(getRoleAdmin, [role]); + return resp as string; + } + + public async setRoleAdmin(role: string, adminRole: string): Promise { + return this.sendTxAndAwaitResponse(setRoleAdmin, [role, adminRole]); + } } diff --git a/test-suites/clients/bridgeClient.ts b/test-suites/clients/bridgeClient.ts index 9684532..512b63b 100644 --- a/test-suites/clients/bridgeClient.ts +++ b/test-suites/clients/bridgeClient.ts @@ -8,14 +8,8 @@ export class BridgeClient extends AptosContractWrapperBaseClass { asset: AccountAddress, amount: BigNumber, fee: BigNumber, - protocolFeeBps: BigNumber, ): Promise { - return this.sendTxAndAwaitResponse(BackUnbackedFuncAddr, [ - asset, - amount.toString(), - fee.toString(), - protocolFeeBps.toString(), - ]); + return this.sendTxAndAwaitResponse(BackUnbackedFuncAddr, [asset, amount.toString(), fee.toString()]); } public async mintUnbacked( diff --git a/test-suites/clients/coreClient.ts b/test-suites/clients/coreClient.ts index c08848c..f59b50e 100644 --- a/test-suites/clients/coreClient.ts +++ b/test-suites/clients/coreClient.ts @@ -11,8 +11,8 @@ import { SetUserUseReserveAsCollateralFuncAddr, SupplyFuncAddr, WithdrawFuncAddr, -} from "../configs/supply_borrow"; -import { mapToBN } from "../helpers/contract_helper"; +} from "../configs/supplyBorrow"; +import { mapToBN } from "../helpers/contractHelper"; export class CoreClient extends AptosContractWrapperBaseClass { /// User supplies @@ -25,16 +25,6 @@ export class CoreClient extends AptosContractWrapperBaseClass { return this.sendTxAndAwaitResponse(SupplyFuncAddr, [asset, amount.toString(), onBehalfOf, referralCode]); } - /// User deposits, same as supply - public async deposit( - asset: AccountAddress, - amount: BigNumber, - onBehalfOf: AccountAddress, - referralCode: number, - ): Promise { - return this.supply(asset, amount, onBehalfOf, referralCode); - } - /// User withdraws public async withdraw( asset: AccountAddress, @@ -47,19 +37,17 @@ export class CoreClient extends AptosContractWrapperBaseClass { /// User borrows public async borrow( asset: AccountAddress, - onBehalfOf: AccountAddress, amount: BigNumber, interestRateMode: number, referralCode: number, - releaseUnderlying: boolean, + onBehalfOf: AccountAddress, ): Promise { return this.sendTxAndAwaitResponse(BorrowFuncAddr, [ asset, - onBehalfOf, amount.toString(), interestRateMode, referralCode, - releaseUnderlying, + onBehalfOf, ]); } @@ -69,15 +57,8 @@ export class CoreClient extends AptosContractWrapperBaseClass { amount: BigNumber, interestRateMode: number, onBehalfOf: AccountAddress, - useATokens: boolean, ): Promise { - return this.sendTxAndAwaitResponse(RepayFuncAddr, [ - asset, - amount.toString(), - interestRateMode, - onBehalfOf, - useATokens, - ]); + return this.sendTxAndAwaitResponse(RepayFuncAddr, [asset, amount.toString(), interestRateMode, onBehalfOf]); } /// User repays with A tokens diff --git a/test-suites/clients/largePackagesClient.ts b/test-suites/clients/largePackagesClient.ts index acd51d0..da705c6 100644 --- a/test-suites/clients/largePackagesClient.ts +++ b/test-suites/clients/largePackagesClient.ts @@ -6,7 +6,7 @@ import { StageCodeChunkAndPublishToObjectFuncAddr, StageCodeChunkAndUpgradeObjectCodeFuncAddr, StageCodeChunkFuncAddr, -} from "../configs/large_packages"; +} from "../configs/largePackages"; export class LargePackagesClient extends AptosContractWrapperBaseClass { public async stageCodeChunk( diff --git a/test-suites/clients/oracleClient.ts b/test-suites/clients/oracleClient.ts index d588eee..b796102 100644 --- a/test-suites/clients/oracleClient.ts +++ b/test-suites/clients/oracleClient.ts @@ -1,8 +1,15 @@ import { AccountAddress, CommittedTransactionResponse } from "@aptos-labs/ts-sdk"; import { BigNumber } from "ethers"; import { AptosContractWrapperBaseClass } from "./baseClass"; -import { mapToBN } from "../helpers/contract_helper"; -import { GetAssetPriceFuncAddr, SetAssetPriceFuncAddr } from "../configs/oracle"; +import { mapToBN } from "../helpers/contractHelper"; +import { + GetAssetPriceFuncAddr, + GetGracePeriodFuncAddr, + IsBorrowAllowedFuncAddr, + IsLiquidationAllowedFuncAddr, + SetAssetPriceFuncAddr, + SetGracePeriodFuncAddr, +} from "../configs/oracle"; export class OracleClient extends AptosContractWrapperBaseClass { public async setAssetPrice(asset: AccountAddress, price: BigNumber): Promise { @@ -13,4 +20,23 @@ export class OracleClient extends AptosContractWrapperBaseClass { const [resp] = (await this.callViewMethod(GetAssetPriceFuncAddr, [asset])).map(mapToBN); return resp; } + + public async isBorrowAllowed(): Promise { + const [resp] = await this.callViewMethod(IsBorrowAllowedFuncAddr, []); + return resp as boolean; + } + + public async isLiquidationAllowed(): Promise { + const [resp] = await this.callViewMethod(IsLiquidationAllowedFuncAddr, []); + return resp as boolean; + } + + public async setGracePeriod(newGracePeriod: BigNumber): Promise { + return this.sendTxAndAwaitResponse(SetGracePeriodFuncAddr, [newGracePeriod.toString()]); + } + + public async getGracePeriod(): Promise { + const [resp] = (await this.callViewMethod(GetGracePeriodFuncAddr, [])).map(mapToBN); + return resp; + } } diff --git a/test-suites/clients/poolClient.ts b/test-suites/clients/poolClient.ts index 26598d9..85e2914 100644 --- a/test-suites/clients/poolClient.ts +++ b/test-suites/clients/poolClient.ts @@ -17,6 +17,7 @@ import { GetMaxVariableBorrowRateFuncAddr, GetPausedFuncAddr, GetReserveCapsFuncAddr, + GetReserveDataAndReservesCountFuncAddr, GetReserveEModeCategoryFuncAddr, GetReserveTokensAddressesFuncAddr, GetSiloedBorrowingFuncAddr, @@ -25,14 +26,14 @@ import { GetUserReserveDataFuncAddr, GetVariableRateSlope1FuncAddr, GetVariableRateSlope2FuncAddr, - PoolConfiguratorAddReservesFuncAddr, + PoolConfiguratorInitReservesFuncAddr, PoolConfiguratorConfigureReserveAsCollateralFuncAddr, PoolConfiguratorDropReserveFuncAddr, PoolConfiguratorGetRevisionFuncAddr, - PoolConfiguratorReservesFuncAddr, PoolConfiguratorSetAssetEmodeCategoryFuncAddr, PoolConfiguratorSetBorrowCapFuncAddr, PoolConfiguratorSetBorrowableInIsolationFuncAddr, + PoolConfiguratorSetDebtCeilingFuncAddr, PoolConfiguratorSetEmodeCategoryFuncAddr, PoolConfiguratorSetLiquidationProtocolFeeFuncAddr, PoolConfiguratorSetPoolPauseFuncAddr, @@ -47,6 +48,7 @@ import { PoolConfiguratorSetUnbackedMintCapFuncAddr, PoolConfiguratorUpdateBridgeProtocolFeeFuncAddr, PoolConfiguratorUpdateFlashloanPremiumToProtocolFuncAddr, + PoolConfiguratorUpdateFlashloanPremiumTotalFuncAddr, PoolConfigureEmodeCategoryFuncAddr, PoolGetBridgeProtocolFeeFuncAddr, PoolGetEmodeCategoryDataFuncAddr, @@ -66,12 +68,17 @@ import { PoolMintToTreasuryFuncAddr, PoolRescueTokensFuncAddr, PoolResetIsolationModeTotalDebtFuncAddr, + PoolScaledATokenBalanceOfFuncAddr, + PoolScaledATokenTotalSupplyFuncAddr, + PoolScaledVariableTokenBalanceOfFuncAddr, + PoolScaledVariableTokenTotalSupplyFuncAddr, PoolSetBridgeProtocolFeeFuncAddr, PoolSetFlashloanPremiumsFuncAddr, PoolSetUserEmodeFuncAddr, SetReserveInterestRateStrategyFuncAddr, + PoolConfiguratorConfigureReservesFuncAddr, } from "../configs/pool"; -import { mapToBN } from "../helpers/contract_helper"; +import { mapToBN } from "../helpers/contractHelper"; export type ReserveConfigurationMap = { data: Number; @@ -161,12 +168,11 @@ export class PoolClient extends AptosContractWrapperBaseClass { } public async rescueTokens( - asset: AccountAddress, + token: AccountAddress, + to: AccountAddress, amount: BigNumber, - onBehalfOf: AccountAddress, - referralCode: number, ): Promise { - return this.sendTxAndAwaitResponse(PoolRescueTokensFuncAddr, [asset, amount.toString(), onBehalfOf, referralCode]); + return this.sendTxAndAwaitResponse(PoolRescueTokensFuncAddr, [token, to, amount.toString()]); } public async setBridgeProtocolFee(protocolFee: BigNumber): Promise { @@ -193,8 +199,13 @@ export class PoolClient extends AptosContractWrapperBaseClass { return resp as ReserveConfigurationMap; } - public async getReserveData(asset: AccountAddress): Promise { + public async getReserveData(asset: AccountAddress): Promise<{ reserveData: ReserveData; count: number }> { const [resp] = await this.callViewMethod(PoolGetReserveDataFuncAddr, [asset]); + return { reserveData: resp[0] as ReserveData, count: resp[1] as number }; + } + + public async getReserveDataAndReservesCount(asset: AccountAddress): Promise { + const [resp] = await this.callViewMethod(GetReserveDataAndReservesCountFuncAddr, [asset]); return resp as ReserveData; } @@ -256,7 +267,7 @@ export class PoolClient extends AptosContractWrapperBaseClass { underlyingAssetDecimals: Array, underlyingAsset: Array, ): Promise { - return this.sendTxAndAwaitResponse(PoolConfiguratorAddReservesFuncAddr, [ + return this.sendTxAndAwaitResponse(PoolConfiguratorInitReservesFuncAddr, [ aTokenImpl, variableDebtTokenImpl.map((item) => item.toString()), underlyingAssetDecimals.map((item) => item.toString()), @@ -311,8 +322,8 @@ export class PoolClient extends AptosContractWrapperBaseClass { return this.sendTxAndAwaitResponse(PoolConfiguratorSetLiquidationProtocolFeeFuncAddr, [asset, newFee.toString()]); } - public async setPoolPause(asset: AccountAddress, paused: boolean): Promise { - return this.sendTxAndAwaitResponse(PoolConfiguratorSetPoolPauseFuncAddr, [asset, paused]); + public async setPoolPause(paused: boolean): Promise { + return this.sendTxAndAwaitResponse(PoolConfiguratorSetPoolPauseFuncAddr, [paused]); } public async setReserveActive(asset: AccountAddress, active: boolean): Promise { @@ -323,6 +334,10 @@ export class PoolClient extends AptosContractWrapperBaseClass { return this.sendTxAndAwaitResponse(PoolConfiguratorSetReserveBorrowingFuncAddr, [asset, enabled]); } + public async setDebtCeiling(asset: AccountAddress, newDebtCeiling: BigNumber): Promise { + return this.sendTxAndAwaitResponse(PoolConfiguratorSetDebtCeilingFuncAddr, [asset, newDebtCeiling.toString()]); + } + public async configureReserveAsCollateral( asset: AccountAddress, ltv: BigNumber, @@ -352,7 +367,7 @@ export class PoolClient extends AptosContractWrapperBaseClass { return this.sendTxAndAwaitResponse(PoolConfiguratorSetReserveFreezeFuncAddr, [asset, freeze]); } - public async setReservePaused(asset: AccountAddress, paused: boolean): Promise { + public async setReservePause(asset: AccountAddress, paused: boolean): Promise { return this.sendTxAndAwaitResponse(PoolConfiguratorSetReservePauseFuncAddr, [asset, paused]); } @@ -388,6 +403,14 @@ export class PoolClient extends AptosContractWrapperBaseClass { ]); } + public async updateFloashloanPremiumTotal( + newFlashloanPremiumTotal: BigNumber, + ): Promise { + return this.sendTxAndAwaitResponse(PoolConfiguratorUpdateFlashloanPremiumTotalFuncAddr, [ + newFlashloanPremiumTotal.toString(), + ]); + } + public async configureReserves( asset: Array, base_ltv: Array, @@ -399,7 +422,7 @@ export class PoolClient extends AptosContractWrapperBaseClass { borrowingEnabled: Array, flashloanEnabled: Array, ): Promise { - return this.sendTxAndAwaitResponse(PoolConfiguratorReservesFuncAddr, [ + return this.sendTxAndAwaitResponse(PoolConfiguratorConfigureReservesFuncAddr, [ asset, base_ltv.map((item) => item.toString()), liquidationThreshold.map((item) => item.toString()), @@ -412,6 +435,26 @@ export class PoolClient extends AptosContractWrapperBaseClass { ]); } + public async initReserves( + underlyingAssets: Array, + underlyingAssetDecimals: Array, + treasury: Array, + aTokenName: Array, + aTokenSymbol: Array, + variableDebtTokenName: Array, + variableDebtTokenSymbol: Array, + ): Promise { + return this.sendTxAndAwaitResponse(PoolConfiguratorInitReservesFuncAddr, [ + underlyingAssets, + underlyingAssetDecimals, + treasury, + aTokenName, + aTokenSymbol, + variableDebtTokenName, + variableDebtTokenSymbol, + ]); + } + public async getPoolConfiguratorRevision(): Promise { const [resp] = (await this.callViewMethod(PoolConfiguratorGetRevisionFuncAddr, [])).map(mapToBN); return resp; @@ -501,16 +544,23 @@ export class PoolClient extends AptosContractWrapperBaseClass { reserveFactor: BigNumber, reserve: AccountAddress, atokenAddress: AccountAddress, - ): Promise { - return this.sendTxAndAwaitResponse(CalculateInterestRatesFuncAddr, [ - unbacked.toString(), - liquidityAdded.toString(), - liquidityTaken.toString(), - totalVariableDebt.toString(), - reserveFactor.toString(), - reserve, - atokenAddress, - ]); + ): Promise<{ currentLiquidityRate: BigNumber; currentVariableBorrowRate: BigNumber }> { + const [currentLiquidityRate, currentVariableBorrowRate] = await this.callViewMethod( + CalculateInterestRatesFuncAddr, + [ + unbacked.toString(), + liquidityAdded.toString(), + liquidityTaken.toString(), + totalVariableDebt.toString(), + reserveFactor.toString(), + reserve, + atokenAddress, + ], + ); + return { + currentLiquidityRate: BigNumber.from(currentLiquidityRate), + currentVariableBorrowRate: BigNumber.from(currentVariableBorrowRate), + }; } public async getAllReservesTokens(): Promise> { @@ -678,4 +728,35 @@ export class PoolClient extends AptosContractWrapperBaseClass { const [isFlashloanEnabled] = await this.callViewMethod(GetFlashLoanEnabledFuncAddr, [asset]); return isFlashloanEnabled as boolean; } + + public async getScaledATokenTotalSupply(aTokenAddress: AccountAddress): Promise { + const [totalSupply] = (await this.callViewMethod(PoolScaledATokenTotalSupplyFuncAddr, [aTokenAddress])).map( + mapToBN, + ); + return totalSupply; + } + + public async getScaledATokenBalanceOf(owner: AccountAddress, aTokenAddress: AccountAddress): Promise { + const [balance] = (await this.callViewMethod(PoolScaledATokenBalanceOfFuncAddr, [owner, aTokenAddress])).map( + mapToBN, + ); + return balance; + } + + public async getScaledVariableTokenTotalSupply(aTokenAddress: AccountAddress): Promise { + const [totalSupply] = (await this.callViewMethod(PoolScaledVariableTokenTotalSupplyFuncAddr, [aTokenAddress])).map( + mapToBN, + ); + return totalSupply; + } + + public async getScaledVariableTokenBalanceOf( + owner: AccountAddress, + varTokenAddress: AccountAddress, + ): Promise { + const [balance] = ( + await this.callViewMethod(PoolScaledVariableTokenBalanceOfFuncAddr, [owner, varTokenAddress]) + ).map(mapToBN); + return balance; + } } diff --git a/test-suites/clients/uiIncentiveDataProvider.ts b/test-suites/clients/uiIncentiveDataProvider.ts new file mode 100644 index 0000000..1d30982 --- /dev/null +++ b/test-suites/clients/uiIncentiveDataProvider.ts @@ -0,0 +1,184 @@ +import { AccountAddress } from "@aptos-labs/ts-sdk"; +import { AptosContractWrapperBaseClass } from "./baseClass"; +import { + UiIncentivesDataProviderGetFullReservesIncentiveDataFuncAddr, + UiIncentivesDataProviderGetReservesIncentivesDataFuncAddr, + UiIncentivesDataProviderGetUserReservesIncentivesDataFuncAddr, + UiIncentivesDataProviderV3DataAddressFuncAddr, + UiIncentivesDataProviderV3DataObjectFuncAddr, +} from "../configs/pool"; +import { Metadata } from "../helpers/interfaces"; + +export type AggregatedReserveIncentiveData = { + underlyingAsset: AccountAddress; + aIncentiveData: IncentiveData; + vIncentiveData: IncentiveData; +}; + +export type IncentiveData = { + tokenAddress: AccountAddress; + incentiveControllerAddress: AccountAddress; + rewardsTokenInformation: [RewardInfo]; +}; + +export type RewardInfo = { + rewardTokenSymbol: String; + rewardTokenAddress: AccountAddress; + rewardOracleAddress: AccountAddress; + emissionPerSecond: bigint; + incentivesLastUpdateTimestamp: bigint; + tokenIncentivesIndex: bigint; + emissionEndTimestamp: bigint; + rewardPriceFeed: bigint; + rewardTokenDecimals: number; + precision: number; + priceFeedDecimals: number; +}; + +export type UserReserveIncentiveData = { + underlyingAsset: AccountAddress; + aTokenIncentivesUserData: UserIncentiveData; + vTokenIncentivesUserData: UserIncentiveData; +}; + +export type UserIncentiveData = { + tokenAddress: AccountAddress; + incentiveControllerAddress: AccountAddress; + userRewardsInformation: [UserRewardInfo]; +}; + +export type UserRewardInfo = { + rewardTokenSymbol: String; + rewardOracleAddress: AccountAddress; + rewardTokenAddress: AccountAddress; + userUnclaimedRewards: bigint; + tokenIncentivesUserIndex: bigint; + rewardPriceFeed: bigint; + priceFeedDecimals: number; + rewardTokenDecimals: number; +}; + +const mapIncentiveData = (rewardTokenInfo: any): RewardInfo => + ({ + rewardTokenSymbol: rewardTokenInfo.reward_token_symbol as string, + rewardTokenAddress: AccountAddress.fromString(rewardTokenInfo.reward_token_address.toString()), + rewardOracleAddress: AccountAddress.fromString(rewardTokenInfo.reward_oracle_address.toString()), + emissionPerSecond: BigInt(rewardTokenInfo.emission_per_second), + incentivesLastUpdateTimestamp: BigInt(rewardTokenInfo.incentives_last_update_timestamp), + tokenIncentivesIndex: BigInt(rewardTokenInfo.token_incentives_index), + emissionEndTimestamp: BigInt(rewardTokenInfo.emission_end_timestamp), + rewardPriceFeed: BigInt(rewardTokenInfo.reward_price_feed), + rewardTokenDecimals: rewardTokenInfo.reward_token_decimals as number, + precision: rewardTokenInfo.precision as number, + priceFeedDecimals: rewardTokenInfo.price_feed_decimals as number, + }) as RewardInfo; + +const mapUserIncentiveData = (rewardTokenInfo: any): UserRewardInfo => + ({ + rewardTokenSymbol: rewardTokenInfo.reward_token_symbol as string, + rewardOracleAddress: AccountAddress.fromString(rewardTokenInfo.reward_oracle_address.toString()), + rewardTokenAddress: AccountAddress.fromString(rewardTokenInfo.reward_token_address.toString()), + userUnclaimedRewards: BigInt(rewardTokenInfo.user_unclaimed_rewards), + tokenIncentivesUserIndex: BigInt(rewardTokenInfo.token_incentives_user_index), + rewardPriceFeed: BigInt(rewardTokenInfo.reward_price_feed), + priceFeedDecimals: rewardTokenInfo.price_feed_decimals as number, + rewardTokenDecimals: rewardTokenInfo.reward_token_decimals as number, + }) as UserRewardInfo; + +const getUserReservesIncentivesDataInternal = ( + userReservesIncentivesDataRaw: Array, +): [UserReserveIncentiveData] => { + const userReservesIncentives = userReservesIncentivesDataRaw.map((item) => { + const aIncentiveUserData = item.a_token_incentives_user_data; + const aRewardsTokenInformation = aIncentiveUserData.user_rewards_information as Array; + const vIncentiveUserData = item.v_token_incentives_user_data; + const vRewardsTokenInformation = vIncentiveUserData.user_rewards_information as Array; + + return { + underlyingAsset: AccountAddress.fromString(item.underlying_asset.toString()), + aTokenIncentivesUserData: { + tokenAddress: AccountAddress.fromString(aIncentiveUserData.token_address.toString()), + incentiveControllerAddress: AccountAddress.fromString( + aIncentiveUserData.incentive_controller_address.toString(), + ), + userRewardsInformation: aRewardsTokenInformation.map(mapUserIncentiveData), + } as UserIncentiveData, + vTokenIncentivesUserData: { + tokenAddress: AccountAddress.fromString(vIncentiveUserData.token_address.toString()), + incentiveControllerAddress: AccountAddress.fromString( + vIncentiveUserData.incentive_controller_address.toString(), + ), + userRewardsInformation: vRewardsTokenInformation.map(mapUserIncentiveData), + } as UserIncentiveData, + } as UserReserveIncentiveData; + }); + + return userReservesIncentives as [UserReserveIncentiveData]; +}; + +const getReservesIncentivesDataInternal = ( + aggregatedIncentivesReserveDataRaw: Array, +): [AggregatedReserveIncentiveData] => { + const reservesIncentivesData = aggregatedIncentivesReserveDataRaw.map((item) => { + const aIncentiveData = item.a_incentive_data; + const aRewardsTokenInformation = aIncentiveData.rewards_token_information as Array; + const vIncentiveData = item.v_incentive_data; + const vRewardsTokenInformation = vIncentiveData.rewards_token_information as Array; + return { + underlyingAsset: AccountAddress.fromString(item.underlying_asset.toString()), + aIncentiveData: { + tokenAddress: AccountAddress.fromString(aIncentiveData.token_address.toString()), + incentiveControllerAddress: AccountAddress.fromString(aIncentiveData.incentive_controller_address.toString()), + rewardsTokenInformation: aRewardsTokenInformation.map(mapIncentiveData), + } as IncentiveData, + vIncentiveData: { + tokenAddress: AccountAddress.fromString(vIncentiveData.token_address.toString()), + incentiveControllerAddress: AccountAddress.fromString(vIncentiveData.incentive_controller_address.toString()), + rewardsTokenInformation: vRewardsTokenInformation.map(mapIncentiveData), + } as IncentiveData, + } as AggregatedReserveIncentiveData; + }); + + return reservesIncentivesData as [AggregatedReserveIncentiveData]; +}; + +export class UiIncentiveDataProviderClient extends AptosContractWrapperBaseClass { + public async uiPoolDataProviderV3DataAddress(): Promise { + const [resp] = await this.callViewMethod(UiIncentivesDataProviderV3DataAddressFuncAddr, []); + return AccountAddress.fromString(resp as string); + } + + public async uiPoolDataProviderV3DataObject(): Promise { + const [resp] = await this.callViewMethod(UiIncentivesDataProviderV3DataObjectFuncAddr, []); + return AccountAddress.fromString((resp as Metadata).inner); + } + + public async getFullReservesIncentiveData(user: AccountAddress): Promise<{ + aggregatedReservesIncentivesData: [AggregatedReserveIncentiveData]; + userReserveIncentiveData: [UserReserveIncentiveData]; + }> { + const resp = await this.callViewMethod(UiIncentivesDataProviderGetFullReservesIncentiveDataFuncAddr, [user]); + + const reservesIncentivesDataInternal = resp.at(0) as Array; + const aggregatedReservesIncentivesData = getReservesIncentivesDataInternal(reservesIncentivesDataInternal); + + const userReservesIncentivesDataRaw = resp.at(1) as Array; + const userReserveIncentiveData = getUserReservesIncentivesDataInternal(userReservesIncentivesDataRaw); + + return { aggregatedReservesIncentivesData, userReserveIncentiveData }; + } + + public async getReservesIncentivesData(): Promise<[AggregatedReserveIncentiveData]> { + const resp = await this.callViewMethod(UiIncentivesDataProviderGetReservesIncentivesDataFuncAddr, []); + const reservesIncentivesDataInternal = resp.at(0) as Array; + const aggregatedReservesIncentivesData = getReservesIncentivesDataInternal(reservesIncentivesDataInternal); + return aggregatedReservesIncentivesData as [AggregatedReserveIncentiveData]; + } + + public async getUserReservesIncentivesData(user: AccountAddress): Promise<[UserReserveIncentiveData]> { + const resp = await this.callViewMethod(UiIncentivesDataProviderGetUserReservesIncentivesDataFuncAddr, [user]); + const userUserReservesIncentivesDataRaw = resp.at(1) as Array; + const userReserveIncentivesData = getUserReservesIncentivesDataInternal(userUserReservesIncentivesDataRaw); + return userReserveIncentivesData as [UserReserveIncentiveData]; + } +} diff --git a/test-suites/clients/uiPoolDataProvider.ts b/test-suites/clients/uiPoolDataProvider.ts new file mode 100644 index 0000000..3591811 --- /dev/null +++ b/test-suites/clients/uiPoolDataProvider.ts @@ -0,0 +1,189 @@ +import { AccountAddress } from "@aptos-labs/ts-sdk"; +import { AptosContractWrapperBaseClass } from "./baseClass"; +import { + UiPoolDataProviderGetReservesDataFuncAddr, + UiPoolDataProviderGetReservesListFuncAddr, + UiPoolDataProviderGetUserReservesDataFuncAddr, + UiPoolDataProviderV3DataAddressFuncAddr, + UiPoolDataProviderV3DataObjectFuncAddr, +} from "../configs/pool"; +import { Metadata } from "../helpers/interfaces"; + +export type AggregatedReserveData = { + underlyingAsset: AccountAddress; + name: string; + symbol: string; + decimals: number; + baseLTVasCollateral: bigint; + reserveLiquidationThreshold: bigint; + reserveLiquidationBonus: bigint; + reserveFactor: bigint; + usageAsCollateralEnabled: boolean; + borrowingEnabled: boolean; + isActive: boolean; + isFrozen: boolean; + // base data + liquidityIndex: bigint; + variableBorrowIndex: bigint; + liquidityRate: bigint; + variableBorrowRate: bigint; + lastUpdateTimestamp: number; + aTokenAddress: AccountAddress; + variableDebtTokenAddress: AccountAddress; + // + availableLiquidity: bigint; + totalScaledVariableDebt: bigint; + priceInMarketReferenceCurrency: bigint; + priceOracle: AccountAddress; + variableRateSlope1: bigint; + variableRateSlope2: bigint; + baseVariableBorrowRate: bigint; + optimalUsageRatio: bigint; + // v3 only + isPaused: boolean; + isSiloedBorrowing: boolean; + accruedToTreasury: bigint; + unbacked: bigint; + isolationModeTotalDebt: bigint; + flashLoanEnabled: boolean; + // + debtCeiling: bigint; + debtCeilingDecimals: number; + eModeCategoryId: number; + borrowCap: bigint; + supplyCap: bigint; + // e_mode + eModeLtv: bigint; + eModeLiquidationThreshold: bigint; + eModeLiquidationBonus: bigint; + eModePriceSource: AccountAddress; + eModeLabel: string; + borrowableInIsolation: boolean; +}; + +export type BaseCurrencyData = { + marketReferenceCurrencyDecimals: number; + marketReferenceCurrencyPriceInUsd: bigint; + networkBaseTokenPriceInUsd: bigint; + networkBaseTokenPriceDecimals: number; +}; + +export type UserReserveData = { + underlyingAsset: AccountAddress; + scaledATokenBalance: bigint; + usageAsCollateralEnabledOnUser: boolean; + scaledVariableDebt: bigint; +}; + +export type ReservesData = { + reservesData: AggregatedReserveData[]; + baseCurrencyData: BaseCurrencyData; +}; + +export type UserReservesData = { + userReserves: UserReserveData[]; + userEmodeCategoryId: number; +}; + +export class UiPoolDataProviderClient extends AptosContractWrapperBaseClass { + public async uiPoolDataProviderV3DataAddress(): Promise { + const [resp] = await this.callViewMethod(UiPoolDataProviderV3DataAddressFuncAddr, []); + return AccountAddress.fromString(resp as string); + } + + public async uiPoolDataProviderV3DataObject(): Promise { + const [resp] = await this.callViewMethod(UiPoolDataProviderV3DataObjectFuncAddr, []); + return AccountAddress.fromString((resp as Metadata).inner); + } + + public async getReservesList(): Promise> { + const resp = ((await this.callViewMethod(UiPoolDataProviderGetReservesListFuncAddr, [])).at(0) as Array).map( + (item) => AccountAddress.fromString(item as string), + ); + return resp; + } + + public async getReservesData(): Promise { + const resp = await this.callViewMethod(UiPoolDataProviderGetReservesDataFuncAddr, []); + const aggregatedReserveDataRaw = resp.at(0) as Array; + const reservesData = aggregatedReserveDataRaw.map((item) => ({ + underlyingAsset: AccountAddress.fromString(item.underlying_asset.toString()), + name: item.name as string, + symbol: item.symbol as string, + decimals: Number(item.decimals.toString()), + baseLTVasCollateral: BigInt(item.base_lt_vas_collateral), + reserveLiquidationThreshold: BigInt(item.reserve_liquidation_threshold), + reserveLiquidationBonus: BigInt(item.reserve_liquidation_bonus), + reserveFactor: BigInt(item.reserve_factor), + usageAsCollateralEnabled: item.usage_as_collateral_enabled as boolean, + borrowingEnabled: item.borrowing_enabled as boolean, + isActive: item.is_active as boolean, + isFrozen: item.is_frozen as boolean, + // base data + liquidityIndex: BigInt(item.liquidity_index), + variableBorrowIndex: BigInt(item.variable_borrow_index), + liquidityRate: BigInt(item.liquidity_rate), + variableBorrowRate: BigInt(item.variable_borrow_rate), + lastUpdateTimestamp: Number(item.last_update_timestamp.toString()), + aTokenAddress: AccountAddress.fromString(item.a_token_address.toString()), + variableDebtTokenAddress: AccountAddress.fromString(item.variable_debt_token_address.toString()), + // + availableLiquidity: BigInt(item.available_liquidity), + totalScaledVariableDebt: BigInt(item.total_scaled_variable_debt), + priceInMarketReferenceCurrency: BigInt(item.price_in_market_reference_currency), + priceOracle: AccountAddress.fromString(item.price_oracle.toString()), + variableRateSlope1: BigInt(item.variable_rate_slope1), + variableRateSlope2: BigInt(item.variable_rate_slope2), + baseVariableBorrowRate: BigInt(item.base_variable_borrow_rate), + optimalUsageRatio: BigInt(item.optimal_usage_ratio), + // v3 only + isPaused: item.is_paused as boolean, + isSiloedBorrowing: item.is_siloed_borrowing as boolean, + accruedToTreasury: BigInt(item.accrued_to_treasury), + unbacked: BigInt(item.unbacked), + isolationModeTotalDebt: BigInt(item.isolation_mode_total_debt), + flashLoanEnabled: item.flash_loan_enabled as boolean, + // + debtCeiling: BigInt(item.debt_ceiling), + debtCeilingDecimals: Number(item.debt_ceiling_decimals.toString()), + eModeCategoryId: Number(item.e_mode_category_id.toString()), + borrowCap: BigInt(item.borrow_cap), + supplyCap: BigInt(item.supply_cap), + // e_mode + eModeLtv: BigInt(item.e_mode_ltv.toString()), + eModeLiquidationThreshold: BigInt(item.e_mode_liquidation_threshold.toString()), + eModeLiquidationBonus: BigInt(item.e_mode_liquidation_bonus.toString()), + eModePriceSource: AccountAddress.fromString(item.e_mode_price_source.toString()), + eModeLabel: item.e_mode_label as string, + borrowableInIsolation: item.borrowable_in_isolation as boolean, + })); + + const basicCurrencyInfoRaw = resp.at(1) as any; + const baseCurrencyData = { + marketReferenceCurrencyDecimals: Number(basicCurrencyInfoRaw.market_reference_currency_unit.toString()), + marketReferenceCurrencyPriceInUsd: BigInt(basicCurrencyInfoRaw.market_reference_currency_price_in_usd), + networkBaseTokenPriceInUsd: BigInt(basicCurrencyInfoRaw.network_base_token_price_in_usd.toString()), + networkBaseTokenPriceDecimals: Number(basicCurrencyInfoRaw.network_base_token_price_decimals.toString()), + }; + + return { reservesData, baseCurrencyData }; + } + + public async getUserReserveData(user: string): Promise { + const resp = await this.callViewMethod(UiPoolDataProviderGetUserReservesDataFuncAddr, [user]); + const userReserveDataRaw = resp.at(0) as Array; + const userReserves = userReserveDataRaw.map( + (item) => + ({ + underlyingAsset: AccountAddress.fromString(item.underlying_asset.toString()), + scaledATokenBalance: BigInt(item.scaled_a_token_balance), + usageAsCollateralEnabledOnUser: item.usage_as_collateral_enabled_on_user as boolean, + scaledVariableDebt: BigInt(item.scaled_variable_debt), + }) as UserReserveData, + ); + + const userEmodeCategoryId = resp.at(1) as number; + + return { userReserves, userEmodeCategoryId }; + } +} diff --git a/test-suites/clients/underlyingTokensClient.ts b/test-suites/clients/underlyingTokensClient.ts index bb83b11..f4842cd 100644 --- a/test-suites/clients/underlyingTokensClient.ts +++ b/test-suites/clients/underlyingTokensClient.ts @@ -12,8 +12,9 @@ import { UnderlyingNameFuncAddr, UnderlyingSupplyFuncAddr, UnderlyingSymbolFuncAddr, + UnderlyingTokenAddressFuncAddr, } from "../configs/tokens"; -import { mapToBN } from "../helpers/contract_helper"; +import { mapToBN } from "../helpers/contractHelper"; import { Metadata } from "../helpers/interfaces"; export class UnderlyingTokensClient extends AptosContractWrapperBaseClass { @@ -43,27 +44,14 @@ export class UnderlyingTokensClient extends AptosContractWrapperBaseClass { return this.sendTxAndAwaitResponse(UnderlyingMintFuncAddr, [to, amount.toString(), metadataAddress]); } - public async burn( - from: AccountAddress, - amount: BigNumber, - metadataAddress: AccountAddress, - ): Promise { - return this.sendTxAndAwaitResponse(UnderlyingMintFuncAddr, [from, amount.toString(), metadataAddress]); - } - - public async getMetadataBySymbol(symbol: string): Promise { + public async getMetadataBySymbol(symbol: string): Promise { const [resp] = await this.callViewMethod(UnderlyingGetMetadataBySymbolFuncAddr, [symbol]); - return (resp as Metadata).inner; - } - - public async getTokenAccountAddress(metadataAddress: AccountAddress): Promise { - const [resp] = await this.callViewMethod(UnderlyingGetTokenAccountAddressFuncAddr, [metadataAddress]); return AccountAddress.fromString((resp as Metadata).inner); } - public async balanceOf(owner: AccountAddress, metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(UnderlyingBalanceOfFuncAddr, [owner, metadataAddress])).map(mapToBN); - return resp; + public async getTokenAccountAddress(): Promise { + const [resp] = await this.callViewMethod(UnderlyingGetTokenAccountAddressFuncAddr, []); + return AccountAddress.fromString(resp as string); } public async supply(metadataAddress: AccountAddress): Promise { @@ -106,4 +94,14 @@ export class UnderlyingTokensClient extends AptosContractWrapperBaseClass { const [res] = (await this.callViewMethod(funcAddr, [metadataAddr])).map(mapToBN); return res; } + + public async balanceOf(owner: AccountAddress, metadataAddress: AccountAddress): Promise { + const [resp] = (await this.callViewMethod(UnderlyingBalanceOfFuncAddr, [owner, metadataAddress])).map(mapToBN); + return resp; + } + + public async getTokenAddress(symbol: string): Promise { + const [resp] = await this.callViewMethod(UnderlyingTokenAddressFuncAddr, [symbol]); + return AccountAddress.fromString(resp as string); + } } diff --git a/test-suites/clients/variableTokensClient.ts b/test-suites/clients/variableTokensClient.ts index 7701d65..9e233f2 100644 --- a/test-suites/clients/variableTokensClient.ts +++ b/test-suites/clients/variableTokensClient.ts @@ -2,22 +2,21 @@ import { AccountAddress, CommittedTransactionResponse, MoveFunctionId } from "@a import { BigNumber } from "ethers"; import { AptosContractWrapperBaseClass } from "./baseClass"; import { - VariableBalanceOfFuncAddr, VariableCreateTokenFuncAddr, VariableDecimalsFuncAddr, + VariableGetAssetMetadataFuncAddr, VariableGetMetadataBySymbolFuncAddr, VariableGetPreviousIndexFuncAddr, VariableGetRevisionFuncAddr, VariableGetScaledUserBalanceAndSupplyFuncAddr, - VariableGetTokenAccountAddressFuncAddr, - VariableMaximumFuncAddr, + VariableGetTokenAddressFuncAddr, + VariableGetUnderlyingAddressFuncAddr, VariableNameFuncAddr, - VariableScaleBalanceOfFuncAddr, - VariableScaleTotalSupplyFuncAddr, - VariableSupplyFuncAddr, + VariableScaledBalanceOfFuncAddr, + VariableScaledTotalSupplyFuncAddr, VariableSymbolFuncAddr, } from "../configs/tokens"; -import { mapToBN } from "../helpers/contract_helper"; +import { mapToBN } from "../helpers/contractHelper"; import { Metadata } from "../helpers/interfaces"; export class VariableTokensClient extends AptosContractWrapperBaseClass { @@ -29,7 +28,6 @@ export class VariableTokensClient extends AptosContractWrapperBaseClass { iconUri: string, projectUri: string, underlyingAsset: AccountAddress, - treasuryAddress: AccountAddress, ): Promise { return this.sendTxAndAwaitResponse(VariableCreateTokenFuncAddr, [ maximumSupply, @@ -39,7 +37,6 @@ export class VariableTokensClient extends AptosContractWrapperBaseClass { iconUri, projectUri, underlyingAsset, - treasuryAddress, ]); } @@ -48,33 +45,33 @@ export class VariableTokensClient extends AptosContractWrapperBaseClass { return resp as number; } - public async getMetadataBySymbol(symbol: string): Promise { - const [resp] = await this.callViewMethod(VariableGetMetadataBySymbolFuncAddr, [symbol]); - return (resp as Metadata).inner; + public async getMetadataBySymbol(owner: AccountAddress, symbol: string): Promise { + const [resp] = await this.callViewMethod(VariableGetMetadataBySymbolFuncAddr, [owner, symbol]); + return AccountAddress.fromString((resp as Metadata).inner); } - public async getTokenAccountAddress(): Promise { - const [resp] = await this.callViewMethod(VariableGetTokenAccountAddressFuncAddr, []); - return AccountAddress.fromString((resp as Metadata).inner); + public async getTokenAddress(owner: AccountAddress, symbol: string): Promise { + const [resp] = await this.callViewMethod(VariableGetTokenAddressFuncAddr, [owner, symbol]); + return AccountAddress.fromString(resp as string); } - public async balanceOf(owner: AccountAddress, metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(VariableBalanceOfFuncAddr, [owner, metadataAddress])).map(mapToBN); - return resp; + public async getAssetMetadata(owner: AccountAddress, symbol: string): Promise { + const [resp] = await this.callViewMethod(VariableGetAssetMetadataFuncAddr, [owner, symbol]); + return AccountAddress.fromString((resp as Metadata).inner); } - public async scaleBalanceOf(owner: AccountAddress, metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(VariableScaleBalanceOfFuncAddr, [owner, metadataAddress])).map(mapToBN); - return resp; + public async getUnderlyingAssetAddress(metadataAddress: AccountAddress): Promise { + const [resp] = await this.callViewMethod(VariableGetUnderlyingAddressFuncAddr, [metadataAddress]); + return AccountAddress.fromString(resp as string); } - public async supply(metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(VariableSupplyFuncAddr, [metadataAddress])).map(mapToBN); + public async scaledBalanceOf(owner: AccountAddress, metadataAddress: AccountAddress): Promise { + const [resp] = (await this.callViewMethod(VariableScaledBalanceOfFuncAddr, [owner, metadataAddress])).map(mapToBN); return resp; } - public async scaleTotalSupply(metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(VariableScaleTotalSupplyFuncAddr, [metadataAddress])).map(mapToBN); + public async scaledTotalSupplyOf(metadataAddress: AccountAddress): Promise { + const [resp] = (await this.callViewMethod(VariableScaledTotalSupplyFuncAddr, [metadataAddress])).map(mapToBN); return resp; } @@ -93,12 +90,6 @@ export class VariableTokensClient extends AptosContractWrapperBaseClass { return resp; } - // Get the maximum supply from the metadata object. - public async maximum(metadataAddress: AccountAddress): Promise { - const [resp] = (await this.callViewMethod(VariableMaximumFuncAddr, [metadataAddress])).map(mapToBN); - return resp; - } - // Get the name of the fungible asset from the metadata object. public async name(metadataAddress: AccountAddress): Promise { const [resp] = await this.callViewMethod(VariableNameFuncAddr, [metadataAddress]); @@ -117,12 +108,6 @@ export class VariableTokensClient extends AptosContractWrapperBaseClass { return resp; } - // get metadata address - public async getMetadataAddress(funcAddr: MoveFunctionId, coinName: string): Promise { - const [resp] = await this.callViewMethod(funcAddr, [coinName]); - return AccountAddress.fromString((resp as Metadata).inner); - } - // get decimals public async getDecimals(funcAddr: MoveFunctionId, metadataAddr: AccountAddress): Promise { const [res] = (await this.callViewMethod(funcAddr, [metadataAddr])).map(mapToBN); diff --git a/test-suites/configs/acl_manage.ts b/test-suites/configs/aclManage.ts similarity index 85% rename from test-suites/configs/acl_manage.ts rename to test-suites/configs/aclManage.ts index bdaaa0f..d15bb34 100644 --- a/test-suites/configs/acl_manage.ts +++ b/test-suites/configs/aclManage.ts @@ -14,8 +14,9 @@ export const AclManagerAccountAddress = AclManager.accountAddress.toString(); // Resource Func Addr export const hasRoleFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::has_role`; export const grantRoleFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::grant_role`; +export const renounceRoleFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::renounce_role`; export const revokeRoleFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::revoke_role`; -export const AddPoolAdminFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::add_pool_admin`; +export const addPoolAdminFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::add_pool_admin`; export const removePoolAdminFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::remove_pool_admin`; export const isPoolAdminFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::is_pool_admin`; export const addEmergencyAdminFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::add_emergency_admin`; @@ -39,6 +40,10 @@ export const getRiskAdminRoleFuncAddr: MoveFunctionId = `${AclManagerAccountAddr export const getFlashBorrowerRoleFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::get_flash_borrower_role`; export const getBridgeRoleFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::get_bridge_role`; export const getAssetListingAdminRoleFuncAddr: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::get_asset_listing_admin_role`; +export const grantDefaultAdminRole: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::grant_default_admin_role`; +export const defaultAdminRole: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::default_admin_role`; +export const getRoleAdmin: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::get_role_admin`; +export const setRoleAdmin: MoveFunctionId = `${AclManagerAccountAddress}::acl_manage::set_role_admin`; // Mock Account export const FLASH_BORROW_ADMIN_ROLE = "FLASH_BORROWER"; diff --git a/test-suites/configs/config.ts b/test-suites/configs/config.ts index bf88522..92bcdff 100644 --- a/test-suites/configs/config.ts +++ b/test-suites/configs/config.ts @@ -1,31 +1,11 @@ -import { Account, Ed25519Account } from "@aptos-labs/ts-sdk"; +import { Account, AccountAddress, Ed25519Account } from "@aptos-labs/ts-sdk"; import path from "path"; import dotenv from "dotenv"; -import { Transaction, View } from "../helpers/helper"; -import { aptos } from "./common"; -import { - AAAVE, - AAVE, - ADAI, - ATokenGetMetadataBySymbolFuncAddr, - AUSDC, - AWETH, - DAI, - getMetadataAddress, - UnderlyingGetMetadataBySymbolFuncAddr, - USDC, - VariableGetMetadataBySymbolFuncAddr, - VDAI, - WETH, -} from "./tokens"; -import { - AclManager, - addEmergencyAdminFuncAddr, - addRiskAdminFuncAddr, - isEmergencyAdminFuncAddr, - isRiskAdminFuncAddr, -} from "./acl_manage"; +import { AAAVE, AAVE, ADAI, AUSDC, AWETH, DAI, USDC, VDAI, WETH } from "./tokens"; +import { AclManager } from "./aclManage"; import { AptosProvider } from "../wrappers/aptosProvider"; +import { aTokens, underlyingTokens, varTokens } from "../scripts/createTokens"; +import { AclClient } from "../clients/aclClient"; dotenv.config(); @@ -33,29 +13,29 @@ interface TestEnv { emergencyAdmin: Ed25519Account; riskAdmin: Ed25519Account; users: Ed25519Account[]; - weth: string; - aWETH: string; - dai: string; - aDai: string; - aAave: string; - vDai: string; - aUsdc: string; - usdc: string; - aave: string; + weth: AccountAddress; + aWETH: AccountAddress; + dai: AccountAddress; + aDai: AccountAddress; + aAave: AccountAddress; + vDai: AccountAddress; + aUsdc: AccountAddress; + usdc: AccountAddress; + aave: AccountAddress; } export const testEnv: TestEnv = { emergencyAdmin: {} as Ed25519Account, riskAdmin: {} as Ed25519Account, users: [] as Ed25519Account[], - weth: "", - aWETH: "", - dai: "", - aDai: "", - vDai: "", - aUsdc: "", - usdc: "", - aave: "", + weth: AccountAddress.ZERO, + aWETH: AccountAddress.ZERO, + dai: AccountAddress.ZERO, + aDai: AccountAddress.ZERO, + vDai: AccountAddress.ZERO, + aUsdc: AccountAddress.ZERO, + usdc: AccountAddress.ZERO, + aave: AccountAddress.ZERO, } as TestEnv; const envPath = path.resolve(__dirname, "../../.env"); @@ -63,7 +43,7 @@ dotenv.config({ path: envPath }); const aptosProvider = new AptosProvider(); -export async function getAccounts(): Promise { +export async function getTestAccounts(): Promise { // 1. create accounts const accounts: Ed25519Account[] = []; const manager0 = Account.fromPrivateKey({ privateKey: aptosProvider.getProfilePrivateKeyByName("test_account_0") }); @@ -88,34 +68,33 @@ export async function getAccounts(): Promise { export async function initializeMakeSuite() { // account manage - testEnv.users = await getAccounts(); + testEnv.users = await getTestAccounts(); // eslint-disable-next-line prefer-destructuring testEnv.emergencyAdmin = testEnv.users[1]; // eslint-disable-next-line prefer-destructuring testEnv.riskAdmin = testEnv.users[2]; - // // token address - testEnv.aDai = await getMetadataAddress(ATokenGetMetadataBySymbolFuncAddr, ADAI); - testEnv.aUsdc = await getMetadataAddress(ATokenGetMetadataBySymbolFuncAddr, AUSDC); - testEnv.aWETH = await getMetadataAddress(ATokenGetMetadataBySymbolFuncAddr, AWETH); - testEnv.aAave = await getMetadataAddress(ATokenGetMetadataBySymbolFuncAddr, AAAVE); + testEnv.aDai = aTokens.find((token) => token.symbol === ADAI).metadataAddress; + testEnv.aUsdc = aTokens.find((token) => token.symbol === AUSDC).metadataAddress; + testEnv.aWETH = aTokens.find((token) => token.symbol === AWETH).metadataAddress; + testEnv.aAave = aTokens.find((token) => token.symbol === AAAVE).metadataAddress; - testEnv.vDai = await getMetadataAddress(VariableGetMetadataBySymbolFuncAddr, VDAI); + testEnv.vDai = varTokens.find((token) => token.symbol === VDAI).metadataAddress; - testEnv.dai = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, DAI); - testEnv.aave = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, AAVE); - testEnv.usdc = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, USDC); - testEnv.weth = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, WETH); + testEnv.dai = underlyingTokens.find((token) => token.symbol === DAI).accountAddress; + testEnv.aave = underlyingTokens.find((token) => token.symbol === AAVE).accountAddress; + testEnv.usdc = underlyingTokens.find((token) => token.symbol === USDC).accountAddress; + testEnv.weth = underlyingTokens.find((token) => token.symbol === WETH).accountAddress; + + const aclClient = new AclClient(aptosProvider, AclManager); // setup admins - const [isRiskAdmin] = await View(aptos, isRiskAdminFuncAddr, [testEnv.riskAdmin.accountAddress.toString()]); + const isRiskAdmin = await aclClient.isRiskAdmin(testEnv.riskAdmin.accountAddress); if (!isRiskAdmin) { - await Transaction(aptos, AclManager, addRiskAdminFuncAddr, [testEnv.riskAdmin.accountAddress.toString()]); + await aclClient.addAssetListingAdmin(testEnv.riskAdmin.accountAddress); } - const [isEmergencyAdmin] = await View(aptos, isEmergencyAdminFuncAddr, [ - testEnv.emergencyAdmin.accountAddress.toString(), - ]); + const isEmergencyAdmin = await aclClient.isEmergencyAdmin(testEnv.emergencyAdmin.accountAddress); if (!isEmergencyAdmin) { - await Transaction(aptos, AclManager, addEmergencyAdminFuncAddr, [testEnv.emergencyAdmin.accountAddress.toString()]); + await aclClient.addEmergencyAdmin(testEnv.emergencyAdmin.accountAddress); } } diff --git a/test-suites/configs/flash_loan.ts b/test-suites/configs/flashLoan.ts similarity index 80% rename from test-suites/configs/flash_loan.ts rename to test-suites/configs/flashLoan.ts index fcddef8..d95c9bb 100644 --- a/test-suites/configs/flash_loan.ts +++ b/test-suites/configs/flashLoan.ts @@ -14,9 +14,9 @@ export const FlashLoanManager = Account.fromPrivateKey({ export const FlashLoanManagerAccountAddress = FlashLoanManager.accountAddress.toString(); // Resource Func Addr -export const ExecuteFlashLoanComplexFuncAddr: MoveFunctionId = `${FlashLoanManagerAccountAddress}::flash_loan_logic::execute_flash_loan_complex`; +export const ExecuteFlashLoanFuncAddr: MoveFunctionId = `${FlashLoanManagerAccountAddress}::flash_loan_logic::flashloan`; export const PayFlashLoanComplexFuncAddr: MoveFunctionId = `${FlashLoanManagerAccountAddress}::flash_loan_logic::pay_flash_loan_complex`; -export const ExecuteFlashLoanSimpleFuncAddr: MoveFunctionId = `${FlashLoanManagerAccountAddress}::flash_loan_logic::execute_flash_loan_simple`; +export const ExecuteFlashLoanSimpleFuncAddr: MoveFunctionId = `${FlashLoanManagerAccountAddress}::flash_loan_logic::flash_loan_simple`; export const PayFlashLoanSimpleFuncAddr: MoveFunctionId = `${FlashLoanManagerAccountAddress}::flash_loan_logic::pay_flash_loan_simple`; // Mock Account diff --git a/test-suites/configs/large_packages.ts b/test-suites/configs/largePackages.ts similarity index 100% rename from test-suites/configs/large_packages.ts rename to test-suites/configs/largePackages.ts diff --git a/test-suites/configs/oracle.ts b/test-suites/configs/oracle.ts index 2538ca3..728fe35 100644 --- a/test-suites/configs/oracle.ts +++ b/test-suites/configs/oracle.ts @@ -16,5 +16,9 @@ export const OracleManagerAccountAddress = OracleManager.accountAddress.toString // Resource Func Addr export const GetAssetPriceFuncAddr: MoveFunctionId = `${OracleManagerAccountAddress}::oracle::get_asset_price`; export const SetAssetPriceFuncAddr: MoveFunctionId = `${OracleManagerAccountAddress}::oracle::set_asset_price`; +export const IsBorrowAllowedFuncAddr: MoveFunctionId = `${OracleManagerAccountAddress}::oracle_sentinel::is_borrow_allowed`; +export const IsLiquidationAllowedFuncAddr: MoveFunctionId = `${OracleManagerAccountAddress}::oracle_sentinel::is_liquidation_allowed`; +export const SetGracePeriodFuncAddr: MoveFunctionId = `${OracleManagerAccountAddress}::oracle_sentinel::set_grace_period`; +export const GetGracePeriodFuncAddr: MoveFunctionId = `${OracleManagerAccountAddress}::oracle_sentinel::get_grace_period`; // Mock Account diff --git a/test-suites/configs/pool.ts b/test-suites/configs/pool.ts index b306359..2c3c8e9 100644 --- a/test-suites/configs/pool.ts +++ b/test-suites/configs/pool.ts @@ -41,6 +41,10 @@ export const PoolGetBridgeProtocolFeeFuncAddr: MoveFunctionId = `${PoolManagerAc export const PoolGetFlashloanPremiumTotalFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool::get_flashloan_premium_total`; export const PoolGetFlashloanPremiumToProtocolFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool::get_flashloan_premium_to_protocol`; export const PoolMaxNumberReservesFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool::max_number_reserves`; +export const PoolScaledATokenTotalSupplyFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool::scaled_a_token_total_supply`; +export const PoolScaledATokenBalanceOfFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool::scaled_a_token_balance_of`; +export const PoolScaledVariableTokenTotalSupplyFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool::scaled_variable_token_total_supply`; +export const PoolScaledVariableTokenBalanceOfFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool::scaled_variable_token_balance_of`; /** * ------------------------------------------------------------------------- @@ -48,7 +52,7 @@ export const PoolMaxNumberReservesFuncAddr: MoveFunctionId = `${PoolManagerAccou * -------------------------------------------------------------------------= */ // Entry -export const PoolConfiguratorAddReservesFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::add_reserves`; +export const PoolConfiguratorInitReservesFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::init_reserves`; export const PoolConfiguratorDropReserveFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::drop_reserve`; export const PoolConfiguratorSetAssetEmodeCategoryFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::set_asset_emode_category`; export const PoolConfiguratorSetBorrowCapFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::set_borrow_cap`; @@ -70,7 +74,7 @@ export const PoolConfiguratorSetUnbackedMintCapFuncAddr: MoveFunctionId = `${Poo export const PoolConfiguratorUpdateBridgeProtocolFeeFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::update_bridge_protocol_fee`; export const PoolConfiguratorUpdateFlashloanPremiumToProtocolFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::update_flashloan_premium_to_protocol`; export const PoolConfiguratorUpdateFlashloanPremiumTotalFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::update_flashloan_premium_total`; -export const PoolConfiguratorReservesFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::configure_reserves`; +export const PoolConfiguratorConfigureReservesFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::configure_reserves`; // View export const PoolConfiguratorGetRevisionFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_configurator::get_revision`; @@ -134,6 +138,7 @@ export const GetUnbackedMintCapFuncAddr: MoveFunctionId = `${PoolManagerAccountA export const GetDebtCeilingFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_data_provider::get_debt_ceiling`; export const GetDebtCeilingDecimalsFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_data_provider::get_debt_ceiling_decimals`; export const GetReserveDataFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_data_provider::get_reserve_data`; +export const GetReserveDataAndReservesCountFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_data_provider::get_reserve_data_and_reserves_count`; export const GetATokenTotalSupplyFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_data_provider::get_a_token_total_supply`; export const GetTotalDebtFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_data_provider::get_total_debt`; export const GetUserReserveDataFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_data_provider::get_user_reserve_data`; @@ -142,7 +147,7 @@ export const GetFlashLoanEnabledFuncAddr: MoveFunctionId = `${PoolManagerAccount /** * ------------------------------------------------------------------------- - * pool data provider + * pool addresses provider * ------------------------------------------------------------------------- */ // View @@ -168,6 +173,30 @@ export const SetAclAdminFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress} export const SetPriceOracleSentinelFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_addresses_provider::set_price_oracle_sentinel`; export const SetPoolDataProviderFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::pool_addresses_provider::set_pool_data_provider`; +/** + * ------------------------------------------------------------------------- + * ui pool data provider + * ------------------------------------------------------------------------- + */ +// View +export const UiPoolDataProviderGetReservesListFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_pool_data_provider_v3::get_reserves_list`; +export const UiPoolDataProviderGetReservesDataFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_pool_data_provider_v3::get_reserves_data`; +export const UiPoolDataProviderGetUserReservesDataFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_pool_data_provider_v3::get_user_reserves_data`; +export const UiPoolDataProviderV3DataAddressFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_pool_data_provider_v3::ui_pool_data_provider_v3_data_address`; +export const UiPoolDataProviderV3DataObjectFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_pool_data_provider_v3::ui_pool_data_provider_v3_data_object`; + +/** + * ------------------------------------------------------------------------- + * ui incentives data provider + * ------------------------------------------------------------------------- + */ +// View +export const UiIncentivesDataProviderGetFullReservesIncentiveDataFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_incentive_data_provider_v3::get_full_reserves_incentive_data`; +export const UiIncentivesDataProviderGetReservesIncentivesDataFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_incentive_data_provider_v3::get_reserves_incentives_data`; +export const UiIncentivesDataProviderGetUserReservesIncentivesDataFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_incentive_data_provider_v3::get_user_reserves_incentives_data`; +export const UiIncentivesDataProviderV3DataAddressFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_pool_data_provider_v3::ui_incentive_data_provider_v3_data_address`; +export const UiIncentivesDataProviderV3DataObjectFuncAddr: MoveFunctionId = `${PoolManagerAccountAddress}::ui_pool_data_provider_v3::ui_incentive_data_provider_v3_data_object`; + // Asset Strategy Configurator export const strategyDAI = { // strategy: rateStrategies_1.rateStrategyStableTwo, diff --git a/test-suites/configs/supply_borrow.ts b/test-suites/configs/supplyBorrow.ts similarity index 94% rename from test-suites/configs/supply_borrow.ts rename to test-suites/configs/supplyBorrow.ts index bd1b003..db2309d 100644 --- a/test-suites/configs/supply_borrow.ts +++ b/test-suites/configs/supplyBorrow.ts @@ -20,7 +20,6 @@ export const SupplyFuncAddr: MoveFunctionId = `${SupplyBorrowManagerAccountAddre export const WithdrawFuncAddr: MoveFunctionId = `${SupplyBorrowManagerAccountAddress}::supply_logic::withdraw`; export const FinalizeTransferFuncAddr: MoveFunctionId = `${SupplyBorrowManagerAccountAddress}::supply_logic::finalize_transfer`; export const SetUserUseReserveAsCollateralFuncAddr: MoveFunctionId = `${SupplyBorrowManagerAccountAddress}::supply_logic::set_user_use_reserve_as_collateral`; -export const DepositFuncAddr: MoveFunctionId = `${SupplyBorrowManagerAccountAddress}::supply_logic::deposit`; // Borrow /// Entry diff --git a/test-suites/configs/tokens.ts b/test-suites/configs/tokens.ts index 753c227..7eeba66 100644 --- a/test-suites/configs/tokens.ts +++ b/test-suites/configs/tokens.ts @@ -1,4 +1,4 @@ -import { Account, MoveFunctionId } from "@aptos-labs/ts-sdk"; +import { Account, AccountAddress, MoveFunctionId } from "@aptos-labs/ts-sdk"; import path from "path"; import dotenv from "dotenv"; import { View } from "../helpers/helper"; @@ -37,35 +37,29 @@ export const VariableManagerAccountAddress = VariableManager.accountAddress.toSt // Resource Func Addr // Underlying Token -export const UnderlyingCreateTokenFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::create_token`; -export const UnderlyingGetMetadataBySymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::get_metadata_by_symbol`; -export const UnderlyingGetTokenAccountAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::get_token_account_address`; -export const UnderlyingMintFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::mint`; -export const UnderlyingSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::supply`; -export const UnderlyingMaximumFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::maximum`; -export const UnderlyingNameFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::name`; -export const UnderlyingSymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::symbol`; -export const UnderlyingDecimalsFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::decimals`; -export const UnderlyingBalanceOfFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::underlying_token_factory::balance_of`; +export const UnderlyingCreateTokenFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::create_token`; +export const UnderlyingGetMetadataBySymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::get_metadata_by_symbol`; +export const UnderlyingGetTokenAccountAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::get_token_account_address`; +export const UnderlyingMintFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::mint`; +export const UnderlyingSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::supply`; +export const UnderlyingMaximumFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::maximum`; +export const UnderlyingNameFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::name`; +export const UnderlyingSymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::symbol`; +export const UnderlyingDecimalsFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::decimals`; +export const UnderlyingBalanceOfFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::balance_of`; +export const UnderlyingTokenAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::mock_underlying_token_factory::token_address`; // A Token export const ATokenCreateTokenFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::create_token`; export const ATokenGetMetadataBySymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::get_metadata_by_symbol`; export const ATokenGetTokenAccountAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::get_token_account_address`; export const ATokenGetReserveTreasuryAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::get_reserve_treasury_address`; -export const ATokenMintToTreasuryAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::mint_to_treasury`; export const ATokenGetUnderlyingAssetAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::get_underlying_asset_address`; -export const ATokenTransferUnderlyingToFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::transfer_underlying_to`; -export const ATokenTransferOnLiquidationFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::transfer_on_liquidation`; -export const ATokenHandleRepaymentFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::handle_repayment`; -export const ATokenSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::supply`; -export const ATokenScaleTotalSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::scale_total_supply`; -export const ATokenMaximumFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::maximum`; +export const ATokenScaledTotalSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::scaled_total_supply`; export const ATokenNameFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::name`; export const ATokenSymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::symbol`; export const ATokenDecimalsFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::decimals`; -export const ATokenBalanceOfFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::balance_of`; -export const ATokenScaleBalanceOfFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::scale_balance_of`; +export const ATokenScaledBalanceOfFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::scaled_balance_of`; export const ATokenRescueTokensFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::rescue_tokens`; export const ATokenGetScaledUserBalanceAndSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::get_scaled_user_balance_and_supply`; export const ATokenGetGetPreviousIndexFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::get_previous_index`; @@ -74,20 +68,19 @@ export const ATokenTokenAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAc export const ATokenAssetMetadataFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::a_token_factory::asset_metadata`; // Variable Token -export const VariableCreateTokenFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::create_token`; -export const VariableGetMetadataBySymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::get_metadata_by_symbol`; -export const VariableGetTokenAccountAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::get_token_account_address`; -export const VariableSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::supply`; -export const VariableMaximumFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::maximum`; -export const VariableNameFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::name`; -export const VariableSymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::symbol`; -export const VariableDecimalsFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::decimals`; -export const VariableBalanceOfFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::balance_of`; -export const VariableScaleBalanceOfFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::scale_balance_of`; -export const VariableScaleTotalSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::scale_total_supply`; -export const VariableGetScaledUserBalanceAndSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::get_scaled_user_balance_and_supply`; -export const VariableGetPreviousIndexFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::get_previous_index`; -export const VariableGetRevisionFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_token_factory::get_revision`; +export const VariableCreateTokenFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::create_token`; +export const VariableGetMetadataBySymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::get_metadata_by_symbol`; +export const VariableGetTokenAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::token_address`; +export const VariableGetAssetMetadataFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::asset_metadata`; +export const VariableGetUnderlyingAddressFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::get_underlying_asset_address`; +export const VariableNameFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::name`; +export const VariableSymbolFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::symbol`; +export const VariableDecimalsFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::decimals`; +export const VariableScaledBalanceOfFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::scaled_balance_of`; +export const VariableScaledTotalSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::scaled_total_supply`; +export const VariableGetScaledUserBalanceAndSupplyFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::get_scaled_user_balance_and_supply`; +export const VariableGetPreviousIndexFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::get_previous_index`; +export const VariableGetRevisionFuncAddr: MoveFunctionId = `${AaveTokensManagerAccountAddress}::variable_debt_token_factory::get_revision`; // Tokens export const DAI = "DAI"; @@ -113,15 +106,13 @@ interface Metadata { } // get metadata address -export async function getMetadataAddress(funcAddr: MoveFunctionId, coinName: string) { - const res = await View(aptos, funcAddr, [coinName]); - return (res[0] as Metadata).inner; +export async function getMetadataAddress(funcAddr: MoveFunctionId, coinName: string): Promise { + const [resp] = await View(aptos, funcAddr, [coinName]); + return AccountAddress.fromString((resp as Metadata).inner); } // get decimals -export async function getDecimals(funcAddr: MoveFunctionId, metadataAddr: string) { +export async function getDecimals(funcAddr: MoveFunctionId, metadataAddr: AccountAddress): Promise { const res = await View(aptos, funcAddr, [metadataAddr]); return res[0] as number; } - -// Mock Account diff --git a/test-suites/helpers/constants.ts b/test-suites/helpers/constants.ts index b973bfa..3a9ece9 100644 --- a/test-suites/helpers/constants.ts +++ b/test-suites/helpers/constants.ts @@ -27,3 +27,7 @@ export const ONE_ADDRESS = "0x1"; export const MOCK_USD_PRICE_IN_WEI = "5848466240000000"; export const USD_ADDRESS = "0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96"; export const AAVE_REFERRAL = 0; +export const INTEREST_RATE_MODES = { + NONE: 0, + VARIABLE: 2, +}; diff --git a/test-suites/helpers/contract_helper.ts b/test-suites/helpers/contractHelper.ts similarity index 94% rename from test-suites/helpers/contract_helper.ts rename to test-suites/helpers/contractHelper.ts index 8532bef..75753c0 100644 --- a/test-suites/helpers/contract_helper.ts +++ b/test-suites/helpers/contractHelper.ts @@ -19,10 +19,10 @@ import { import { ATokenGetTokenAccountAddressFuncAddr, - ATokenScaleBalanceOfFuncAddr, + ATokenScaledBalanceOfFuncAddr, UnderlyingBalanceOfFuncAddr, UnderlyingSymbolFuncAddr, - VariableScaleTotalSupplyFuncAddr, + VariableScaledTotalSupplyFuncAddr, } from "../configs/tokens"; export function mapToBN(value: MoveValue): BigNumber { @@ -58,7 +58,7 @@ export const getReserveData = async (reserve: string): Promise => { const [aToken, vToken] = await View(aptos, GetReserveTokensAddressesFuncAddr, [reserve]); - const [scaledVariableDebt] = await View(aptos, VariableScaleTotalSupplyFuncAddr, [vToken.toString()]); + const [scaledVariableDebt] = await View(aptos, VariableScaledTotalSupplyFuncAddr, [vToken.toString()]); const [symbol] = await View(aptos, UnderlyingSymbolFuncAddr, [reserve]); const [aTokenAccount] = await View(aptos, ATokenGetTokenAccountAddressFuncAddr, [aToken.toString()]); @@ -99,7 +99,7 @@ export const getReserveData = async (reserve: string): Promise => { }; const getATokenUserData = async (reserve: string, user: string) => { const [aTokenAddress] = await View(aptos, GetReserveTokensAddressesFuncAddr, [reserve]); - const [scaledBalance] = await View(aptos, ATokenScaleBalanceOfFuncAddr, [user, aTokenAddress.toString()]); + const [scaledBalance] = await View(aptos, ATokenScaledBalanceOfFuncAddr, [user, aTokenAddress.toString()]); return scaledBalance.toString(); }; diff --git a/test-suites/package.json b/test-suites/package.json index 5e26cfc..e85ea36 100644 --- a/test-suites/package.json +++ b/test-suites/package.json @@ -6,10 +6,10 @@ "scripts": { "test": "jest", "test:cov": "jest --coverage", - "init-data": "ts-node scripts/init_data.ts", - "publish-pool-package": "ts-node scripts/publish_large_package.ts --module=../aave-core --profile=aave_pool", - "publish-acl-package": "ts-node scripts/publish_large_package.ts --module=../aave-core/aave-acl --profile=aave_acl", - "core-operations": "ts-node scripts/core_operations.ts", + "init-data": "ts-node scripts/initData.ts", + "publish-pool-package": "ts-node scripts/publishLargePackage.ts --module=../aave-core --profile=aave_pool", + "publish-acl-package": "ts-node scripts/publishLargePackage.ts --module=../aave-core/aave-acl --profile=aave_acl", + "core-operations": "ts-node scripts/coreOperations.ts", "lint": "eslint .", "lint:fix": "eslint --fix --ext=.js,.jsx,.ts .", "prettier": "prettier --check .", @@ -29,7 +29,8 @@ "test:liquidation": "jest liquidation.spec.ts", "test:liquidation-underlying": "jest liquidation-underlying.spec.ts", "test:logic": "pnpm test:standalone && pnpm test:pool-edge && pnpm test:config-edge && pnpm test:config && pnpm test:rescue-tokens && pnpm test:supply && pnpm test:withdraw && pnpm test:borrow && pnpm test:repay && pnpm test:repay-atoken && pnpm test:liquidation && pnpm test:liquidation-underlying", - "test:samples": "jest test/aave-oracle.spec.ts test/acl-manager.spec.ts test/atoken-delegation-aware.spec.ts test/atoken-event-accounting.spec.ts test/atoken-events.spec.ts test/atoken-modifiers.spec.ts test/atoken-permit.spec.ts test/configurator.spec.ts test/liquidation-atoken.spec.ts test/liquidation-edge.spec.ts test/liquidation-emode-interest.spec.ts test/liquidation-emode.spec.ts test/liquidation-with-fee.spec.ts test/liquidity-indexes.spec.ts test/ltv-validation.spec.ts test/mint-to-treasury.spec.ts test/pool-drop-reserve.spec.ts test/pool-edge.spec.ts test/pool-get-reserve-address-by-id.spec.ts test/rate-strategy.spec.ts test/supply.spec.ts test/variable-debt-token-events.spec.ts test/variable-debt-token.spec.ts test/wadraymath.spec.ts" + "test:samples": "jest test/aave-oracle.spec.ts test/acl-manager.spec.ts test/atoken-delegation-aware.spec.ts test/atoken-event-accounting.spec.ts test/atoken-events.spec.ts test/atoken-modifiers.spec.ts test/atoken-permit.spec.ts test/configurator.spec.ts test/liquidation-atoken.spec.ts test/liquidation-edge.spec.ts test/liquidation-emode-interest.spec.ts test/liquidation-emode.spec.ts test/liquidation-with-fee.spec.ts test/liquidity-indexes.spec.ts test/ltv-validation.spec.ts test/mint-to-treasury.spec.ts test/pool-drop-reserve.spec.ts test/pool-edge.spec.ts test/pool-get-reserve-address-by-id.spec.ts test/rate-strategy.spec.ts test/supply.spec.ts test/variable-debt-token-events.spec.ts test/variable-debt-token.spec.ts test/wadraymath.spec.ts", + "test:xxx": "jest test/acl-manager.spec.ts" }, "author": "AAVE", "license": "ISC", diff --git a/test-suites/scripts/config_reserves.ts b/test-suites/scripts/configReserves.ts similarity index 74% rename from test-suites/scripts/config_reserves.ts rename to test-suites/scripts/configReserves.ts index 33d42c3..591e2bf 100644 --- a/test-suites/scripts/config_reserves.ts +++ b/test-suites/scripts/configReserves.ts @@ -1,16 +1,10 @@ +/* eslint-disable no-console */ import * as dotenv from "dotenv"; -import { aptos } from "../configs/common"; - -import { Transaction } from "../helpers/helper"; -import { - PoolConfiguratorReservesFuncAddr, - PoolManager, - strategyAAVE, - strategyDAI, - strategyUSDC, - strategyWETH, -} from "../configs/pool"; -import { AAVE, DAI, getMetadataAddress, UnderlyingGetMetadataBySymbolFuncAddr, USDC, WETH } from "../configs/tokens"; +import { PoolManager, strategyAAVE, strategyDAI, strategyUSDC, strategyWETH } from "../configs/pool"; +import { AAVE, DAI, USDC, WETH } from "../configs/tokens"; +import { underlyingTokens } from "./createTokens"; +import { PoolClient } from "../clients/poolClient"; +import { AptosProvider } from "../wrappers/aptosProvider"; // eslint-disable-next-line import/no-commonjs const chalk = require("chalk"); @@ -18,12 +12,12 @@ const chalk = require("chalk"); dotenv.config(); async function getReserveInfo() { - // get assets address + // get assets addresses const assets = []; - const dai = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, DAI); - const weth = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, WETH); - const usdc = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, USDC); - const aave = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, AAVE); + const dai = underlyingTokens.find((token) => token.symbol === DAI).accountAddress; + const weth = underlyingTokens.find((token) => token.symbol === WETH).accountAddress; + const usdc = underlyingTokens.find((token) => token.symbol === USDC).accountAddress; + const aave = underlyingTokens.find((token) => token.symbol === AAVE).accountAddress; assets.push(dai); assets.push(weth); assets.push(usdc); @@ -111,8 +105,12 @@ export async function configReserves() { flashLoanEnabled, } = await getReserveInfo(); + // global aptos provider + const aptosProvider = new AptosProvider(); + const poolClient = new PoolClient(aptosProvider, PoolManager); + // configure the reserve - const txReceipt = await Transaction(aptos, PoolManager, PoolConfiguratorReservesFuncAddr, [ + const txReceipt = await poolClient.configureReserves( assets, baseLtv, liquidationThreshold, @@ -122,6 +120,6 @@ export async function configReserves() { supplyCap, borrowingEnabled, flashLoanEnabled, - ]); - console.log(chalk.green(`Reserve configured with tx hash = ${txReceipt.hash}`)); + ); + console.log(chalk.yellow(`Reserve configured with tx hash = ${txReceipt.hash}`)); } diff --git a/test-suites/scripts/core_operations.ts b/test-suites/scripts/coreOperations.ts similarity index 60% rename from test-suites/scripts/core_operations.ts rename to test-suites/scripts/coreOperations.ts index 6002dc1..522db09 100644 --- a/test-suites/scripts/core_operations.ts +++ b/test-suites/scripts/coreOperations.ts @@ -1,17 +1,19 @@ +/* eslint-disable no-console */ /* eslint-disable no-await-in-loop */ import dotenv from "dotenv"; import path from "path"; -import { Account, AccountAddress } from "@aptos-labs/ts-sdk"; import { BigNumber } from "ethers"; -import { AclClient } from "../clients/aclClient"; -import { ATokensClient } from "../clients/aTokensClient"; import { UnderlyingTokensClient } from "../clients/underlyingTokensClient"; -import { VariableTokensClient } from "../clients/variableTokensClient"; import { PoolClient } from "../clients/poolClient"; import { CoreClient } from "../clients/coreClient"; import { AptosProvider } from "../wrappers/aptosProvider"; -import { getAccounts } from "../configs/config"; -import { AAVE_REFERRAL } from "../helpers/constants"; +import { getTestAccounts } from "../configs/config"; +import { AAVE_REFERRAL, INTEREST_RATE_MODES } from "../helpers/constants"; +import { DAI, UnderlyingManager, WETH } from "../configs/tokens"; +import { PoolManager } from "../configs/pool"; +import { SupplyBorrowManager } from "../configs/supplyBorrow"; +import { OracleClient } from "../clients/oracleClient"; +import { OracleManager } from "../configs/oracle"; const envPath = path.resolve(__dirname, "../../.env"); dotenv.config({ path: envPath }); @@ -23,47 +25,45 @@ const chalk = require("chalk"); // global aptos provider const aptosProvider = new AptosProvider(); - // all atokens-related operations client - const AclManager = Account.fromPrivateKey({ privateKey: aptosProvider.getProfilePrivateKeyByName("aave_acl") }); - const aclClient = new AclClient(aptosProvider, AclManager); - - // all atokens-related operations client - const ATokenManager = Account.fromPrivateKey({ - privateKey: aptosProvider.getProfilePrivateKeyByName("a_tokens"), - }); - const aTokensClient = new ATokensClient(aptosProvider, ATokenManager); - // all underlying-tokens-related operations client - const UnderlyingManager = Account.fromPrivateKey({ - privateKey: aptosProvider.getProfilePrivateKeyByName("underlying_tokens"), - }); const underlyingTokensClient = new UnderlyingTokensClient(aptosProvider, UnderlyingManager); - // all variable-tokens-related operations client - const VariableManager = Account.fromPrivateKey({ - privateKey: aptosProvider.getProfilePrivateKeyByName("variable_tokens"), - }); - const variableTokensClient = new VariableTokensClient(aptosProvider, VariableManager); - // all pool-related operations client - const PoolManager = Account.fromPrivateKey({ - privateKey: aptosProvider.getProfilePrivateKeyByName("aave_pool"), - }); const poolClient = new PoolClient(aptosProvider, PoolManager); // all core-related operations client (supply, borrow, withdraw, repay) - const SupplyBorrowManager = Account.fromPrivateKey({ - privateKey: aptosProvider.getProfilePrivateKeyByName("aave_pool"), - }); const coreClient = new CoreClient(aptosProvider, SupplyBorrowManager); + // init oracle client + const oracleClient = new OracleClient(aptosProvider, OracleManager); + + // get all pool reserves + const allReserveUnderlyingTokens = await poolClient.getAllReservesTokens(); + + // ==============================SET POOL RESERVES PARAMS=============================================== + // NOTE: all other params come from the pool reserve configurations + for (const reserveUnderlyingToken of allReserveUnderlyingTokens) { + const underlyingSymbol = await underlyingTokensClient.symbol(reserveUnderlyingToken.tokenAddress); + // set reserve active + let txReceipt = await poolClient.setReserveActive(reserveUnderlyingToken.tokenAddress, true); + console.log( + chalk.yellow(`Activated pool reserve ${underlyingSymbol.toUpperCase()}. + Tx hash = ${txReceipt.hash}`), + ); + // set reserve not in frozen state + txReceipt = await poolClient.setReserveFreeze(reserveUnderlyingToken.tokenAddress, false); + console.log( + chalk.yellow(`Set reserve ${underlyingSymbol.toUpperCase()} not in frozen state. + Tx hash = ${txReceipt.hash}`), + ); + } + try { // ==============================MINT UNDERLYINGS FOR A TEST USER =============================================== console.log(chalk.yellow("---------------------------------------------")); console.log(chalk.cyan("Minting underlyings for test user...")); // get all reserve underlying tokens - const allReserveUnderlyingTokens = await poolClient.getAllReservesTokens(); - const supplier = (await getAccounts()).at(0); + const supplier = (await getTestAccounts()).at(0); const baseMintAmount = 1000; for (const reserveUnderlyingToken of allReserveUnderlyingTokens) { @@ -76,7 +76,7 @@ const chalk = require("chalk"); reserveUnderlyingToken.tokenAddress, ); console.log( - chalk.green(`Minted ${mintAmount.toString()} ${underlyingSymbol.toUpperCase()} to user account ${supplier.accountAddress.toString()}. + chalk.yellow(`Minted ${mintAmount.toString()} ${underlyingSymbol.toUpperCase()} to user account ${supplier.accountAddress.toString()}. Tx hash = ${txReceipt.hash}`), ); } @@ -89,43 +89,55 @@ const chalk = require("chalk"); for (const reserveUnderlyingToken of allReserveUnderlyingTokens) { const underlyingSymbol = await underlyingTokensClient.symbol(reserveUnderlyingToken.tokenAddress); const underlyingDecimals = await underlyingTokensClient.decimals(reserveUnderlyingToken.tokenAddress); - const depositAmount = BigNumber.from(10).pow(underlyingDecimals).mul(baseMintAmount).div(2); + const supplyAmount = BigNumber.from(10).pow(underlyingDecimals).mul(baseMintAmount).div(2); // set the supplier to be the signer const txReceipt = await coreClient.supply( reserveUnderlyingToken.tokenAddress, - depositAmount, + supplyAmount, supplier.accountAddress, AAVE_REFERRAL, ); console.log( - chalk.green(`User ${supplier.accountAddress.toString()} supplied ${depositAmount.toString()} ${underlyingSymbol.toUpperCase()} to the pool. + chalk.yellow(`User ${supplier.accountAddress.toString()} supplied ${supplyAmount.toString()} ${underlyingSymbol.toUpperCase()} to the pool. Tx hash = ${txReceipt.hash}`), ); } console.log(chalk.green("Supplying assets for test user finished successfully!")); + // ==============================ALLOW BORROWING ON ORACLE LEVEL=============================================== + + const isBorrowAllowed = await oracleClient.isBorrowAllowed(); + console.log(chalk.yellow("Is borrow allowed ? ", isBorrowAllowed)); + if (!isBorrowAllowed) { + const gracePeriod = BigNumber.from(1); + console.log(chalk.yellow(`Setting oracle grace period of ${gracePeriod.toNumber()} seconds`)); + const txReceipt = await oracleClient.setGracePeriod(gracePeriod); + console.log( + chalk.yellow(`Set grance period of ${gracePeriod.toNumber()} to the oracle. + Tx hash = ${txReceipt.hash}`), + ); + } + // ==============================USER BORROWS SOME ASSETS FROM POOL=============================================== console.log(chalk.yellow("---------------------------------------------")); console.log(chalk.cyan("Borrowing assets...")); - const underlyingsToBorrowSymbol = ["DAI", "WETH"]; + const underlyingsToBorrowSymbol = [DAI, WETH]; coreClient.setSigner(supplier); const borrowedAssetsWithAmounts = new Map(); for (const underlyingToBorrowSymbol of underlyingsToBorrowSymbol) { - const underlyingToBorrow = await underlyingTokensClient.getMetadataBySymbol(underlyingToBorrowSymbol); - const underlyingToBorrowAccAddress = AccountAddress.fromString(underlyingToBorrow); - const underlyingToBorrowDecimals = await underlyingTokensClient.decimals(underlyingToBorrowAccAddress); + const underlyingToBorrow = await underlyingTokensClient.getTokenAddress(underlyingToBorrowSymbol); + const underlyingToBorrowDecimals = await underlyingTokensClient.decimals(underlyingToBorrow); const borrowAmount = BigNumber.from(10).pow(underlyingToBorrowDecimals).mul(baseMintAmount).div(5); borrowedAssetsWithAmounts.set(underlyingToBorrowSymbol, borrowAmount); const txReceipt = await coreClient.borrow( - underlyingToBorrowAccAddress, - supplier.accountAddress, + underlyingToBorrow, borrowAmount, - 1, + INTEREST_RATE_MODES.VARIABLE, AAVE_REFERRAL, - true, + supplier.accountAddress, ); console.log( - chalk.green(`User ${supplier.accountAddress.toString()} borrowed ${borrowAmount.toString()} ${underlyingToBorrowSymbol.toUpperCase()} from the pool. + chalk.yellow(`User ${supplier.accountAddress.toString()} borrowed ${borrowAmount.toString()} ${underlyingToBorrowSymbol.toUpperCase()} from the pool. Tx hash = ${txReceipt.hash}`), ); } @@ -134,22 +146,15 @@ const chalk = require("chalk"); // ==============================USER WITHDRAWS SOME HIS BORROWED ASSET FROM POOL=============================================== console.log(chalk.yellow("---------------------------------------------")); console.log(chalk.cyan("Withdrawing assets...")); - const underlyingsToWithdrawSymbols = ["AAVE", "USDC"]; coreClient.setSigner(supplier); - for (const underlyingToWithdrawSymbol of underlyingsToWithdrawSymbols) { + for (const underlyingToWithdrawSymbol of underlyingsToBorrowSymbol) { const underlyingToWithdraw = await underlyingTokensClient.getMetadataBySymbol(underlyingToWithdrawSymbol); - const underlyingToWithdrawAccAddress = AccountAddress.fromString(underlyingToWithdraw); - const underlyingToWithdrawDecimals = await underlyingTokensClient.decimals(underlyingToWithdrawAccAddress); + const underlyingToWithdrawDecimals = await underlyingTokensClient.decimals(underlyingToWithdraw); const withdrawAmount = BigNumber.from(10).pow(underlyingToWithdrawDecimals).mul(baseMintAmount).div(5); - - const txReceipt = await coreClient.withdraw( - underlyingToWithdrawAccAddress, - withdrawAmount, - supplier.accountAddress, - ); + const txReceipt = await coreClient.withdraw(underlyingToWithdraw, withdrawAmount, supplier.accountAddress); console.log( - chalk.green(`User ${supplier.accountAddress.toString()} withdrew ${withdrawAmount.toString()} ${underlyingToWithdrawSymbol.toUpperCase()} from the pool. + chalk.yellow(`User ${supplier.accountAddress.toString()} withdrew ${withdrawAmount.toString()} ${underlyingToWithdrawSymbol.toUpperCase()} from the pool. Tx hash = ${txReceipt.hash}`), ); } @@ -162,21 +167,18 @@ const chalk = require("chalk"); for (const [key, borrowedValue] of borrowedAssetsWithAmounts.entries()) { const underlyingToRepay = await underlyingTokensClient.getMetadataBySymbol(key); - const underlyingToRepayAccAddress = AccountAddress.fromString(underlyingToRepay); - const txReceipt = await coreClient.repay( - underlyingToRepayAccAddress, + underlyingToRepay, borrowedValue, - 1, + INTEREST_RATE_MODES.VARIABLE, supplier.accountAddress, - false, ); console.log( - chalk.green(`User ${supplier.accountAddress.toString()} repayed ${borrowedValue.toString()} ${key.toUpperCase()} from the pool. + chalk.yellow(`User ${supplier.accountAddress.toString()} repayed ${borrowedValue.toString()} ${key.toUpperCase()} from the pool. Tx hash = ${txReceipt.hash}`), ); } - console.log(chalk.green("Repaying assets for test user finished successfully!")); + console.log(chalk.yellow("Repaying assets for test user finished successfully!")); } catch (ex) { console.error("Exception = ", ex); } diff --git a/test-suites/scripts/createRoles.ts b/test-suites/scripts/createRoles.ts new file mode 100644 index 0000000..e0dc96f --- /dev/null +++ b/test-suites/scripts/createRoles.ts @@ -0,0 +1,39 @@ +/* eslint-disable no-console */ +import { ATokenManager, UnderlyingManager, VariableManager } from "../configs/tokens"; +import { AclClient } from "../clients/aclClient"; + +import { AclManager } from "../configs/aclManage"; +import { PoolManager } from "../configs/pool"; +import { AptosProvider } from "../wrappers/aptosProvider"; + +// eslint-disable-next-line import/no-commonjs +const chalk = require("chalk"); + +export async function createRoles() { + const aptosProvider = new AptosProvider(); + const aclClient = new AclClient(aptosProvider, AclManager); + + // acl manager grants itself a default admin role + let txReceipt = await aclClient.grantDefaultRoleAdmin(); + console.log( + chalk.yellow( + `Added ${AclManager.accountAddress.toString()} as a default admin role with tx hash = ${txReceipt.hash}`, + ), + ); + + // add asset listing authorities + const assetListingAuthoritiesAddresses = [UnderlyingManager, VariableManager, ATokenManager].map( + (auth) => auth.accountAddress, + ); + for (const auth of assetListingAuthoritiesAddresses) { + // eslint-disable-next-line no-await-in-loop,@typescript-eslint/no-shadow + const txReceipt = await aclClient.addAssetListingAdmin(auth); + console.log(chalk.yellow(`Added ${auth} as an asset listing authority with tx hash = ${txReceipt.hash}`)); + } + + // create pool admin + txReceipt = await aclClient.addPoolAdmin(PoolManager.accountAddress); + console.log( + chalk.yellow(`Added ${PoolManager.accountAddress.toString()} as a pool admin with tx hash = ${txReceipt.hash}`), + ); +} diff --git a/test-suites/scripts/create_token.ts b/test-suites/scripts/createToken.ts similarity index 99% rename from test-suites/scripts/create_token.ts rename to test-suites/scripts/createToken.ts index b9c5a31..6fb4de4 100644 --- a/test-suites/scripts/create_token.ts +++ b/test-suites/scripts/createToken.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import { Transaction } from "../helpers/helper"; import { aptos } from "../configs/common"; import { diff --git a/test-suites/scripts/initData.ts b/test-suites/scripts/initData.ts new file mode 100644 index 0000000..34bfe9c --- /dev/null +++ b/test-suites/scripts/initData.ts @@ -0,0 +1,58 @@ +/* eslint-disable no-console */ +import * as dotenv from "dotenv"; +import { initReserveOraclePrice } from "./initOraclePrice"; +import { configReserves } from "./configReserves"; +import { initReserves } from "./initReserves"; +import { createTokens } from "./createTokens"; +import { createRoles } from "./createRoles"; +import { initInteresRates } from "./initInterestRate"; +import { initPoolAddressesProvider } from "./initPoolAddressesProvider"; + +dotenv.config(); + +// eslint-disable-next-line import/no-commonjs +const chalk = require("chalk"); + +(async () => { + // step1. create roles + console.log(chalk.yellow("---------------------------------------------")); + console.log(chalk.cyan("creating roles...")); + await createRoles(); + console.log(chalk.green("created roles successfully!")); + + // step2. create tokens + console.log(chalk.yellow("---------------------------------------------")); + console.log(chalk.cyan("creating tokens...")); + await createTokens(); + console.log(chalk.green("created tokens successfully!")); + + // step3. init interest rate strategies + console.log(chalk.yellow("---------------------------------------------")); + console.log(chalk.cyan("initializing interest rate strategies...")); + await initInteresRates(); + console.log(chalk.green("initialized interest rate strategies successfully!")); + + // step3. init reserves and interest rate strategies + console.log(chalk.yellow("---------------------------------------------")); + console.log(chalk.cyan("initializing reserves...")); + await initReserves(); + console.log(chalk.green("initialized reserves successfully!")); + + // step4. config reserves + console.log(chalk.yellow("---------------------------------------------")); + console.log(chalk.cyan("configuring reserves...")); + await configReserves(); + console.log(chalk.green("configured reserves successfully!")); + + // step5. config oracle price + console.log(chalk.yellow("---------------------------------------------")); + console.log(chalk.cyan("configuring reserve prices...")); + await initReserveOraclePrice(); + console.log(chalk.green("configured reserve prices successfully!")); + + // step6. config pool addresses provider + console.log(chalk.yellow("---------------------------------------------")); + console.log(chalk.cyan("configuring pool addresses provider...")); + await initPoolAddressesProvider(); + console.log(chalk.green("configured pool addresses provider successfully!")); +})(); diff --git a/test-suites/scripts/initInterestRate.ts b/test-suites/scripts/initInterestRate.ts new file mode 100644 index 0000000..6de14bb --- /dev/null +++ b/test-suites/scripts/initInterestRate.ts @@ -0,0 +1,28 @@ +/* eslint-disable no-console */ +/* eslint-disable no-await-in-loop */ +import { BigNumber } from "ethers"; +import { PoolManager, rateStrategyStableTwo } from "../configs/pool"; +import { AptosProvider } from "../wrappers/aptosProvider"; +import { PoolClient } from "../clients/poolClient"; +import { underlyingTokens } from "./createTokens"; + +// eslint-disable-next-line import/no-commonjs +const chalk = require("chalk"); + +export async function initInteresRates() { + // global aptos provider + const aptosProvider = new AptosProvider(); + const poolClient = new PoolClient(aptosProvider, PoolManager); + + // set interest rate strategy fr each reserve + for (const [, underlyingToken] of underlyingTokens.entries()) { + const txReceipt = await poolClient.setReserveInterestRateStrategy( + underlyingToken.accountAddress, + BigNumber.from(rateStrategyStableTwo.optimalUsageRatio), + BigNumber.from(rateStrategyStableTwo.baseVariableBorrowRate), + BigNumber.from(rateStrategyStableTwo.variableRateSlope1), + BigNumber.from(rateStrategyStableTwo.variableRateSlope2), + ); + console.log(chalk.yellow(`${underlyingToken.symbol} interest rate strategy set with tx hash`, txReceipt.hash)); + } +} diff --git a/test-suites/scripts/initOraclePrice.ts b/test-suites/scripts/initOraclePrice.ts new file mode 100644 index 0000000..471d499 --- /dev/null +++ b/test-suites/scripts/initOraclePrice.ts @@ -0,0 +1,25 @@ +/* eslint-disable no-console */ +/* eslint-disable no-await-in-loop */ +import { BigNumber } from "ethers"; +import { OracleManager } from "../configs/oracle"; +import { AptosProvider } from "../wrappers/aptosProvider"; +import { OracleClient } from "../clients/oracleClient"; +import { underlyingTokens } from "./createTokens"; + +// eslint-disable-next-line import/no-commonjs +const chalk = require("chalk"); + +export async function initReserveOraclePrice() { + // global aptos provider + const aptosProvider = new AptosProvider(); + const oracleClient = new OracleClient(aptosProvider, OracleManager); + + for (const [, underlyingToken] of underlyingTokens.entries()) { + const txReceipt = await oracleClient.setAssetPrice(underlyingToken.accountAddress, BigNumber.from(1)); + console.log( + chalk.yellow( + `Price set by oracle for underlying asset ${underlyingToken.symbol} with tx hash = ${txReceipt.hash}`, + ), + ); + } +} diff --git a/test-suites/scripts/initPoolAddressesProvider.ts b/test-suites/scripts/initPoolAddressesProvider.ts new file mode 100644 index 0000000..6fddc09 --- /dev/null +++ b/test-suites/scripts/initPoolAddressesProvider.ts @@ -0,0 +1,55 @@ +/* eslint-disable no-console */ +/* eslint-disable no-await-in-loop */ +import { AptosProvider } from "../wrappers/aptosProvider"; +import { PoolAddressesProviderClient } from "../clients/poolAddressesProviderClient"; +import { PoolManager } from "../configs/pool"; +import { AclManager } from "../configs/aclManage"; +import { OracleManager } from "../configs/oracle"; + +// eslint-disable-next-line import/no-commonjs +const chalk = require("chalk"); + +export async function initPoolAddressesProvider() { + // global aptos provider + const aptosProvider = new AptosProvider(); + const poolAddressesProviderClient = new PoolAddressesProviderClient(aptosProvider, PoolManager); + + let txReceipt = await poolAddressesProviderClient.setAclAdmin(AclManager.accountAddress); + console.log( + chalk.yellow(`Acl admin set to ${AclManager.accountAddress.toString()} with tx hash = ${txReceipt.hash}`), + ); + + txReceipt = await poolAddressesProviderClient.setAclManager(AclManager.accountAddress); + console.log( + chalk.yellow(`Acl maanger set to ${AclManager.accountAddress.toString()} with tx hash = ${txReceipt.hash}`), + ); + + txReceipt = await poolAddressesProviderClient.setPoolConfigurator(PoolManager.accountAddress); + console.log( + chalk.yellow(`Pool configurator set to ${PoolManager.accountAddress.toString()} with tx hash = ${txReceipt.hash}`), + ); + + txReceipt = await poolAddressesProviderClient.setPoolDataProvider(PoolManager.accountAddress); + console.log( + chalk.yellow(`Pool data provider set to ${PoolManager.accountAddress.toString()} with tx hash = ${txReceipt.hash}`), + ); + + txReceipt = await poolAddressesProviderClient.setPoolImpl(PoolManager.accountAddress); + console.log( + chalk.yellow( + `Pool implementation set to ${PoolManager.accountAddress.toString()} with tx hash = ${txReceipt.hash}`, + ), + ); + + txReceipt = await poolAddressesProviderClient.setPriceOracle(OracleManager.accountAddress); + console.log( + chalk.yellow(`Price Oracle set to ${OracleManager.accountAddress.toString()} with tx hash = ${txReceipt.hash}`), + ); + + txReceipt = await poolAddressesProviderClient.setPriceOracleSentinel(OracleManager.accountAddress); + console.log( + chalk.yellow( + `Price Oracle Sentinel set to ${OracleManager.accountAddress.toString()} with tx hash = ${txReceipt.hash}`, + ), + ); +} diff --git a/test-suites/scripts/initReserve.ts b/test-suites/scripts/initReserve.ts new file mode 100644 index 0000000..6d2afb1 --- /dev/null +++ b/test-suites/scripts/initReserve.ts @@ -0,0 +1,68 @@ +/* eslint-disable no-console */ +/* eslint-disable no-await-in-loop */ +import { BigNumber } from "ethers"; +import { PoolManager } from "../configs/pool"; +import { AptosProvider } from "../wrappers/aptosProvider"; +import { PoolClient } from "../clients/poolClient"; +import { aTokens, underlyingTokens, varTokens } from "./createTokens"; +import { ATokensClient } from "../clients/aTokensClient"; +import { VariableTokensClient } from "../clients/variableTokensClient"; + +// eslint-disable-next-line import/no-commonjs +const chalk = require("chalk"); + +export async function initReserves() { + // global aptos provider + const aptosProvider = new AptosProvider(); + const poolClient = new PoolClient(aptosProvider, PoolManager); + const aTokensClient = new ATokensClient(aptosProvider); + const varTokensClient = new VariableTokensClient(aptosProvider); + + // create reserves input data + const underlyingAssets = underlyingTokens.map((token) => token.accountAddress); + const underlyingAssetDecimals = underlyingTokens.map((token) => BigNumber.from(token.decimals).toNumber()); + const treasuries = underlyingTokens.map((token) => token.treasury); + const aTokenNames = aTokens.map((token) => token.name); + const aTokenSymbols = aTokens.map((token) => token.symbol); + const varTokenNames = varTokens.map((token) => token.name); + const varTokenSymbols = varTokens.map((token) => token.symbol); + + // init reserves + const txReceipt = await poolClient.initReserves( + underlyingAssets, + underlyingAssetDecimals, + treasuries, + aTokenNames, + aTokenSymbols, + varTokenNames, + varTokenSymbols, + ); + console.log(chalk.yellow("Reserves set with tx hash", txReceipt.hash)); + + // reserve atokens + for (const [, aToken] of aTokens.entries()) { + const aTokenMetadataAddress = await aTokensClient.getMetadataBySymbol(PoolManager.accountAddress, aToken.symbol); + console.log(chalk.yellow(`${aToken.symbol} atoken metadata address: `, aTokenMetadataAddress.toString())); + aToken.metadataAddress = aTokenMetadataAddress; + + const aTokenAddress = await aTokensClient.getTokenAddress(PoolManager.accountAddress, aToken.symbol); + console.log(chalk.yellow(`${aToken.symbol} atoken account address: `, aTokenAddress.toString())); + aToken.accountAddress = aTokenAddress; + } + + // reserve var debt tokens + for (const [, varToken] of varTokens.entries()) { + const varTokenMetadataAddress = await varTokensClient.getMetadataBySymbol( + PoolManager.accountAddress, + varToken.symbol, + ); + console.log( + chalk.yellow(`${varToken.symbol} var debt token metadata address: `, varTokenMetadataAddress.toString()), + ); + varToken.metadataAddress = varTokenMetadataAddress; + + const varTokenAddress = await varTokensClient.getTokenAddress(PoolManager.accountAddress, varToken.symbol); + console.log(chalk.yellow(`${varToken.symbol} var debt token account address: `, varTokenAddress.toString())); + varToken.accountAddress = varTokenAddress; + } +} diff --git a/test-suites/scripts/init_data.ts b/test-suites/scripts/init_data.ts deleted file mode 100644 index 4c30e8f..0000000 --- a/test-suites/scripts/init_data.ts +++ /dev/null @@ -1,43 +0,0 @@ -import * as dotenv from "dotenv"; -import { initReserveOraclePrice } from "./init_oracle_price"; -import { configReserves } from "./config_reserves"; -import { addReserves } from "./init_reserve"; -import { initReserveInterestRateStrategy } from "./init_interest_rate"; -import { createTokens } from "./create_token"; - -dotenv.config(); - -// eslint-disable-next-line import/no-commonjs -const chalk = require("chalk"); - -(async () => { - // step1. create tokens - console.log(chalk.yellow("---------------------------------------------")); - console.log(chalk.cyan("creating tokens...")); - await createTokens(); - console.log(chalk.green("created tokens successfully!")); - - // step2. init reserves - console.log(chalk.yellow("---------------------------------------------")); - console.log(chalk.cyan("creating reserves...")); - await addReserves(); - console.log(chalk.green("initiated reserves successfully!")); - - // step3. init reserve interest rate strategy - console.log(chalk.yellow("---------------------------------------------")); - console.log(chalk.cyan("initializing interest rate strategies...")); - await initReserveInterestRateStrategy(); - console.log(chalk.green("initialized reserve interest rate strategy successfully!")); - - // step4. config reserves - console.log(chalk.yellow("---------------------------------------------")); - console.log(chalk.cyan("configuring reserves...")); - await configReserves(); - console.log(chalk.green("configured reserves successfully!")); - - // step5. config oracle price - console.log(chalk.yellow("---------------------------------------------")); - console.log(chalk.cyan("configuring reserve prices...")); - await initReserveOraclePrice(); - console.log(chalk.green("configured reserve prices successfully!")); -})(); diff --git a/test-suites/scripts/init_interest_rate.ts b/test-suites/scripts/init_interest_rate.ts deleted file mode 100644 index f2b83a4..0000000 --- a/test-suites/scripts/init_interest_rate.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { PoolManager, rateStrategyStableTwo, SetReserveInterestRateStrategyFuncAddr } from "../configs/pool"; -import { Transaction } from "../helpers/helper"; -import { aptos } from "../configs/common"; -import { AAVE, DAI, getMetadataAddress, UnderlyingGetMetadataBySymbolFuncAddr, USDC, WETH } from "../configs/tokens"; - -// eslint-disable-next-line import/no-commonjs -const chalk = require("chalk"); - -export async function initReserveInterestRateStrategy() { - const params: string[] = [ - rateStrategyStableTwo.optimalUsageRatio, - rateStrategyStableTwo.baseVariableBorrowRate, - rateStrategyStableTwo.variableRateSlope1, - rateStrategyStableTwo.variableRateSlope2, - ]; - const daiAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, DAI); - const wethAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, WETH); - const usdcAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, USDC); - const aaveAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, AAVE); - - // config dai rate strategy - let txReceipt = await Transaction(aptos, PoolManager, SetReserveInterestRateStrategyFuncAddr, [ - daiAddress, - ...params, - ]); - console.log(chalk.green(`DAI Reserve Interest rate strategy set with tx hash = ${txReceipt.hash}`)); - - // config weth rate strategy - txReceipt = await Transaction(aptos, PoolManager, SetReserveInterestRateStrategyFuncAddr, [wethAddress, ...params]); - console.log(chalk.green(`WETH Reserve Interest rate strategy set with tx hash = ${txReceipt.hash}`)); - - // config usdc rate strategy - txReceipt = await Transaction(aptos, PoolManager, SetReserveInterestRateStrategyFuncAddr, [usdcAddress, ...params]); - console.log(chalk.green(`USDC Reserve Interest rate strategy set with tx hash = ${txReceipt.hash}`)); - - // config aave rate strategy - txReceipt = await Transaction(aptos, PoolManager, SetReserveInterestRateStrategyFuncAddr, [aaveAddress, ...params]); - console.log(chalk.green(`AAVE Reserve Interest rate strategy set with tx hash = ${txReceipt.hash}`)); -} diff --git a/test-suites/scripts/init_oracle_price.ts b/test-suites/scripts/init_oracle_price.ts deleted file mode 100644 index fac2f0b..0000000 --- a/test-suites/scripts/init_oracle_price.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { Transaction } from "../helpers/helper"; -import { aptos } from "../configs/common"; -import { AAVE, DAI, getMetadataAddress, UnderlyingGetMetadataBySymbolFuncAddr, USDC, WETH } from "../configs/tokens"; -import { OracleManager, SetAssetPriceFuncAddr } from "../configs/oracle"; - -// eslint-disable-next-line import/no-commonjs -const chalk = require("chalk"); - -export async function initReserveOraclePrice() { - const daiAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, DAI); - const wethAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, WETH); - const usdcAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, USDC); - const aaveAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, AAVE); - - // config dai price - let txReceipt = await Transaction(aptos, OracleManager, SetAssetPriceFuncAddr, [daiAddress, 1]); - console.log(chalk.green(`DAI price set with tx hash = ${txReceipt.hash}`)); - - // config weth price - txReceipt = await Transaction(aptos, OracleManager, SetAssetPriceFuncAddr, [wethAddress, 1]); - console.log(chalk.green(`WETH price set with tx hash = ${txReceipt.hash}`)); - - // config usdc price - txReceipt = await Transaction(aptos, OracleManager, SetAssetPriceFuncAddr, [usdcAddress, 1]); - console.log(chalk.green(`USDC price set with tx hash = ${txReceipt.hash}`)); - - // config aave price - txReceipt = await Transaction(aptos, OracleManager, SetAssetPriceFuncAddr, [aaveAddress, 1]); - console.log(chalk.green(`AAVE price set with tx hash = ${txReceipt.hash}`)); -} diff --git a/test-suites/scripts/init_reserve.ts b/test-suites/scripts/init_reserve.ts deleted file mode 100644 index 915aa87..0000000 --- a/test-suites/scripts/init_reserve.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { Transaction } from "../helpers/helper"; -import { PoolConfiguratorAddReservesFuncAddr, PoolManager } from "../configs/pool"; -import { - AAAVE, - AAVE, - ADAI, - ATokenGetMetadataBySymbolFuncAddr, - AUSDC, - AWETH, - DAI, - getDecimals, - getMetadataAddress, - UnderlyingDecimalsFuncAddr, - UnderlyingGetMetadataBySymbolFuncAddr, - USDC, - VAAVE, - VariableGetMetadataBySymbolFuncAddr, - VDAI, - VUSDC, - VWETH, - WETH, -} from "../configs/tokens"; -import { aptos } from "../configs/common"; -import { AclManager, AddPoolAdminFuncAddr } from "../configs/acl_manage"; -import { getAccounts, testEnv } from "../configs/config"; - -// eslint-disable-next-line import/no-commonjs -const chalk = require("chalk"); - -async function getTokenInfo() { - // underlying tokens - const underlying = []; - const decimals = []; - const daiAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, DAI); - const daiDecimals = await getDecimals(UnderlyingDecimalsFuncAddr, daiAddress); - underlying.push(daiAddress); - decimals.push(daiDecimals); - - const wethAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, WETH); - const wethDecimals = await getDecimals(UnderlyingDecimalsFuncAddr, wethAddress); - underlying.push(wethAddress); - decimals.push(wethDecimals); - - const usdcAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, USDC); - const usdcDecimals = await getDecimals(UnderlyingDecimalsFuncAddr, usdcAddress); - underlying.push(usdcAddress); - decimals.push(usdcDecimals); - - const aaveAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, AAVE); - const aaveDecimals = await getDecimals(UnderlyingDecimalsFuncAddr, aaveAddress); - underlying.push(aaveAddress); - decimals.push(aaveDecimals); - - // a tokens - const aTokens = []; - const adaiAddress = await getMetadataAddress(ATokenGetMetadataBySymbolFuncAddr, ADAI); - const awethAddress = await getMetadataAddress(ATokenGetMetadataBySymbolFuncAddr, AWETH); - const ausdcAddress = await getMetadataAddress(ATokenGetMetadataBySymbolFuncAddr, AUSDC); - const aaaveAddress = await getMetadataAddress(ATokenGetMetadataBySymbolFuncAddr, AAAVE); - aTokens.push(adaiAddress); - aTokens.push(awethAddress); - aTokens.push(ausdcAddress); - aTokens.push(aaaveAddress); - - // v tokens - const vTokens = []; - const vdaiAddress = await getMetadataAddress(VariableGetMetadataBySymbolFuncAddr, VDAI); - const vwethAddress = await getMetadataAddress(VariableGetMetadataBySymbolFuncAddr, VWETH); - const vusdcAddress = await getMetadataAddress(VariableGetMetadataBySymbolFuncAddr, VUSDC); - const vaaveAddress = await getMetadataAddress(VariableGetMetadataBySymbolFuncAddr, VAAVE); - vTokens.push(vdaiAddress); - vTokens.push(vwethAddress); - vTokens.push(vusdcAddress); - vTokens.push(vaaveAddress); - - return { - underlyingTokens: underlying, - aTokens, - vTokens, - decimals, - }; -} - -export async function addReserves() { - // step1. get token info - const { underlyingTokens, aTokens, vTokens, decimals } = await getTokenInfo(); - const userAccounts = await getAccounts(); - - // step2. Add pool admin - let txReceipt = await Transaction(aptos, AclManager, AddPoolAdminFuncAddr, [PoolManager.accountAddress.toString()]); - console.log(chalk.green(`Pool admin added with tx hash = ${txReceipt.hash}`)); - - // step3. Add the reserve - txReceipt = await Transaction(aptos, PoolManager, PoolConfiguratorAddReservesFuncAddr, [ - aTokens, - vTokens, - decimals, - underlyingTokens, - ]); - console.log(chalk.green(`Reserves added in batch to pool with tx hash = ${txReceipt.hash}`)); -} diff --git a/test-suites/scripts/publish_large_package.ts b/test-suites/scripts/publishLargePackage.ts similarity index 98% rename from test-suites/scripts/publish_large_package.ts rename to test-suites/scripts/publishLargePackage.ts index a6c35b0..e803ece 100644 --- a/test-suites/scripts/publish_large_package.ts +++ b/test-suites/scripts/publishLargePackage.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ /* eslint-disable no-await-in-loop */ import dotenv from "dotenv"; import path from "path"; diff --git a/test-suites/test/aave-oracle.spec.ts b/test-suites/test/aave-oracle.spec.ts index d7b3a2e..c8b15d1 100644 --- a/test-suites/test/aave-oracle.spec.ts +++ b/test-suites/test/aave-oracle.spec.ts @@ -1,8 +1,9 @@ +import { BigNumber } from "ethers"; import { initializeMakeSuite, testEnv } from "../configs/config"; -import { Transaction, View } from "../helpers/helper"; -import { aptos } from "../configs/common"; -import { GetAssetPriceFuncAddr, OracleManager, SetAssetPriceFuncAddr } from "../configs/oracle"; +import { OracleManager } from "../configs/oracle"; import { oneEther } from "../helpers/constants"; +import { OracleClient } from "../clients/oracleClient"; +import { AptosProvider } from "../wrappers/aptosProvider"; describe("AaveOracle", () => { beforeAll(async () => { @@ -13,19 +14,21 @@ describe("AaveOracle", () => { const { weth } = testEnv; const sourcePrice = "100"; - await Transaction(aptos, OracleManager, SetAssetPriceFuncAddr, [weth, sourcePrice]); + const oracleClient = new OracleClient(new AptosProvider(), OracleManager); + await oracleClient.setAssetPrice(weth, BigNumber.from(sourcePrice)); - const [newPrice] = await View(aptos, GetAssetPriceFuncAddr, [weth]); - expect(newPrice).toBe(sourcePrice); + const newPrice = await oracleClient.getAssetPrice(weth); + expect(newPrice.toString()).toBe(sourcePrice); }); it("Get price of asset with 0 price but non-zero fallback price", async () => { const { weth } = testEnv; const fallbackPrice = oneEther.toString(); - await Transaction(aptos, OracleManager, SetAssetPriceFuncAddr, [weth, fallbackPrice]); + const oracleClient = new OracleClient(new AptosProvider(), OracleManager); + await oracleClient.setAssetPrice(weth, BigNumber.from(fallbackPrice)); - const [newPrice] = await View(aptos, GetAssetPriceFuncAddr, [weth]); - expect(newPrice).toBe(fallbackPrice); + const newPrice = await oracleClient.getAssetPrice(weth); + expect(newPrice.toString()).toBe(fallbackPrice); }); }); diff --git a/test-suites/test/acl-manager.spec.ts b/test-suites/test/acl-manager.spec.ts index 169c257..2e67a54 100644 --- a/test-suites/test/acl-manager.spec.ts +++ b/test-suites/test/acl-manager.spec.ts @@ -6,7 +6,7 @@ import { addBridgeFuncAddr, addEmergencyAdminFuncAddr, addFlashBorrowerFuncAddr, - AddPoolAdminFuncAddr, + addPoolAdminFuncAddr, addRiskAdminFuncAddr, FLASH_BORROW_ADMIN_ROLE, getFlashBorrowerRoleFuncAddr, @@ -25,7 +25,7 @@ import { removePoolAdminFuncAddr, removeRiskAdminFuncAddr, revokeRoleFuncAddr, -} from "../configs/acl_manage"; +} from "../configs/aclManage"; import { initializeMakeSuite, testEnv } from "../configs/config"; describe("Access Control List Manager", () => { @@ -162,7 +162,7 @@ describe("Access Control List Manager", () => { const [isAdmin] = await View(aptos, isPoolAdminFuncAddr, [poolAdmin.accountAddress.toString()]); expect(isAdmin).toBe(false); - await Transaction(aptos, AclManager, AddPoolAdminFuncAddr, [poolAdmin.accountAddress.toString()]); + await Transaction(aptos, AclManager, addPoolAdminFuncAddr, [poolAdmin.accountAddress.toString()]); const [isAdminAfter] = await View(aptos, isPoolAdminFuncAddr, [poolAdmin.accountAddress.toString()]); expect(isAdminAfter).toBe(true); diff --git a/test-suites/test/borrow.spec.ts b/test-suites/test/borrow.spec.ts index 8151957..e467191 100644 --- a/test-suites/test/borrow.spec.ts +++ b/test-suites/test/borrow.spec.ts @@ -3,7 +3,7 @@ import { initializeMakeSuite, testEnv } from "../configs/config"; import { getDecimals, UnderlyingDecimalsFuncAddr, UnderlyingManager, UnderlyingMintFuncAddr } from "../configs/tokens"; import { Transaction, View } from "../helpers/helper"; import { aptos } from "../configs/common"; -import { BorrowFuncAddr, SupplyFuncAddr } from "../configs/supply_borrow"; +import { BorrowFuncAddr, SupplyFuncAddr } from "../configs/supplyBorrow"; import { GetReserveConfigurationDataFuncAddr, GetUserReserveDataFuncAddr, diff --git a/test-suites/test/configurator-edge.spec.ts b/test-suites/test/configurator-edge.spec.ts index 295fee3..d213cb2 100644 --- a/test-suites/test/configurator-edge.spec.ts +++ b/test-suites/test/configurator-edge.spec.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import { BigNumber } from "@ethersproject/bignumber"; import { initializeMakeSuite, testEnv } from "../configs/config"; import { Transaction, View } from "../helpers/helper"; diff --git a/test-suites/test/configurator.spec.ts b/test-suites/test/configurator.spec.ts index edc6a43..bbf7cfd 100644 --- a/test-suites/test/configurator.spec.ts +++ b/test-suites/test/configurator.spec.ts @@ -1,3 +1,4 @@ +import { AccountAddress } from "@aptos-labs/ts-sdk"; import { Transaction, View } from "../helpers/helper"; import { aptos } from "../configs/common"; import { @@ -30,7 +31,7 @@ import { PoolManager, strategyAAVE, } from "../configs/pool"; -import { AclManager, addAssetListingAdminFuncAddr, isAssetListingAdminFuncAddr } from "../configs/acl_manage"; +import { AclManager, addAssetListingAdminFuncAddr, isAssetListingAdminFuncAddr } from "../configs/aclManage"; import { initializeMakeSuite, testEnv } from "../configs/config"; import { RAY } from "../helpers/constants"; @@ -50,7 +51,7 @@ type ReserveConfigurationValues = { supplyCap: string; }; -const expectReserveConfigurationData = async (asset: string, values: ReserveConfigurationValues) => { +const expectReserveConfigurationData = async (asset: AccountAddress, values: ReserveConfigurationValues) => { const [decimals, , , , , , , isActive, isFrozen] = await View(aptos, GetReserveConfigurationDataFuncAddr, [asset]); // const [eModeCategory] = await View(aptos, GetReserveEModeCategoryFuncAddr, [asset]) // const [borrowCap, supplyCap] = await View(aptos, GetReserveCapsFuncAddr, [asset]) diff --git a/test-suites/test/liquidation-underlying.spec.ts b/test-suites/test/liquidation-underlying.spec.ts index a2a671d..19e7787 100644 --- a/test-suites/test/liquidation-underlying.spec.ts +++ b/test-suites/test/liquidation-underlying.spec.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import { BigNumber } from "@ethersproject/bignumber"; import { initializeMakeSuite, testEnv } from "../configs/config"; import { Transaction, View } from "../helpers/helper"; @@ -8,7 +9,7 @@ import { GetUserAccountDataFuncAddr, LiquidationCallFuncAddr, SupplyFuncAddr, -} from "../configs/supply_borrow"; +} from "../configs/supplyBorrow"; import { getDecimals, UnderlyingDecimalsFuncAddr, UnderlyingManager, UnderlyingMintFuncAddr } from "../configs/tokens"; import { GetAssetPriceFuncAddr, OracleManager, SetAssetPriceFuncAddr } from "../configs/oracle"; import "../helpers/wadraymath"; diff --git a/test-suites/test/liquidation.spec.ts b/test-suites/test/liquidation.spec.ts index f2213c3..b5c5fbf 100644 --- a/test-suites/test/liquidation.spec.ts +++ b/test-suites/test/liquidation.spec.ts @@ -3,7 +3,7 @@ import { getDecimals, UnderlyingDecimalsFuncAddr, UnderlyingManager, UnderlyingM import { Transaction } from "../helpers/helper"; import { aptos } from "../configs/common"; -import { BorrowFuncAddr, LiquidationCallFuncAddr, SupplyFuncAddr } from "../configs/supply_borrow"; +import { BorrowFuncAddr, LiquidationCallFuncAddr, SupplyFuncAddr } from "../configs/supplyBorrow"; import "../helpers/wadraymath"; describe("Liquidation Test", () => { diff --git a/test-suites/test/pool-edge.spec.ts b/test-suites/test/pool-edge.spec.ts index 1421d65..b040b54 100644 --- a/test-suites/test/pool-edge.spec.ts +++ b/test-suites/test/pool-edge.spec.ts @@ -6,7 +6,7 @@ import { PoolManager, PoolMaxNumberReservesFuncAddr, } from "../configs/pool"; -import { FinalizeTransferFuncAddr } from "../configs/supply_borrow"; +import { FinalizeTransferFuncAddr } from "../configs/supplyBorrow"; import { ZERO_ADDRESS } from "../helpers/constants"; describe("Pool: Edge cases", () => { diff --git a/test-suites/test/rate-strategy.spec.ts b/test-suites/test/rate-strategy.spec.ts index e69fcdd..a98ec2f 100644 --- a/test-suites/test/rate-strategy.spec.ts +++ b/test-suites/test/rate-strategy.spec.ts @@ -1,59 +1,52 @@ import { utils } from "ethers"; - import "../helpers/wadraymath"; - import { BigNumber } from "@ethersproject/bignumber"; -import { - CalculateInterestRatesFuncAddr, - GetBaseVariableBorrowRateFuncAddr, - GetGetMaxExcessUsageRatioFuncAddr, - GetGetOptimalUsageRatioFuncAddr, - GetMaxVariableBorrowRateFuncAddr, - GetVariableRateSlope1FuncAddr, - GetVariableRateSlope2FuncAddr, - PoolManager, - rateStrategyStableTwo, - SetReserveInterestRateStrategyFuncAddr, - strategyDAI, -} from "../configs/pool"; -import { Transaction, View } from "../helpers/helper"; -import { aptos } from "../configs/common"; - -import { - ADAI, - ATokenGetMetadataBySymbolFuncAddr, - DAI, - getMetadataAddress, - UnderlyingGetMetadataBySymbolFuncAddr, -} from "../configs/tokens"; +import { AccountAddress } from "@aptos-labs/ts-sdk"; +import { PoolManager, rateStrategyStableTwo, strategyDAI } from "../configs/pool"; +import { ADAI, ATokenManager, DAI, UnderlyingManager } from "../configs/tokens"; +import { AptosProvider } from "../wrappers/aptosProvider"; +import { ATokensClient } from "../clients/aTokensClient"; +import { UnderlyingTokensClient } from "../clients/underlyingTokensClient"; +import { PoolClient } from "../clients/poolClient"; describe("InterestRateStrategy", () => { - let daiAddress: string; - let aDaiAddress: string; + let daiAddress: AccountAddress; + let aDaiAddress: AccountAddress; + const aptosProvider = new AptosProvider(); + let aTokensClient: ATokensClient; + let underlyingTokensClient: UnderlyingTokensClient; + let poolClient: PoolClient; beforeAll(async () => { - daiAddress = await getMetadataAddress(UnderlyingGetMetadataBySymbolFuncAddr, DAI); - aDaiAddress = await getMetadataAddress(ATokenGetMetadataBySymbolFuncAddr, ADAI); + aTokensClient = new ATokensClient(aptosProvider, ATokenManager); + underlyingTokensClient = new UnderlyingTokensClient(aptosProvider, UnderlyingManager); + poolClient = new PoolClient(aptosProvider, PoolManager); + daiAddress = await underlyingTokensClient.getMetadataBySymbol(DAI); + aDaiAddress = await aTokensClient.getMetadataBySymbol(PoolManager.accountAddress, ADAI); }); it("Checks getters", async () => { - const [optimalUsageRatio] = await View(aptos, GetGetOptimalUsageRatioFuncAddr, [daiAddress]); - expect(optimalUsageRatio).toBe(rateStrategyStableTwo.optimalUsageRatio); + const optimalUsageRatio = await poolClient.getOptimalUsageRatio(daiAddress); + expect(optimalUsageRatio.toString()).toBe(rateStrategyStableTwo.optimalUsageRatio); - const [maxExcessUsageRatio] = await View(aptos, GetGetMaxExcessUsageRatioFuncAddr, [daiAddress]); - expect(maxExcessUsageRatio).toBe(BigNumber.from(1).ray().sub(rateStrategyStableTwo.optimalUsageRatio).toString()); + const maxExcessUsageRatio = await poolClient.getMaxExcessUsageRatio(daiAddress); + expect(maxExcessUsageRatio.toString()).toBe( + BigNumber.from(1).ray().sub(rateStrategyStableTwo.optimalUsageRatio).toString(), + ); - const [baseVariableBorrowRate] = await View(aptos, GetBaseVariableBorrowRateFuncAddr, [daiAddress]); - expect(baseVariableBorrowRate).toBe(rateStrategyStableTwo.baseVariableBorrowRate); + const baseVariableBorrowRate = await poolClient.getBaseVariableBorrowRate(daiAddress); + expect(baseVariableBorrowRate.toString()).toBe( + BigNumber.from(rateStrategyStableTwo.baseVariableBorrowRate).toString(), + ); - const [variableRateSlope1] = await View(aptos, GetVariableRateSlope1FuncAddr, [daiAddress]); - expect(variableRateSlope1).toBe(rateStrategyStableTwo.variableRateSlope1); + const variableRateSlope1 = await poolClient.getVariableRateSlope1(daiAddress); + expect(variableRateSlope1.toString()).toBe(BigNumber.from(rateStrategyStableTwo.variableRateSlope1).toString()); - const [variableRateSlope2] = await View(aptos, GetVariableRateSlope2FuncAddr, [daiAddress]); - expect(variableRateSlope2).toBe(rateStrategyStableTwo.variableRateSlope2); + const variableRateSlope2 = await poolClient.getVariableRateSlope2(daiAddress); + expect(variableRateSlope2.toString()).toBe(BigNumber.from(rateStrategyStableTwo.variableRateSlope2).toString()); - const [maxVariableBorrowRate] = await View(aptos, GetMaxVariableBorrowRateFuncAddr, [daiAddress]); - expect(maxVariableBorrowRate).toBe( + const maxVariableBorrowRate = await poolClient.getMaxVariableBorrowRate(daiAddress); + expect(maxVariableBorrowRate.toString()).toBe( BigNumber.from(rateStrategyStableTwo.baseVariableBorrowRate) .add(BigNumber.from(rateStrategyStableTwo.variableRateSlope1)) .add(BigNumber.from(rateStrategyStableTwo.variableRateSlope2)) @@ -62,23 +55,29 @@ describe("InterestRateStrategy", () => { }); it("Checks rates at 0% usage ratio, empty reserve", async () => { - const params: string[] = ["0", "0", "0", "0", strategyDAI.reserveFactor, daiAddress, aDaiAddress]; - const [currentLiquidityRate, currentVariableBorrowRate] = await View(aptos, CalculateInterestRatesFuncAddr, [ - ...params, - ]); - expect(currentLiquidityRate).toBe("0"); - expect(currentVariableBorrowRate).toBe("0"); + const { currentLiquidityRate, currentVariableBorrowRate } = await poolClient.calculateInterestRates( + BigNumber.from(0), + BigNumber.from(0), + BigNumber.from(0), + BigNumber.from(0), + BigNumber.from(strategyDAI.reserveFactor), + daiAddress, + aDaiAddress, + ); + + expect(currentLiquidityRate.toString()).toBe("0"); + expect(currentVariableBorrowRate.toString()).toBe("0"); }); it("Deploy an interest rate strategy with optimalUsageRatio out of range (expect revert)", async () => { - const params: string[] = [ - utils.parseUnits("1.0", 28).toString(), - rateStrategyStableTwo.baseVariableBorrowRate, - rateStrategyStableTwo.variableRateSlope1, - rateStrategyStableTwo.variableRateSlope2, - ]; try { - await Transaction(aptos, PoolManager, SetReserveInterestRateStrategyFuncAddr, [daiAddress, ...params]); + await poolClient.setReserveInterestRateStrategy( + daiAddress, + utils.parseUnits("1.0", 28), + BigNumber.from(rateStrategyStableTwo.baseVariableBorrowRate), + BigNumber.from(rateStrategyStableTwo.variableRateSlope1), + BigNumber.from(rateStrategyStableTwo.variableRateSlope2), + ); } catch (err) { expect(err.toString().includes("default_reserve_interest_rate_strategy: 0x53")).toBe(true); } diff --git a/test-suites/test/repay-atoken.spec.ts b/test-suites/test/repay-atoken.spec.ts index dc76a70..f49d6e6 100644 --- a/test-suites/test/repay-atoken.spec.ts +++ b/test-suites/test/repay-atoken.spec.ts @@ -1,7 +1,7 @@ import { initializeMakeSuite, testEnv } from "../configs/config"; import { Transaction } from "../helpers/helper"; import { aptos } from "../configs/common"; -import { BorrowFuncAddr, RepayWithATokensFuncAddr, SupplyFuncAddr } from "../configs/supply_borrow"; +import { BorrowFuncAddr, RepayWithATokensFuncAddr, SupplyFuncAddr } from "../configs/supplyBorrow"; import { getDecimals, UnderlyingDecimalsFuncAddr, UnderlyingManager, UnderlyingMintFuncAddr } from "../configs/tokens"; import "../helpers/wadraymath"; diff --git a/test-suites/test/repay.spec.ts b/test-suites/test/repay.spec.ts index ba9e462..d63c48d 100644 --- a/test-suites/test/repay.spec.ts +++ b/test-suites/test/repay.spec.ts @@ -1,7 +1,7 @@ import { initializeMakeSuite, testEnv } from "../configs/config"; import { Transaction, View } from "../helpers/helper"; import { aptos } from "../configs/common"; -import { BorrowFuncAddr, RepayFuncAddr, SupplyFuncAddr } from "../configs/supply_borrow"; +import { BorrowFuncAddr, RepayFuncAddr, SupplyFuncAddr } from "../configs/supplyBorrow"; import { getDecimals, UnderlyingDecimalsFuncAddr, UnderlyingManager, UnderlyingMintFuncAddr } from "../configs/tokens"; import { GetReserveConfigurationDataFuncAddr, diff --git a/test-suites/test/supply.spec.ts b/test-suites/test/supply.spec.ts index cbb188d..6c410d9 100644 --- a/test-suites/test/supply.spec.ts +++ b/test-suites/test/supply.spec.ts @@ -2,7 +2,7 @@ import { BigNumber } from "@ethersproject/bignumber"; import { initializeMakeSuite, testEnv } from "../configs/config"; import { Transaction, View } from "../helpers/helper"; import { aptos } from "../configs/common"; -import { SupplyFuncAddr } from "../configs/supply_borrow"; +import { SupplyFuncAddr } from "../configs/supplyBorrow"; import { GetReserveConfigurationDataFuncAddr, PoolConfiguratorSetReserveActiveFuncAddr, diff --git a/test-suites/test/wadraymath.spec.ts b/test-suites/test/wadraymath.spec.ts index c3476a4..46ebb6c 100644 --- a/test-suites/test/wadraymath.spec.ts +++ b/test-suites/test/wadraymath.spec.ts @@ -27,7 +27,7 @@ describe("WadRayMath", () => { const tooLargeA = BigNumber.from(MAX_UINT_AMOUNT).sub(HALF_WAD).div(b).add(1); expect(() => { - const result = wrapper.wadMul(tooLargeA, b).toNumber(); + wrapper.wadMul(tooLargeA, b).toNumber(); }).toThrow(); }); @@ -41,11 +41,11 @@ describe("WadRayMath", () => { const tooLargeA = BigNumber.from(MAX_UINT_AMOUNT).sub(halfB).div(WAD).add(1); expect(() => { - const result = wrapper.wadDiv(tooLargeA, b).toNumber(); + wrapper.wadDiv(tooLargeA, b).toNumber(); }).toThrow(); expect(() => { - const result = wrapper.wadDiv(a, BigNumber.from(0)).toNumber(); + wrapper.wadDiv(a, BigNumber.from(0)).toNumber(); }).toThrow(); }); @@ -59,7 +59,7 @@ describe("WadRayMath", () => { const tooLargeA = BigNumber.from(MAX_UINT_AMOUNT).sub(HALF_RAY).div(b).add(1); expect(() => { - const result = wrapper.rayMul(tooLargeA, b).toNumber(); + wrapper.rayMul(tooLargeA, b).toNumber(); }).toThrow(); }); @@ -72,10 +72,10 @@ describe("WadRayMath", () => { const halfB = b.div(2); const tooLargeA = BigNumber.from(MAX_UINT_AMOUNT).sub(halfB).div(RAY).add(1); expect(() => { - const result = wrapper.rayDiv(tooLargeA, b).toNumber(); + wrapper.rayDiv(tooLargeA, b).toNumber(); }).toThrow(); expect(() => { - const result = wrapper.rayDiv(a, BigNumber.from(0)).toNumber(); + wrapper.rayDiv(a, BigNumber.from(0)).toNumber(); }).toThrow(); }); @@ -102,7 +102,7 @@ describe("WadRayMath", () => { const ratio = BigNumber.from(10).pow(9); const tooLarge = BigNumber.from(MAX_UINT_AMOUNT).div(ratio).add(1); expect(() => { - const result = wrapper.wadToRay(tooLarge).toNumber(); + wrapper.wadToRay(tooLarge).toNumber(); }).toThrow(); }); }); diff --git a/test-suites/test/withdraw.spec.ts b/test-suites/test/withdraw.spec.ts index 3354301..59ba65e 100644 --- a/test-suites/test/withdraw.spec.ts +++ b/test-suites/test/withdraw.spec.ts @@ -1,30 +1,46 @@ import { BigNumber } from "@ethersproject/bignumber"; +import { Ed25519Account } from "@aptos-labs/ts-sdk"; import { initializeMakeSuite, testEnv } from "../configs/config"; import { Transaction, View } from "../helpers/helper"; import { aptos } from "../configs/common"; -import { BorrowFuncAddr, GetUserAccountDataFuncAddr, SupplyFuncAddr, WithdrawFuncAddr } from "../configs/supply_borrow"; import { - ATokenBalanceOfFuncAddr, - ATokenScaleBalanceOfFuncAddr, - getDecimals, - UnderlyingDecimalsFuncAddr, - UnderlyingManager, - UnderlyingMintFuncAddr, -} from "../configs/tokens"; -import { GetReserveDataFuncAddr, PoolConfiguratorSetReservePauseFuncAddr } from "../configs/pool"; + BorrowFuncAddr, + GetUserAccountDataFuncAddr, + SupplyBorrowManager, + SupplyFuncAddr, + WithdrawFuncAddr, +} from "../configs/supplyBorrow"; +import { ATokenManager, UnderlyingManager, UnderlyingMintFuncAddr } from "../configs/tokens"; +import { PoolManager } from "../configs/pool"; import "../helpers/wadraymath"; import { GetAssetPriceFuncAddr, OracleManager, SetAssetPriceFuncAddr } from "../configs/oracle"; +import { CoreClient } from "../clients/coreClient"; +import { AptosProvider } from "../wrappers/aptosProvider"; +import { ATokensClient } from "../clients/aTokensClient"; +import { UnderlyingTokensClient } from "../clients/underlyingTokensClient"; +import { PoolClient } from "../clients/poolClient"; + +const aptosProvider = new AptosProvider(); +let coreClient: CoreClient; +let aTokensClient: ATokensClient; +let underlyingTokensClient: UnderlyingTokensClient; +let poolClient: PoolClient; describe("Withdraw Test", () => { beforeAll(async () => { await initializeMakeSuite(); + coreClient = new CoreClient(aptosProvider, SupplyBorrowManager); + aTokensClient = new ATokensClient(aptosProvider, ATokenManager); + underlyingTokensClient = new UnderlyingTokensClient(aptosProvider, UnderlyingManager); + poolClient = new PoolClient(aptosProvider, PoolManager); }); it("validateWithdraw() when amount == 0 (revert expected)", async () => { const { users, dai } = testEnv; const user = users[0]; try { - await Transaction(aptos, user, WithdrawFuncAddr, [dai, 0, user.accountAddress.toString()]); + coreClient.setSigner(user as Ed25519Account); + await coreClient.withdraw(dai, BigNumber.from(0), user.accountAddress); } catch (err) { expect(err.toString().includes("validation_logic: 0x1a")).toBe(true); } @@ -33,14 +49,14 @@ describe("Withdraw Test", () => { it("validateWithdraw() when amount > user balance (revert expected)", async () => { const { users, dai, aDai } = testEnv; const user = users[0]; - const [scaleUserBalance] = await View(aptos, ATokenScaleBalanceOfFuncAddr, [user.accountAddress.toString(), aDai]); - const [, , , , , , liquidityIndex, ,] = await View(aptos, GetReserveDataFuncAddr, [dai]); - const userBalance = BigNumber.from(scaleUserBalance).rayMul(BigNumber.from(liquidityIndex)); - const newUserBalance = userBalance.add(1000000000000000).toString(); + const scaleUserBalance = await aTokensClient.scaledBalanceOf(user.accountAddress, aDai); + const { reserveLiquidityIndex } = await poolClient.getReserveData2(dai); + const userBalance = scaleUserBalance.rayMul(BigNumber.from(reserveLiquidityIndex)); + const newUserBalance = userBalance.add(1000000000000000); try { - await Transaction(aptos, user, WithdrawFuncAddr, [dai, newUserBalance, user.accountAddress.toString()]); + coreClient.setSigner(user as Ed25519Account); + await coreClient.withdraw(dai, newUserBalance, user.accountAddress); } catch (err) { - // console.log("err:", err.toString()) expect(err.toString().includes("validation_logic: 0x20")).toBe(true); } }); @@ -48,24 +64,26 @@ describe("Withdraw Test", () => { it("validateWithdraw() when reserve is paused (revert expected)", async () => { const { users, dai } = testEnv; const user = users[0]; - const daiDecimals = await getDecimals(UnderlyingDecimalsFuncAddr, dai); + const daiDecimals = (await underlyingTokensClient.decimals(dai)).toNumber(); const daiDepositAmount = 1000 * 10 ** daiDecimals; - await Transaction(aptos, UnderlyingManager, UnderlyingMintFuncAddr, [ - user.accountAddress.toString(), - daiDepositAmount, - dai, - ]); + + await underlyingTokensClient.mint(user.accountAddress, BigNumber.from(daiDepositAmount), dai); const user1 = users[1]; - await Transaction(aptos, user1, PoolConfiguratorSetReservePauseFuncAddr, [dai, true]); + + coreClient.setSigner(user1 as Ed25519Account); + await poolClient.setReservePause(dai, true); const daiWithdrawAmount = 100 * 10 ** daiDecimals; try { - await Transaction(aptos, user, WithdrawFuncAddr, [dai, daiWithdrawAmount, user.accountAddress.toString()]); + coreClient.setSigner(user as Ed25519Account); + await coreClient.withdraw(dai, BigNumber.from(daiWithdrawAmount), user.accountAddress); } catch (err) { expect(err.toString().includes("validation_logic: 0x1d")).toBe(true); } - await Transaction(aptos, user1, PoolConfiguratorSetReservePauseFuncAddr, [dai, false]); + + coreClient.setSigner(user1 as Ed25519Account); + await poolClient.setReservePause(dai, false); }); it("validateHFAndLtv() with HF < 1 (revert expected)", async () => { @@ -80,7 +98,7 @@ describe("Withdraw Test", () => { await Transaction(aptos, OracleManager, SetAssetPriceFuncAddr, [dai, 1]); // dai mint - const daiDecimals = await getDecimals(UnderlyingDecimalsFuncAddr, dai); + const daiDecimals = (await underlyingTokensClient.decimals(dai)).toNumber(); const daiDepositAmount = 1000 * 10 ** daiDecimals; await Transaction(aptos, UnderlyingManager, UnderlyingMintFuncAddr, [ user.accountAddress.toString(), @@ -92,7 +110,7 @@ describe("Withdraw Test", () => { await Transaction(aptos, user, SupplyFuncAddr, [dai, daiDepositAmount, user.accountAddress.toString(), 0]); // usdc mint - const usdcDecimals = await getDecimals(UnderlyingDecimalsFuncAddr, usdc); + const usdcDecimals = (await underlyingTokensClient.decimals(usdc)).toNumber(); const usdcDepositAmount = 1000 * 10 ** usdcDecimals; await Transaction(aptos, UnderlyingManager, UnderlyingMintFuncAddr, [ usdcProvider.accountAddress.toString(), @@ -141,7 +159,7 @@ describe("Withdraw Test", () => { users: [user1], } = testEnv; // dai mint - const daiDecimals = await getDecimals(UnderlyingDecimalsFuncAddr, dai); + const daiDecimals = (await underlyingTokensClient.decimals(dai)).toNumber(); const daiDepositAmount = 10 * 10 ** daiDecimals; await Transaction(aptos, UnderlyingManager, UnderlyingMintFuncAddr, [ user1.accountAddress.toString(), @@ -152,11 +170,12 @@ describe("Withdraw Test", () => { // dai supply await Transaction(aptos, user1, SupplyFuncAddr, [dai, daiDepositAmount, user1.accountAddress.toString(), 0]); - const [aDaiBalanceBefore] = await View(aptos, ATokenBalanceOfFuncAddr, [user1.accountAddress.toString(), aDai]); + const aDaiBalanceBefore = await aTokensClient.scaledBalanceOf(user1.accountAddress, aDai); const withdrawnAmount = 10 ** daiDecimals; - await Transaction(aptos, user1, WithdrawFuncAddr, [dai, withdrawnAmount, user1.accountAddress.toString()]); + coreClient.setSigner(user1); + await coreClient.withdraw(dai, BigNumber.from(withdrawnAmount), user1.accountAddress); - const [aDaiBalanceAfter] = await View(aptos, ATokenBalanceOfFuncAddr, [user1.accountAddress.toString(), aDai]); - expect(aDaiBalanceAfter).toBe(((aDaiBalanceBefore as number) - withdrawnAmount).toString()); + const aDaiBalanceAfter = await aTokensClient.scaledBalanceOf(user1.accountAddress, aDai); + expect(aDaiBalanceAfter.toString()).toBe(aDaiBalanceBefore.sub(withdrawnAmount).toString()); }); }); diff --git a/test-suites/tsconfig.json b/test-suites/tsconfig.json index f2be68a..fb646f8 100644 --- a/test-suites/tsconfig.json +++ b/test-suites/tsconfig.json @@ -63,6 +63,7 @@ "./node_modules/@types/node/index.d.ts" ], "include": [ + "./clients/**/*.ts", "./configs/**/*.ts", "./helpers/**/*.ts", "./scripts/**/*.ts", diff --git a/test-suites/wrappers/packagePublisher.ts b/test-suites/wrappers/packagePublisher.ts index 76efd60..0d868e0 100644 --- a/test-suites/wrappers/packagePublisher.ts +++ b/test-suites/wrappers/packagePublisher.ts @@ -1,3 +1,6 @@ +/* eslint-disable no-console */ +/* eslint-disable no-plusplus */ +/* eslint-disable no-await-in-loop */ import { Account, CommittedTransactionResponse, Ed25519Account } from "@aptos-labs/ts-sdk"; import fs from "fs"; import path from "path"; @@ -94,10 +97,9 @@ export class PackagePublisher { if (totalSize < PackagePublisher.MAX_TRANSACTION_SIZE) { console.log(`Publishing small package of size ${totalSize}...`); return this.publishSmallPackage(metadataBytes, moduleBytecode); - } - console.log(`Publishing large package of size ${totalSize}...`); - return this.publishLargePackage(metadataBytes, moduleBytecode); - + } + console.log(`Publishing large package of size ${totalSize}...`); + return this.publishLargePackage(metadataBytes, moduleBytecode); } // ====================== SMALL PACKAGES ==================== //