diff --git a/.codespellrc b/.codespellrc
new file mode 100644
index 0000000..5319ec6
--- /dev/null
+++ b/.codespellrc
@@ -0,0 +1,3 @@
+[codespell]
+skip = .git,target,pnpm-lock.yaml
+ignore-words-list = crate,ser,ratatui,ot,tE
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..b1ef9e7
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,107 @@
+# Logs
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# Runtime data
+pids
+*.pid
+*.seed
+*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage
+.coverage_map.mvcov
+.trace
+
+# nyc test coverage
+.nyc_output
+
+# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+bower_components
+
+# node-waf configuration
+.lock-wscript
+
+# Compiled binary addons (https://nodejs.org/api/addons.html)
+build/Release
+
+# Dependency directories
+node_modules/
+**/node_modules
+jspm_packages/
+
+# TypeScript v1 declaration files
+typings/
+
+# Optional npm cache directory
+.npm
+
+# Optional eslint cache
+.eslintcache
+
+# Optional REPL history
+.node_repl_history
+
+# Output of 'npm pack'
+*.tgz
+
+# Yarn Integrity file
+.yarn-integrity
+
+# next.js build output
+.next
+
+# build folder
+dist/
+
+# bundle files
+bundle.*
+
+# docs files
+docs
+
+# Misc
+.DS_Store
+
+# Generated by Cargo
+# will have compiled files and executables
+debug/
+target/
+
+# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
+# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
+#Cargo.lock
+
+# These are backup files generated by rustfmt
+**/*.rs.bk
+
+# MSVC Windows builds of rustc generate these, which store debugging information
+*.pdb
+
+.idea
+.github
+**/build
+
+# Move coverage testing
+*.mvcov
+*.trace
+gas-profiling
+
+# some aave-core specific stuff
+aave-core/build/
+aave-core/doc/
+aave-core/tests/
+test-suites/node_modules/
+
+# local aptos and gh
+.aptos/
+.github/
diff --git a/.env.local b/.env.local
deleted file mode 100644
index 9d11029..0000000
--- a/.env.local
+++ /dev/null
@@ -1,11 +0,0 @@
-#APTOS_CONFIG_FILE= ... put your aptos config file path here e.g. /home/user/.aptos/config.yaml or leave uncommented if default workspace...
-APTOS_NETWORK=local
-ARTIFACTS_LEVEL=all
-DEFAULT_FUND_AMOUNT=100000000
-DEFAULT_FUNDER_PRIVATE_KEY=0x676c8aee36857acbcfa02c6953958236a695a6520967ca49cddd7547f5a958ce
-
-# pyth oracle (irrelevant for local)
-PYTH_HERMES_URL=https://hermes-beta.pyth.network
-PYTH_CONTRACT_ACCOUNT=0x0000000000000000000000000000000000000000000000000000000000000000
-PYTH_DEPLOYER_ACCOUNT=0x0000000000000000000000000000000000000000000000000000000000000000
-PYTH_WORMHOLE=0x0000000000000000000000000000000000000000000000000000000000000000
diff --git a/.env.template b/.env.template
new file mode 100644
index 0000000..0cd2783
--- /dev/null
+++ b/.env.template
@@ -0,0 +1,31 @@
+#APTOS_CONFIG_FILE= ... put your aptos config file path here e.g. /home/user/.aptos/config.yaml or leave uncommented if default workspace...
+APTOS_NETWORK=local
+UPGRADE_CONTRACTS=false
+ARTIFACTS_LEVEL=all
+DEFAULT_FUND_AMOUNT=40000000
+CHAINLINK_DATA_FEEDS ?= 0x100
+CHAINLINK_PLATFORM ?= 0x200
+
+# aave profiles private keys
+AAVE_ACL_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+AAVE_CONFIG_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+AAVE_MATH_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+AAVE_RATE_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+AAVE_ORACLE_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+AAVE_POOL_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+A_TOKENS_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+UNDERLYING_TOKENS_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+VARIABLE_TOKENS_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+AAVE_LARGE_PACKAGES_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+AAVE_DATA_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+AAVE_DATA_FEEDS_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+AAVE_PLATFORM_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+DEFAULT_FUNDER_PRIVATE_KEY=[YOUR PROFILE ACCOUNT PRIVATE KEY]
+
+# test profiles private keys
+TEST_ACCOUNT_0_PRIVATE_KEY=[ADDRESS]
+TEST_ACCOUNT_1_PRIVATE_KEY=[ADDRESS]
+TEST_ACCOUNT_2_PRIVATE_KEY=[ADDRESS]
+TEST_ACCOUNT_3_PRIVATE_KEY=[ADDRESS]
+TEST_ACCOUNT_4_PRIVATE_KEY=[ADDRESS]
+TEST_ACCOUNT_5_PRIVATE_KEY=[ADDRESS]
diff --git a/.env.tesnet b/.env.tesnet
deleted file mode 100644
index 43a0997..0000000
--- a/.env.tesnet
+++ /dev/null
@@ -1,11 +0,0 @@
-#APTOS_CONFIG_FILE= ... put your aptos config file path here e.g. /home/user/.aptos/config.yaml or leave uncommented if default workspace...
-APTOS_NETWORK=testnet
-ARTIFACTS_LEVEL=none
-DEFAULT_FUND_AMOUNT=20000000
-DEFAULT_FUNDER_PRIVATE_KEY=[YOUR FUNDER ACCOUNT PRIVATE KEY]
-
-# pyth oracle (for testnet and devnet)
-PYTH_HERMES_URL=https://hermes-beta.pyth.network
-PYTH_CONTRACT_ACCOUNT=0x7e783b349d3e89cf5931af376ebeadbfab855b3fa239b7ada8f5a92fbea6b387
-PYTH_DEPLOYER_ACCOUNT=0xb31e712b26fd295357355f6845e77c888298636609e93bc9b05f0f604049f434
-PYTH_WORMHOLE=0x5bc11445584a763c1fa7ed39081f1b920954da14e04b32440cba863d03e19625
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 0000000..22d03f5
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1 @@
+* @tyshko5 @meng-xu-cs @matchv @mpsc0x
diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml
new file mode 100644
index 0000000..592bf5e
--- /dev/null
+++ b/.github/actionlint.yaml
@@ -0,0 +1,3 @@
+self-hosted-runner:
+ labels:
+ - Larger-Github-Runners
diff --git a/.github/workflows/apterly-audit.yml b/.github/workflows/apterly-audit.yml
new file mode 100644
index 0000000..dfa17e8
--- /dev/null
+++ b/.github/workflows/apterly-audit.yml
@@ -0,0 +1,35 @@
+name: npm audit
+
+on:
+ pull_request:
+ merge_group:
+ branches:
+ - main
+ schedule:
+ - cron: '0 10 * * *'
+
+jobs:
+ npm-scan:
+ name: apterly
+ runs-on: Larger-Github-Runners
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - name: Install pnpm
+ uses: pnpm/action-setup@v4
+ with:
+ version: 9
+ run_install: false
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+ working-directory: apterly
+
+ - name: Run pnpm audit
+ run: pnpm audit
+ working-directory: apterly
diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml
index 5e965e6..94377e4 100644
--- a/.github/workflows/doc.yml
+++ b/.github/workflows/doc.yml
@@ -3,15 +3,21 @@ name: Build Aptos Documentation
on:
pull_request:
merge_group:
- branches: [main]
+ branches:
+ - main
env:
CARGO_TERM_COLOR: always
+ GITHUB_ACTIONS: true
+ APTOS_NETWORK: local
+ UPGRADE_CONTRACTS: false
+ ARTIFACTS_LEVEL: all
+ DEFAULT_FUNDER_PRIVATE_KEY: ${{ secrets.GH_DEFAULT_FUNDER_PRIVATE_KEY }}
jobs:
build-docs:
name: Build Aptos Documentation
- runs-on: ubuntu-latest
+ runs-on: Larger-Github-Runners
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
@@ -25,7 +31,11 @@ jobs:
echo $! > aptos_serve_pid.txt
- name: Wait for Aptos Local Testnet to be ready
run: sleep 20
+ - name: Set Local Aptos Workspace Config
+ run: make set-workspace-config
+ - name: Init Local Aptos Workspace Config
+ run: make init-workspace-config
- name: Run Aptos Create Profiles
run: make init-profiles
- name: Create Documentation
- run: make doc-all
\ No newline at end of file
+ run: make doc-all
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index a3e4fcf..86379c1 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -1,47 +1,147 @@
-name: Fmt Linter
+name: lint
on:
pull_request:
merge_group:
- branches: [main]
+ branches:
+ - main
env:
CARGO_TERM_COLOR: always
+ CLICOLOR: true
+ CI: true
GITHUB_ACTIONS: true
APTOS_NETWORK: local
+ UPGRADE_CONTRACTS: false
ARTIFACTS_LEVEL: all
- PYTH_HERMES_URL: https://hermes-beta.pyth.network
- PYTH_CONTRACT_ACCOUNT: 0x0
- PYTH_DEPLOYER_ACCOUNT: 0x0
- PYTH_WORMHOLE: 0x0
+ AAVE_LARGE_PACKAGES_PRIVATE_KEY: ${{ secrets.GH_AAVE_LARGE_PACKAGES_PRIVATE_KEY }} # temp hack: remove after large packages is no longer needed
jobs:
+ pre-commit:
+ name: Pre-commit
+ runs-on: Larger-Github-Runners
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check workflow files
+ uses: docker://rhysd/actionlint:latest
+ env:
+ SHELLCHECK_OPTS: --exclude=SC2086,SC2129,SC2046
+ with:
+ args: -color
+
+ - uses: actions/checkout@v4
+
+ - name: Install dependencies
+ run: |
+ sudo apt-get update -y
+ sudo apt-get install -y libudev-dev
+
+ - name: Install Aptos CLI
+ run: |
+ curl -fsSL "https://aptos.dev/scripts/install_cli.py" | python3
+ aptos --version
+ aptos update movefmt
+ echo 'Adding movefmt to PATH'
+ echo "$HOME/.aptos/bin" >> $GITHUB_PATH
+
+ - name: Install Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - uses: pnpm/action-setup@v4
+ name: Install pnpm
+ with:
+ version: 9
+ run_install: true
+
+ - name: Install Python
+ uses: actions/setup-python@v5
+
+ - name: Run Pre Commit
+ uses: pre-commit/action@v3.0.1
+
fmt:
- name: Run fmt
- runs-on: ubuntu-latest
+ name: fmt
+ runs-on: Larger-Github-Runners
env:
RUST_BACKTRACE: 1
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
- - uses: dtolnay/rust-toolchain@stable
- - uses: taiki-e/install-action@nextest
+ - name: Install dependencies
+ run: |
+ sudo apt-get update -y
+ sudo apt-get install -y libudev-dev
+
+ - name: Install Aptos CLI
+ run: |
+ curl -fsSL "https://aptos.dev/scripts/install_cli.py" | python3
+ aptos --version
+ aptos update movefmt
+ echo 'Adding movefmt to PATH'
+ echo "$HOME/.aptos/bin" >> $GITHUB_PATH
+
+ - name: Install Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - uses: pnpm/action-setup@v4
+ name: Install pnpm
+ with:
+ version: 9
+ run_install: true
+
+ - name: Fmt Project
+ run: make fmt
- - uses: Swatinem/rust-cache@v2
+ codespell:
+ runs-on: Larger-Github-Runners
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v4
+ - uses: codespell-project/actions-codespell@v2
with:
- cache-on-failure: true
+ skip: "*.json"
+
+ lint:
+ name: lint
+ needs:
+ - codespell
+ runs-on: Larger-Github-Runners
+ steps:
+ - uses: actions/checkout@v4
- name: Install dependencies
run: |
sudo apt-get update -y
sudo apt-get install -y libudev-dev
- - name: Run Install move fmt
+ - name: Install Aptos CLI
run: |
- cargo install --git https://github.com/movebit/movefmt --branch develop movefmt
- export PATH=~/.cargo/bin:$PATH
+ curl -fsSL "https://aptos.dev/scripts/install_cli.py" | python3
+ aptos --version
+ aptos update movefmt
+ echo 'Adding movefmt to PATH'
+ echo "$HOME/.aptos/bin" >> $GITHUB_PATH
+
+ - name: Install Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - uses: pnpm/action-setup@v4
+ name: Install pnpm
+ with:
+ version: 9
+ run_install: true
+
+ - name: Install Python
+ uses: actions/setup-python@v5
- - name: Run fmt check on all files
- run: make fmt-all
\ No newline at end of file
+ - name: Lint project
+ run: make lint
diff --git a/.github/workflows/test-suite-audit.yml b/.github/workflows/test-suite-audit.yml
new file mode 100644
index 0000000..499112c
--- /dev/null
+++ b/.github/workflows/test-suite-audit.yml
@@ -0,0 +1,35 @@
+name: npm audit
+
+on:
+ pull_request:
+ merge_group:
+ branches:
+ - main
+ schedule:
+ - cron: '0 10 * * *'
+
+jobs:
+ npm-scan:
+ name: test-suite
+ runs-on: Larger-Github-Runners
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - name: Install pnpm
+ uses: pnpm/action-setup@v4
+ with:
+ version: 9
+ run_install: false
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+ working-directory: test-suites
+
+ - name: Run pnpm audit
+ run: pnpm audit
+ working-directory: test-suites
diff --git a/.github/workflows/testnet-deployment.yml b/.github/workflows/testnet-deployment.yml
index 33a5ef5..b447b09 100644
--- a/.github/workflows/testnet-deployment.yml
+++ b/.github/workflows/testnet-deployment.yml
@@ -19,26 +19,55 @@ on:
options:
- 'true'
- 'false'
-
-env:
- CARGO_TERM_COLOR: always
- GITHUB_ACTIONS: true
- APTOS_NETWORK: testnet
- ARTIFACTS_LEVEL: none
- DEFAULT_FUND_AMOUNT: 40000000
- PYTH_HERMES_URL: https://hermes-beta.pyth.network
- PYTH_CONTRACT_ACCOUNT: 0x0000000000000000000000000000000000000000000000000000000000000000
- PYTH_DEPLOYER_ACCOUNT: 0x0000000000000000000000000000000000000000000000000000000000000000
- PYTH_WORMHOLE: 0x0000000000000000000000000000000000000000000000000000000000000000
+ upgradeContracts:
+ description: 'Upgrade Contracts'
+ required: true
+ default: 'false'
+ type: choice
+ options:
+ - 'true'
+ - 'false'
jobs:
testnet-deployment:
name: Deploy protocol on Testnet
- runs-on: ubuntu-latest
+ runs-on: Larger-Github-Runners
timeout-minutes: 60
env:
- DEFAULT_FUNDER_PRIVATE_KEY: ${{ secrets.GH_DEFAULT_FUNDER_PRIVATE_KEY }}
+ # common settings
+ CARGO_TERM_COLOR: always
+ GITHUB_ACTIONS: true
+ ARTIFACTS_LEVEL: all
+ DEFAULT_FUND_AMOUNT: 40000000
APTOS_NETWORK: ${{ github.event.inputs.network }}
+ UPGRADE_CONTRACTS: ${{ github.event.inputs.upgradeContracts }}
+
+ # external profiles
+ CHAINLINK_DATA_FEEDS: ${{ secrets.GH_CHAINLINK_DATA_FEEDS }}
+ CHAINLINK_PLATFORM: ${{ secrets.GH_CHAINLINK_PLATFORM }}
+
+ # aave profiles
+ AAVE_ACL_PRIVATE_KEY: ${{ secrets.GH_AAVE_ACL_PRIVATE_KEY }}
+ AAVE_CONFIG_PRIVATE_KEY: ${{ secrets.GH_AAVE_CONFIG_PRIVATE_KEY }}
+ AAVE_MATH_PRIVATE_KEY: ${{ secrets.GH_AAVE_MATH_PRIVATE_KEY }}
+ AAVE_RATE_PRIVATE_KEY: ${{ secrets.GH_AAVE_RATE_PRIVATE_KEY }}
+ AAVE_ORACLE_PRIVATE_KEY: ${{ secrets.GH_AAVE_ORACLE_PRIVATE_KEY }}
+ AAVE_POOL_PRIVATE_KEY: ${{ secrets.GH_AAVE_POOL_PRIVATE_KEY }}
+ A_TOKENS_PRIVATE_KEY: ${{ secrets.GH_A_TOKENS_PRIVATE_KEY }}
+ UNDERLYING_TOKENS_PRIVATE_KEY: ${{ secrets.GH_UNDERLYING_TOKENS_PRIVATE_KEY }}
+ VARIABLE_TOKENS_PRIVATE_KEY: ${{ secrets.GH_VARIABLE_TOKENS_PRIVATE_KEY }}
+ AAVE_LARGE_PACKAGES_PRIVATE_KEY: ${{ secrets.GH_AAVE_LARGE_PACKAGES_PRIVATE_KEY }}
+ AAVE_DATA_PRIVATE_KEY: ${{ secrets.GH_AAVE_DATA_PRIVATE_KEY }}
+ DEFAULT_FUNDER_PRIVATE_KEY: ${{ secrets.GH_DEFAULT_FUNDER_PRIVATE_KEY }}
+
+ # test profiles
+ TEST_ACCOUNT_0_PRIVATE_KEY: ${{ secrets.GH_TEST_ACCOUNT_0_PRIVATE_KEY }}
+ TEST_ACCOUNT_1_PRIVATE_KEY: ${{ secrets.GH_TEST_ACCOUNT_1_PRIVATE_KEY }}
+ TEST_ACCOUNT_2_PRIVATE_KEY: ${{ secrets.GH_TEST_ACCOUNT_2_PRIVATE_KEY }}
+ TEST_ACCOUNT_3_PRIVATE_KEY: ${{ secrets.GH_TEST_ACCOUNT_3_PRIVATE_KEY }}
+ TEST_ACCOUNT_4_PRIVATE_KEY: ${{ secrets.GH_TEST_ACCOUNT_4_PRIVATE_KEY }}
+ TEST_ACCOUNT_5_PRIVATE_KEY: ${{ secrets.GH_TEST_ACCOUNT_5_PRIVATE_KEY }}
+
steps:
- uses: actions/checkout@v4
@@ -54,46 +83,6 @@ jobs:
curl -fsSL "https://aptos.dev/scripts/install_cli.py" | python3
aptos --version # Verify that Aptos CLI is installed
- - name: Checkout aptos-core repository
- run: |
- git clone https://github.com/0xjunha/aptos-core.git
- cd aptos-core
- git checkout large_packages_e2e
-
- - name: Cache Cargo registry
- uses: actions/cache@v4
- id: cargo-cache
- with:
- path: |
- ~/.cargo/registry
- ~/.cargo/git
- key: ${{ runner.os }}-cargo-registry-${{ hashFiles('aptos-core/Cargo.lock') }}
- restore-keys: |
- ${{ runner.os }}-cargo-registry-
-
- - name: Cache Cargo target directory
- uses: actions/cache@v4
- id: cargo-target-cache
- with:
- path: aptos-core/target
- key: ${{ runner.os }}-cargo-target-${{ hashFiles('aptos-core/Cargo.lock') }}
- restore-keys: |
- ${{ runner.os }}-cargo-target-
-
- - name: Build custom Aptos CLI
- run: |
- cd aptos-core
- sh scripts/cli/build_cli_release.sh
-
- - name: Replace original Aptos CLI
- run: |
- cd aptos-core
- zip_file=$(ls aptos-cli-*.zip)
- unzip $zip_file
- sudo mv /home/runner/.local/bin/aptos /home/runner/.local/bin/aptos_backup || true
- sudo mv aptos /home/runner/.local/bin/aptos
- aptos --version # Verify that the new Aptos CLI is installed
-
- name: Set Aptos Workspace Config
run: make set-workspace-config
@@ -156,10 +145,10 @@ jobs:
- name: Initialize Data
if: ${{ github.event.inputs.initData == 'true' }}
- run: pnpm run init-data
+ run: pnpm run deploy:init-data
working-directory: test-suites
- name: Running Core Operations
if: ${{ github.event.inputs.initData == 'true' }}
- run: pnpm run core-operations
- working-directory: test-suites
\ No newline at end of file
+ run: pnpm run deploy:core-operations
+ working-directory: test-suites
diff --git a/.github/workflows/typescript-integration-tests.yml b/.github/workflows/typescript-integration-tests.yml
index 1c49a26..6bda2b4 100644
--- a/.github/workflows/typescript-integration-tests.yml
+++ b/.github/workflows/typescript-integration-tests.yml
@@ -3,29 +3,34 @@ name: TypeScript Integration Tests
on:
pull_request:
merge_group:
- branches: [main]
+ branches:
+ - main
env:
CARGO_TERM_COLOR: always
GITHUB_ACTIONS: true
APTOS_NETWORK: local
+ UPGRADE_CONTRACTS: false
ARTIFACTS_LEVEL: all
- PYTH_HERMES_URL: https://hermes-beta.pyth.network
- PYTH_CONTRACT_ACCOUNT: 0x0
- PYTH_DEPLOYER_ACCOUNT: 0x0
- PYTH_WORMHOLE: 0x0
jobs:
typescript-integration-tests:
name: Run Typescript Integration Tests
- runs-on: ubuntu-latest
+ runs-on: Larger-Github-Runners
timeout-minutes: 60
env:
DEFAULT_FUNDER_PRIVATE_KEY: ${{ secrets.GH_DEFAULT_FUNDER_PRIVATE_KEY }}
steps:
- uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+
+ - name: Install dependencies
+ run: |
+ sudo apt-get update -y
+ sudo apt-get install -y libudev-dev lld libdw-dev
+
- name: Install Aptos CLI
run: |
curl -fsSL "https://aptos.dev/scripts/install_cli.py" | python3
@@ -56,7 +61,7 @@ jobs:
${{ runner.os }}-pnpm-store-
- name: Install npm dependencies
- run: pnpm install
+ run: pnpm install
working-directory: test-suites
- name: Run Aptos Create Local Testnet
@@ -92,15 +97,15 @@ jobs:
- name: Run Aptos Publish All Contracts
run: make publish-all
- - name: Run init test data
- run: pnpm run init-data
- working-directory: test-suites
+ # - name: Run init test data
+ # run: pnpm run deploy:init-data
+ # working-directory: test-suites
- - name: Run integration tests logic
- run: pnpm run test:logic
- working-directory: test-suites
+ # - name: Run integration tests logic
+ # run: pnpm run test:logic
+ # working-directory: test-suites
- name: Terminate Aptos Local Testnet
if: always()
- run: |
- kill $(cat aptos_serve_pid.txt) || true
\ No newline at end of file
+ run: |-
+ kill $(cat aptos_serve_pid.txt) || true
diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml
index 26bda7f..3eb1528 100644
--- a/.github/workflows/unit_tests.yml
+++ b/.github/workflows/unit_tests.yml
@@ -3,22 +3,21 @@ name: Unit Tests
on:
pull_request:
merge_group:
- branches: [main]
+ branches:
+ - main
env:
CARGO_TERM_COLOR: always
GITHUB_ACTIONS: true
APTOS_NETWORK: local
+ UPGRADE_CONTRACTS: false
ARTIFACTS_LEVEL: all
- PYTH_HERMES_URL: https://hermes-beta.pyth.network
- PYTH_CONTRACT_ACCOUNT: 0x0
- PYTH_DEPLOYER_ACCOUNT: 0x0
- PYTH_WORMHOLE: 0x0
+ DEFAULT_FUND_AMOUNT: 40000000
jobs:
unit-tests:
name: Run Aptos Unit Tests
- runs-on: ubuntu-latest
+ runs-on: Larger-Github-Runners
timeout-minutes: 60
env:
DEFAULT_FUNDER_PRIVATE_KEY: ${{ secrets.GH_DEFAULT_FUNDER_PRIVATE_KEY }}
@@ -53,4 +52,9 @@ jobs:
run: make compile-all
- name: Run Aptos Test All Contracts
- run: make test-all
\ No newline at end of file
+ run: make test-all
+
+ - name: Terminate Aptos Local Testnet
+ if: always()
+ run: |-
+ kill $(cat aptos_serve_pid.txt) || true
diff --git a/.gitignore b/.gitignore
index ffd561d..f291704 100644
--- a/.gitignore
+++ b/.gitignore
@@ -95,5 +95,3 @@ target/
*.mvcov
*.trace
gas-profiling
-
-.aptos
\ No newline at end of file
diff --git a/.markdownlint.json b/.markdownlint.json
new file mode 100644
index 0000000..9d5a933
--- /dev/null
+++ b/.markdownlint.json
@@ -0,0 +1,14 @@
+{
+ "extends": "markdownlint/style/prettier",
+ "first-line-h1": false,
+ "no-inline-html": false,
+ "no-alt-text": false,
+ "MD001": false,
+ "MD040": false,
+ "MD024": false,
+ "MD025": false,
+ "MD036": false,
+ "MD042": false,
+ "MD052": false,
+ "MD056": false
+}
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 0000000..c1aff3e
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,44 @@
+default_install_hook_types:
+ - pre-commit
+
+default_stages:
+ - pre-commit
+
+exclude: |
+ (?x)^(
+ CHANGELOG.md|
+ pnpm-lock.yaml|
+ cov-reports
+ )$
+
+repos:
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v4.6.0
+ hooks:
+ - id: trailing-whitespace
+ - id: end-of-file-fixer
+ - id: check-json
+ - id: check-toml
+ - id: check-added-large-files
+ args:
+ - --maxkb=3000
+ - id: check-merge-conflict
+ - id: check-case-conflict
+ - id: detect-private-key
+
+ - repo: local
+ hooks:
+ - id: format
+ name: format
+ description: Format files using different tools
+ entry: make fmt
+ language: system
+ pass_filenames: false
+
+ - repo: https://github.com/lyz-code/yamlfix/
+ rev: 1.17.0
+ hooks:
+ - id: yamlfix
+ args:
+ - -c
+ - .yamlfix.toml
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 0000000..8b63442
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,5 @@
+pnpm-lock.yaml
+images
+audit
+cov-reports
+aave-core
diff --git a/.prettierrc.toml b/.prettierrc.toml
new file mode 100644
index 0000000..a5370ca
--- /dev/null
+++ b/.prettierrc.toml
@@ -0,0 +1,9 @@
+plugins = ["prettier-plugin-sh", "prettier-plugin-toml"]
+singleQuote = false
+printWidth = 100
+
+[[overrides]]
+files = ["**/*.md"]
+
+[overrides.options]
+proseWrap = "preserve"
diff --git a/.typos.toml b/.typos.toml
new file mode 100644
index 0000000..7b30bb8
--- /dev/null
+++ b/.typos.toml
@@ -0,0 +1,2 @@
+[files]
+extend-exclude = []
diff --git a/.yamlfix.toml b/.yamlfix.toml
new file mode 100644
index 0000000..2347b77
--- /dev/null
+++ b/.yamlfix.toml
@@ -0,0 +1,7 @@
+explicit_start = false
+section_whitelines = 1
+whitelines = 1
+line_length = 100
+preserve_quotes = true
+sequence_style = "block_style"
+indent_mapping = 2
diff --git a/BusinessLogic.md b/BusinessLogic.md
deleted file mode 100644
index 9cda610..0000000
--- a/BusinessLogic.md
+++ /dev/null
@@ -1,1317 +0,0 @@
-# AAVE Business Logic
-
-
-## Pool
-> source code: crest/blob/dev/aave-pool/sources/pool.move
-
-### Add resources to the pool
-- 1. Add Token (underlying token, a token, variable token)
-- 2. Determine whether the underlying token is in the pool. If it already exists, it will not be added and an error will be returned directly.
-- 3. Determine whether the total size of the pool exceeds the total size set by the system. If it has exceeded, no more additions can be made.
-- 4. Create resource objects and resource configurations and join the pool
-- 5. Update the added resource count = count + 1
-- 6. Update the map of reserve_address_list (address=>count)
-- 7. Release event ReserveInitialized
-```bash=
-struct ReserveData has key, store, copy, drop {
- /// stores the reserve configuration
- configuration: ReserveConfigurationMap,
- /// the liquidity index. Expressed in ray
- liquidity_index: u128,
- /// the current supply rate. Expressed in ray
- current_liquidity_rate: u128,
- /// variable borrow index. Expressed in ray
- variable_borrow_index: u128,
- /// the current variable borrow rate. Expressed in ray
- current_variable_borrow_rate: u128,
- /// the current stable borrow rate. Expressed in ray
- current_stable_borrow_rate: u128,
- /// timestamp of last update (u40 -> u64)
- last_update_timestamp: u64,
- /// the id of the reserve. Represents the position in the list of the active reserves
- id: u16,
- /// aToken address
- a_token_address: address,
- /// stableDebtToken address
- stable_debt_token_address: address,
- /// variableDebtToken address
- variable_debt_token_address: address,
- /// address of the interest rate strategy
- interest_rate_strategy_address: address,
- /// the current treasury balance, scaled
- accrued_to_treasury: u256,
- /// the outstanding unbacked aTokens minted through the bridging feature
- unbacked: u128,
- /// the outstanding debt borrowed against this asset in isolation mode
- isolation_mode_total_debt: u128,
-}
-
-struct ReserveList has key {
- // SmartTable to store reserve data with asset addresses as keys
- value: SmartTable
,
- // Count of reserves in the list
- count: u256,
-}
-
-// List of reserves as a map (reserveId => reserve).
-struct ReserveAddressesList has key {
- value: SmartTable,
-}
-
-public fun add_reserve(
- account: &signer,
- a_token_tmpl: address,
- stable_debt_token_impl: address,
- variable_debt_token_impl: address,
- underlying_asset_decimals: u256,
- interest_rate_strategy_address: address,
- underlying_asset: address,
- // _treasury: address,
- // _incentives_controller: address,
- // _a_token_name: String,
- // _a_token_symbol: String,
- // _variable_debt_token_name: String,
- // _variable_debt_token_symbol: String,
- // _stable_debt_token_name: String,
- // _stable_debt_token_symbol: String,
- // _params: String
-) acquires ReserveList, ReserveAddressesList {
- // Get the signers address
- let singer_address = signer::address_of(account);
-
- // Borrow the ReserveList resource
- let reserve_data_list = borrow_global_mut(singer_address);
-
- // 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 that the maximum number of reserves has not been reached
- assert!(
- reserve_data_list.count < (reserve_config::get_max_reserves_count()),
- error_config::get_eno_more_reserves_allowed()
- );
-
- // Increment the reserve count
- let count = reserve_data_list.count + 1;
-
- let reserve_configuration = reserve_config::init();
- reserve_config::set_decimals(&mut reserve_configuration, underlying_asset_decimals);
- reserve_config::set_active(&mut reserve_configuration, true);
- reserve_config::set_paused(&mut reserve_configuration, false);
- reserve_config::set_frozen(&mut reserve_configuration, false);
-
- // Create a new ReserveData entry
- let reserve_data = ReserveData {
- configuration: reserve_configuration,
- 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,
- current_stable_borrow_rate: 0,
- last_update_timestamp: 0,
- id: (count as u16),
- a_token_address: a_token_tmpl,
- stable_debt_token_address: stable_debt_token_impl,
- variable_debt_token_address: variable_debt_token_impl,
- interest_rate_strategy_address,
- accrued_to_treasury: 0,
- unbacked: 0,
- isolation_mode_total_debt: 0,
- };
-
- // Add or update the ReserveData in the smart table
- smart_table::add(&mut reserve_data_list.value, underlying_asset, reserve_data);
-
- // Update the reserve count
- reserve_data_list.count = count;
-
- // update reserve address list
- add_reserve_address_list(count, underlying_asset);
-
- // emit the ReserveInitialized event
- event::emit(ReserveInitialized {
- asset: underlying_asset,
- a_token: a_token_tmpl,
- stable_debt_token: stable_debt_token_impl,
- variable_debt_token: variable_debt_token_impl,
- interest_rate_strategy_address,
- })
-}
-```
-
-> Solidity Source Code(Line: 82)
-> Link: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/PoolConfigurator.sol
-### Configuration of pool resources
-```bash=
-struct ReserveConfigurationMap has key, store, copy, drop {
- /// bit 0-15: LTV
- /// bit 16-31: Liq. threshold
- /// bit 32-47: Liq. bonus
- /// bit 48-55: Decimals
- /// bit 56: reserve is active
- /// bit 57: reserve is frozen
- /// bit 58: borrowing is enabled
- /// bit 59: stable rate borrowing enabled
- /// bit 60: asset is paused
- /// bit 61: borrowing in isolation mode is enabled
- /// bit 62: siloed borrowing enabled
- /// bit 63: flashloaning enabled
- /// bit 64-79: reserve factor
- /// bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap
- /// bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap
- /// bit 152-167 liquidation protocol fee
- /// bit 168-175 eMode category
- /// bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled
- /// bit 212-251 debt ceiling for isolation mode with (ReserveConfigurationMap::DEBT_CEILING_DECIMALS) decimals
- /// bit 252-255 unused
- data: u256,
-}
-
-# Source Code: crest/blob/dev/aave-config/sources/reserve_config.move
-
-```
-
-### Delete pool resources
-- 1. Determine whether the resource address to be deleted is the 0 address, and exit if it is the 0 address.
-- 2. Determine whether the resource to be deleted exists. If it does not exist, exit with an error.
-- 3. Get variable_debt_token total_supply and determine whether total_supply is 0. If it is not 0, exit
-- 4. Get the total_supply of a_token, and check a_debt_token_total_supply == 0 && reserve_data.accrued_to_treasury == 0, if the check fails, exit
-- 5. Remove resources and the relationship between resource id and address
-- 6. Update resource count=count-1
-```bash=
-public fun drop_reserve(account: &signer, asset: address) acquires ReserveList, ReserveAddressesList {
- assert!(asset != @0x0, error_config::get_ezero_address_not_valid());
-
- // Get the signers address
- let singer_address = signer::address_of(account);
- // Borrow the ReserveList resource
- let reserve_data_list = borrow_global_mut(singer_address);
- // Assert that the asset is listed
- assert!(smart_table::contains(&reserve_data_list.value, asset), error_config::get_easset_not_listed());
-
- // Get the ReserveData
- let reserve_data = smart_table::borrow(&reserve_data_list.value, asset);
-
- let variable_debt_token_total_supply = variable_token_factory::supply(reserve_data.variable_debt_token_address);
- assert!(variable_debt_token_total_supply == 0, error_config::get_evariable_debt_supply_not_zero());
-
- let a_debt_token_total_supply = a_token_factory::supply(reserve_data.a_token_address);
- assert!(
- a_debt_token_total_supply == 0 && reserve_data.accrued_to_treasury == 0,
- error_config::get_eunderlying_claimable_rights_not_zero()
- );
-
- // Remove the ReserveData entry from the smart_table
- smart_table::remove(&mut reserve_data_list.value, asset);
-
- // Remove ReserveAddressList
- let reserve_address_list = borrow_global_mut(singer_address);
- 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));
- };
- // Decrease the reserve count
- reserve_data_list.count = reserve_data_list.count - 1;
-}
-```
-## User
-> source code: crest/tree/dev/aave-supply-borrow/sources
-### Supply
-- 1. Update the status of the pool (update_state)
-- 2. validate_supply
-```bash=
-// Supply Validate
-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);
- 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::supply(pool::get_reserve_token_address(reserve_data));
- let accrued_to_treasury_liquidity = wad_ray_math::ray_mul(pool::get_reserve_accrued_to_treasury(reserve_data),
- (pool::get_reserve_liquidity_index(reserve_data) as u256)
- );
- let total_supply = a_token_supply + accrued_to_treasury_liquidity + amount;
- let max_supply = supply_cap * (10 ^ reserve_config::get_decimals(&reserve_configuration));
-
- assert!(supply_cap == 0 || total_supply <= max_supply, error_config::get_esupply_cap_exceeded());
-}
-```
-- 3. Update interest rates update_interest_rates
-- 4. Transfer standard assets to aToken
-- 5. Mint atoken to on_behalf_of account
-- 6. Determine whether on_behalf_of is the first deposit. If so, verify whether it can be automatically used as collateral.
-- 7. Update the mortgage configuration and save it to the asset configuration
-- 8. Event of deposit submission
-```bash=
-public entry fun supply(
- account: &signer,
- asset: address,
- amount: u256,
- on_behalf_of: address,
- referral_code: u16
-) {
- let reserve_data = pool::get_reserve_data(asset);
- pool::update_state(asset, &mut reserve_data);
- validation_logic::validate_supply(&reserve_data, amount);
- pool::update_interest_rates(&mut reserve_data, asset, amount, 0);
-
- let account_address = signer::address_of(account);
- let token_a_address = pool::get_reserve_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,
- account_address,
- a_token_account,
- (amount as u64),
- asset
- );
- let is_first_supply: bool = a_token_factory::balance_of(account_address, 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
- );
- if (is_first_supply) {
- if (pool_validation::validate_automatic_use_as_collateral(account_address, asset)) {
- let user_config_map = pool::get_user_configuration(on_behalf_of);
- 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: account_address
- });
- }
- };
- // Emit a supply event
- event::emit(Supply {
- reserve: asset,
- user: account_address,
- on_behalf_of,
- amount,
- referral_code,
- });
-}
-```
-### Withdraw
-- 1. Update the status of the pool (update_state)
-- 2. Get the account balance of the current withdrawal
-- 3. Verify withdrawal validate_withdraw
-```bash=
-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!(is_active, error_config::get_ereserve_inactive());
- assert!(!is_paused, error_config::get_ereserve_paused());
-}
-```
-- 4. Update interest rates update_interest_rates
-- 5. Determine whether it is collateral and whether the withdrawal amount is equal to the user's account balance. If so, update the status of the collateral to uncollateralized and publish an uncollateralized event.
-- 5.burn atoken from on_behalf_of account
-- 6. Determine whether it is collateral and whether it is borrowing money. If so, verify the health factor and loan ratio validateHFAndLtv
-- 7. Submit the event of withdrawal
-```bash=
-public entry fun withdraw(
- account: &signer,
- asset: address,
- amount: u256,
- to: address,
- user_emode_category: u8,
-) {
- let account_address = signer::address_of(account);
- 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::balance_of(account_address, pool::get_reserve_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);
-
- // update interest rates
- pool::update_interest_rates(&mut reserve_data, asset, 0, amount_to_withdraw);
-
- let user_config_map = pool::get_user_configuration(account_address);
- let reserve_id = pool::get_reserve_id(&reserve_data);
- let is_collateral = 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);
- pool::set_user_configuration(account_address, user_config_map);
- event::emit(ReserveUsedAsCollateralDisabled {
- reserve: asset,
- user: account_address
- });
- };
-
- // burn a token
- a_token_factory::burn(
- account_address,
- to,
- amount_to_withdraw,
- (pool::get_reserve_liquidity_index(&reserve_data) as u256),
- pool::get_reserve_token_address(&reserve_data)
- );
-
- if (is_collateral && user_config::is_borrowing_any(&user_config_map)) {
- 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,
- reserves_count,
- &user_config_map,
- account_address,
- user_emode_category,
- emode_ltv,
- emode_liq_threshold,
- emode_asset_price
- );
- };
- // Emit a withdraw event
- event::emit(Withdraw {
- reserve: asset,
- user: account_address,
- to,
- amount,
- });
-}
-```
-### Borrow
-- 1. Update the status of the resource, mainly updating two fields: variableBorrowIndex and accumulatedToTreasury
-- 2. Get the resource isolationModeActive activation status and isolationModeDebtCeiling isolation mode debt ceiling and isolationModeCollateralAddress isolation mode with address
-- 3. Verify Borrow, whether it meets the conditions for borrowing
- - 3.1 Verify that the amount of borrowed money cannot be 0
- ```bash=
- require(params.amount != 0, Errors.INVALID_AMOUNT);
- ```
- - 3.2 Get the resource configuration flags: active, frozen, borrowing is enabled, stable rate borrowing enabled, asset is paused and verify
- ```bash=
- struct ReserveConfigurationMap {
- //bit 0-15: LTV
- //bit 16-31: Liq. threshold
- //bit 32-47: Liq. bonus
- //bit 48-55: Decimals
- //bit 56: reserve is active
- //bit 57: reserve is frozen
- //bit 58: borrowing is enabled
- //bit 59: stable rate borrowing enabled
- //bit 60: asset is paused
- //bit 61: borrowing in isolation mode is enabled
- //bit 62: siloed borrowing enabled
- //bit 63: flashloaning enabled
- //bit 64-79: reserve factor
- //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap
- //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap
- //bit 152-167 liquidation protocol fee
- //bit 168-175 eMode category
- //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled
- //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals
- //bit 252-255 unused
-
- uint256 data;
- }
-
- # Get the flag of the resource and verify it
- (
- vars.isActive,
- vars.isFrozen,
- vars.borrowingEnabled,
- vars.stableRateBorrowingEnabled,
- vars.isPaused
- ) = params.reserveCache.reserveConfiguration.getFlags();
-
- require(vars.isActive, Errors.RESERVE_INACTIVE);
- require(!vars.isPaused, Errors.RESERVE_PAUSED);
- require(!vars.isFrozen, Errors.RESERVE_FROZEN);
- require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED);
- ```
-
- - 3.3 Verify whether borrowing is allowed through oracle sentinel isBorrowAllowed
- - 3.4 Judgment interestRateMode must be one of two types of interest rates: variable and immutable.
- - 3.5 By obtaining the total debt, determine whether the maximum number of borrowable Tokens exceeds BORROW_CAP_EXCEEDED
- - 3.6 Check whether the borrowed assets can be borrowed in isolation mode and the total risk exposure is not greater than the mortgage debt limit
- - 3.7 Determine the resource EModeCategory must be equal to the user's userEModeCategory
- - 3.8 Calculate user account data (user collateral is base currency, user base currency debt, user's maximum loan value, health factor) and verify the data
- ```bash=
- require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO);
- require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED);
-
- require(
- vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
- Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD
- );
- ```
- - 3.9 Determine whether the collateral can cover the new borrowing
- ```bash=
- vars.amountInBaseCurrency =
- IPriceOracleGetter(params.oracle).getAssetPrice(
- vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset
- ) * params.amount;
-
- unchecked {
- vars.amountInBaseCurrency /= vars.assetUnit;
- }
-
- //add the current already borrowed amount to the amount requested to calculate the total collateral needed.
- vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency)
- .percentDiv(vars.currentLtv); //LTV is calculated in percentage
-
- require(
- vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency,
- Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW
- );
- ```
- - 4.0 Check if the user has borrowed from any reserves
- ```bash=
- if (params.userConfig.isBorrowingAny()) {
- (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params
- .userConfig
- .getSiloedBorrowingState(reservesData, reservesList);
-
- if (vars.siloedBorrowingEnabled) {
- require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION);
- } else {
- require(
- !params.reserveCache.reserveConfiguration.getSiloedBorrowing(),
- Errors.SILOED_BORROWING_VIOLATION
- );
- }
- }
- }
- ```
-- 4. According to the interest rate model, Mint specifies the number of Tokens corresponding to the interest rate and gives them to the borrower.
-- 5. Determine whether it is the first time to borrow money. If it is the first time to borrow money, modify the user's status and call setBorrowing(reserve.id, true) to set the user's borrowing resources to true.
-- 6. Determine whether it is isolationModeActive. If activated, obtain the total debt in the next isolation mode and submit the event to update the status of the isolation mode IsolationModeTotalDebtUpdated
-- 7. Recalculate the interest rate updateInterestRates and update the currentLiquidityRate, currentStableBorrowRate, currentVariableBorrowRate of the resource and submit the event
-```bash=
-event ReserveDataUpdated(
- address indexed reserve,
- uint256 liquidityRate,
- uint256 stableBorrowRate,
- uint256 variableBorrowRate,
- uint256 liquidityIndex,
- uint256 variableBorrowIndex
-);
-```
-- 8. Determine whether releaseUnderlying == true, if true, transfer the token amount of the loan to the current user
-- 9. Submit loan event
-```bash=
-event Borrow(
- address indexed reserve,
- address user,
- address indexed onBehalfOf,
- uint256 amount,
- DataTypes.InterestRateMode interestRateMode,
- uint256 borrowRate,
- uint16 indexed referralCode
-);
-```
-### Repay
-- 1. Update the status of repayment resources (mainly update two fields: variableBorrowIndex and accruedToTreasury)
-```bash=
- function executeRepay(
- mapping(address => DataTypes.ReserveData) storage reservesData,
- mapping(uint256 => address) storage reservesList,
- DataTypes.UserConfigurationMap storage userConfig,
- DataTypes.ExecuteRepayParams memory params
-) external returns (uint256) {
- DataTypes.ReserveData storage reserve = reservesData[params.asset];
- DataTypes.ReserveCache memory reserveCache = reserve.cache();
- reserve.updateState(reserveCache);
-}
-```
-- 2. Obtain the current user's debt (including variable interest rate debt and non-variable interest rate debt)
-```bash=
-(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(
- params.onBehalfOf,
- reserveCache
- );
-```
-- 3. validate Repay
-```bash=
- ValidationLogic.validateRepay(
- reserveCache,
- params.amount,
- params.interestRateMode,
- params.onBehalfOf,
- stableDebt,
- variableDebt
- );
- /**
- * @notice Validates a repay action.
- * @param reserveCache The cached data of the reserve
- * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)
- * @param interestRateMode The interest rate mode of the debt being repaid
- * @param onBehalfOf The address of the user msg.sender is repaying for
- * @param stableDebt The borrow balance of the user
- * @param variableDebt The borrow balance of the user
- */
- function validateRepay(
- DataTypes.ReserveCache memory reserveCache,
- uint256 amountSent,
- DataTypes.InterestRateMode interestRateMode,
- address onBehalfOf,
- uint256 stableDebt,
- uint256 variableDebt
- ) internal view {
- # step1. The repayment amount cannot be 0
- require(amountSent != 0, Errors.INVALID_AMOUNT);
-
- require(
- amountSent != type(uint256).max || msg.sender == onBehalfOf,
- Errors.NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF
- );
-
- (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();
- require(isActive, Errors.RESERVE_INACTIVE);
- require(!isPaused, Errors.RESERVE_PAUSED);
-
- require(
- (stableDebt != 0 && interestRateMode == DataTypes.InterestRateMode.STABLE) ||
- (variableDebt != 0 && interestRateMode == DataTypes.InterestRateMode.VARIABLE),
- Errors.NO_DEBT_OF_SELECTED_TYPE
- );
- }
-```
-- 4. Get the payback amount
-```bash=
- uint256 paybackAmount = params.interestRateMode == DataTypes.InterestRateMode.STABLE
- ? stableDebt
- : variableDebt;
-
-// Allows a user to repay with aTokens without leaving dust from interest.
-if (params.useATokens && params.amount == type(uint256).max) {
- params.amount = IAToken(reserveCache.aTokenAddress).balanceOf(msg.sender);
-}
-
-if (params.amount < paybackAmount) {
- paybackAmount = params.amount;
-}
-```
-
-- 5.Burn the specified number of tokens according to the interest rate model
-```bash=
-if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) {
- (reserveCache.nextTotalStableDebt, reserveCache.nextAvgStableBorrowRate) = IStableDebtToken(
- reserveCache.stableDebtTokenAddress
- ).burn(params.onBehalfOf, paybackAmount);
-} else {
- reserveCache.nextScaledVariableDebt = IVariableDebtToken(
- reserveCache.variableDebtTokenAddress
- ).burn(params.onBehalfOf, paybackAmount, reserveCache.nextVariableBorrowIndex);
-}
-```
-- 6.Recalculate the interest rate updateInterestRates and update the currentLiquidityRate, currentStableBorrowRate, currentVariableBorrowRate of the resource and submit the event
-```bash=
-function updateInterestRates(
- DataTypes.ReserveData storage reserve,
- DataTypes.ReserveCache memory reserveCache,
- address reserveAddress,
- uint256 liquidityAdded,
- uint256 liquidityTaken
- ) internal {
- UpdateInterestRatesLocalVars memory vars;
-
- vars.totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(
- reserveCache.nextVariableBorrowIndex
- );
-
- (
- vars.nextLiquidityRate,
- vars.nextStableRate,
- vars.nextVariableRate
- ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
- DataTypes.CalculateInterestRatesParams({
- unbacked: reserve.unbacked,
- liquidityAdded: liquidityAdded,
- liquidityTaken: liquidityTaken,
- totalStableDebt: reserveCache.nextTotalStableDebt,
- totalVariableDebt: vars.totalVariableDebt,
- averageStableBorrowRate: reserveCache.nextAvgStableBorrowRate,
- reserveFactor: reserveCache.reserveFactor,
- reserve: reserveAddress,
- aToken: reserveCache.aTokenAddress
- })
- );
-
- reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();
- reserve.currentStableBorrowRate = vars.nextStableRate.toUint128();
- reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();
-
- emit ReserveDataUpdated(
- reserveAddress,
- vars.nextLiquidityRate,
- vars.nextStableRate,
- vars.nextVariableRate,
- reserveCache.nextLiquidityIndex,
- reserveCache.nextVariableBorrowIndex
- );
-}
-```
-- 7. Calculate variable and immutable debt - whether the investment recovery amount is equal to 0, if equal to 0, update the status of the resource the user is borrowing to false
-```bash=
-if (stableDebt + variableDebt - paybackAmount == 0) {
- userConfig.setBorrowing(reserve.id, false);
-}
-```
-- 8. updated the isolated debt whenever a position collateralized by an isolated asset is repaid or liquidated
-```bash=
-IsolationModeLogic.updateIsolatedDebtIfIsolated(
- reservesData,
- reservesList,
- userConfig,
- reserveCache,
- paybackAmount
-);
-```
-- 9. Determine whether the user uses token to repay the loan
-```bash=
-if (params.useATokens) {
- IAToken(reserveCache.aTokenAddress).burn(
- msg.sender,
- reserveCache.aTokenAddress,
- paybackAmount,
- reserveCache.nextLiquidityIndex
- );
-} else {
- IERC20(params.asset).safeTransferFrom(msg.sender, reserveCache.aTokenAddress, paybackAmount);
- IAToken(reserveCache.aTokenAddress).handleRepayment(
- msg.sender,
- params.onBehalfOf,
- paybackAmount
- );
-}
-```
-- 10. Submit repayment event
-```bash=
-event Repay(
- address indexed reserve,
- address indexed user,
- address indexed repayer,
- uint256 amount,
- bool useATokens
-);
-emit Repay(params.asset, params.onBehalfOf, msg.sender, paybackAmount, params.useATokens);
-```
-### Liquidation
-- 1. Obtain mortgage resources and debt assets and update debt assets (mainly update two fields: variableBorrowIndex and accruedToTreasury)
-```bash=
-function executeLiquidationCall(
- mapping(address => DataTypes.ReserveData) storage reservesData,
- mapping(uint256 => address) storage reservesList,
- mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,
- mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,
- DataTypes.ExecuteLiquidationCallParams memory params
-) external {
- LiquidationCallLocalVars memory vars;
-
- DataTypes.ReserveData storage collateralReserve = reservesData[params.collateralAsset];
- DataTypes.ReserveData storage debtReserve = reservesData[params.debtAsset];
- DataTypes.UserConfigurationMap storage userConfig = usersConfig[params.user];
- vars.debtReserveCache = debtReserve.cache();
- debtReserve.updateState(vars.debtReserveCache);
-```
-- 2. Calculate user data and obtain health factor
-```bash=
-(,,,, vars.healthFactor,) = GenericLogic.calculateUserAccountData(
- reservesData,
- reservesList,
- eModeCategories,
- DataTypes.CalculateUserAccountDataParams({
- userConfig: userConfig,
- reservesCount: params.reservesCount,
- user: params.user,
- oracle: params.priceOracle,
- userEModeCategory: params.userEModeCategory
- })
-);
-```
-- 3. Calculate Debt Gets the user's total debt with variable interest rates, the user's total debt and debts that need to be liquidated
-```bash=
-function _calculateDebt(
- DataTypes.ReserveCache memory debtReserveCache,
- DataTypes.ExecuteLiquidationCallParams memory params,
- uint256 healthFactor
-) internal view returns (uint256, uint256, uint256) {
- (uint256 userStableDebt, uint256 userVariableDebt) = Helpers.getUserCurrentDebt(
- params.user,
- debtReserveCache
- );
-
- uint256 userTotalDebt = userStableDebt + userVariableDebt;
-
- uint256 closeFactor = healthFactor > CLOSE_FACTOR_HF_THRESHOLD
- ? DEFAULT_LIQUIDATION_CLOSE_FACTOR
- : MAX_LIQUIDATION_CLOSE_FACTOR;
-
- uint256 maxLiquidatableDebt = userTotalDebt.percentMul(closeFactor);
-
- uint256 actualDebtToLiquidate = params.debtToCover > maxLiquidatableDebt
- ? maxLiquidatableDebt
- : params.debtToCover;
-
- return (userVariableDebt, userTotalDebt, actualDebtToLiquidate);
-}
-```
-- 4.validate liquidation
-```bash=
-ValidationLogic.validateLiquidationCall(
- userConfig,
- collateralReserve,
- DataTypes.ValidateLiquidationCallParams({
- debtReserveCache: vars.debtReserveCache,
- totalDebt: vars.userTotalDebt,
- healthFactor: vars.healthFactor,
- priceOracleSentinel: params.priceOracleSentinel
- })
-);
-
-function validateLiquidationCall(
- DataTypes.UserConfigurationMap storage userConfig,
- DataTypes.ReserveData storage collateralReserve,
- DataTypes.ValidateLiquidationCallParams memory params
-) internal view {
- ValidateLiquidationCallLocalVars memory vars;
-
- (vars.collateralReserveActive, , , , vars.collateralReservePaused) = collateralReserve
- .configuration
- .getFlags();
-
- (vars.principalReserveActive, , , , vars.principalReservePaused) = params
- .debtReserveCache
- .reserveConfiguration
- .getFlags();
-
- # step1. Verify the active status of the collateral and primary debt, must be active
- require(vars.collateralReserveActive && vars.principalReserveActive, Errors.RESERVE_INACTIVE);
- # step2. Verify the moratorium status of the collateral and primary debt, which must be non-moratorium
- require(!vars.collateralReservePaused && !vars.principalReservePaused, Errors.RESERVE_PAUSED);
-
- # step3. Verify whether the conditions to allow forced liquidation are met
- require(
- params.priceOracleSentinel == address(0) ||
- params.healthFactor < MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD ||
- IPriceOracleSentinel(params.priceOracleSentinel).isLiquidationAllowed(),
- Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED
- );
- # step4. Verify that the health factor is not below the threshold
- require(
- params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
- Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD
- );
-
- vars.isCollateralEnabled =
- collateralReserve.configuration.getLiquidationThreshold() != 0 &&
- userConfig.isUsingAsCollateral(collateralReserve.id);
-
- //if collateral is not enabled as collateral by user, it cannot be liquidated
- # step4. Verify whether the collateral has been enabled, if so, an error will be reported
- require(vars.isCollateralEnabled, Errors.COLLATERAL_CANNOT_BE_LIQUIDATED);
- # step5. Verify that the total debt cannot be 0. If it is 0, an error will be reported.
- require(params.totalDebt != 0, Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER);
-}
-```
-- 5. Get configuration data
-```bash=
-(
- vars.collateralAToken,
- vars.collateralPriceSource,
- vars.debtPriceSource,
- vars.liquidationBonus
-) = _getConfigurationData(eModeCategories, collateralReserve, params);
-
-/**
-* @notice Returns the configuration data for the debt and the collateral reserves.
-* @param eModeCategories The configuration of all the efficiency mode categories
-* @param collateralReserve 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
-*/
-function _getConfigurationData(
- mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,
- DataTypes.ReserveData storage collateralReserve,
- DataTypes.ExecuteLiquidationCallParams memory params
-) internal view returns (IAToken, address, address, uint256) {
- IAToken collateralAToken = IAToken(collateralReserve.aTokenAddress);
- uint256 liquidationBonus = collateralReserve.configuration.getLiquidationBonus();
-
- address collateralPriceSource = params.collateralAsset;
- address debtPriceSource = params.debtAsset;
-
- if (params.userEModeCategory != 0) {
- address eModePriceSource = eModeCategories[params.userEModeCategory].priceSource;
-
- if (
- EModeLogic.isInEModeCategory(
- params.userEModeCategory,
- collateralReserve.configuration.getEModeCategory()
- )
- ) {
- liquidationBonus = eModeCategories[params.userEModeCategory].liquidationBonus;
-
- if (eModePriceSource != address(0)) {
- collateralPriceSource = eModePriceSource;
- }
- }
-
- // when in eMode, debt will always be in the same eMode category, can skip matching category check
- if (eModePriceSource != address(0)) {
- debtPriceSource = eModePriceSource;
- }
- }
-
- return (collateralAToken, collateralPriceSource, debtPriceSource, liquidationBonus);
-}
-```
-- 6.Get the user's collateral balance
-```bash=
-vars.userCollateralBalance = vars.collateralAToken.balanceOf(params.user);
-```
-- 7.Calculate available collateral for liquidation
-```bash=
- (
- vars.actualCollateralToLiquidate,
- vars.actualDebtToLiquidate,
- vars.liquidationProtocolFeeAmount
-) = _calculateAvailableCollateralToLiquidate(
- collateralReserve,
- vars.debtReserveCache,
- vars.collateralPriceSource,
- vars.debtPriceSource,
- vars.actualDebtToLiquidate,
- vars.userCollateralBalance,
- vars.liquidationBonus,
- IPriceOracleGetter(params.priceOracle)
-);
-```
-- 8.It is judged that the user's total debt is equal to the actual debt to be liquidated. If the conditions are met, the borrowing resources will be updated to the unborrowable state.
-```bash=
-if (vars.userTotalDebt == vars.actualDebtToLiquidate) {
- userConfig.setBorrowing(debtReserve.id, false);
-}
-```
-- 9.If the liquidated collateral equals the user balance, we set the currency to no longer be used as collateral, and submit a collateral disable event
-```bash=
-if (
- vars.actualCollateralToLiquidate + vars.liquidationProtocolFeeAmount ==
- vars.userCollateralBalance
-) {
- userConfig.setUsingAsCollateral(collateralReserve.id, false);
- emit ReserveUsedAsCollateralDisabled(params.collateralAsset, params.user);
-}
-```
-- 10.Burn Debt Token
-```bash=
-function _burnDebtTokens(
- DataTypes.ExecuteLiquidationCallParams memory params,
- LiquidationCallLocalVars memory vars
-) internal {
- if (vars.userVariableDebt >= vars.actualDebtToLiquidate) {
- vars.debtReserveCache.nextScaledVariableDebt = IVariableDebtToken(
- vars.debtReserveCache.variableDebtTokenAddress
- ).burn(
- params.user,
- vars.actualDebtToLiquidate,
- vars.debtReserveCache.nextVariableBorrowIndex
- );
- } else {
- // If the user does not have variable debt, no need to try to burn variable debt tokens
- if (vars.userVariableDebt != 0) {
- vars.debtReserveCache.nextScaledVariableDebt = IVariableDebtToken(
- vars.debtReserveCache.variableDebtTokenAddress
- ).burn(params.user, vars.userVariableDebt, vars.debtReserveCache.nextVariableBorrowIndex);
- }
- (
- vars.debtReserveCache.nextTotalStableDebt,
- vars.debtReserveCache.nextAvgStableBorrowRate
- ) = IStableDebtToken(vars.debtReserveCache.stableDebtTokenAddress).burn(
- params.user,
- vars.actualDebtToLiquidate - vars.userVariableDebt
- );
- }
-}
-```
-- 11. Recalculate the interest rate of the debt resource updateInterestRates and update the currentLiquidityRate, currentStableBorrowRate, currentVariableBorrowRate of the resource and submit the event
-```bash=
-function updateInterestRates(
- DataTypes.ReserveData storage reserve,
- DataTypes.ReserveCache memory reserveCache,
- address reserveAddress,
- uint256 liquidityAdded,
- uint256 liquidityTaken
- ) internal {
- UpdateInterestRatesLocalVars memory vars;
-
- vars.totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(
- reserveCache.nextVariableBorrowIndex
- );
-
- (
- vars.nextLiquidityRate,
- vars.nextStableRate,
- vars.nextVariableRate
- ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
- DataTypes.CalculateInterestRatesParams({
- unbacked: reserve.unbacked,
- liquidityAdded: liquidityAdded,
- liquidityTaken: liquidityTaken,
- totalStableDebt: reserveCache.nextTotalStableDebt,
- totalVariableDebt: vars.totalVariableDebt,
- averageStableBorrowRate: reserveCache.nextAvgStableBorrowRate,
- reserveFactor: reserveCache.reserveFactor,
- reserve: reserveAddress,
- aToken: reserveCache.aTokenAddress
- })
- );
-
- reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();
- reserve.currentStableBorrowRate = vars.nextStableRate.toUint128();
- reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();
-
- emit ReserveDataUpdated(
- reserveAddress,
- vars.nextLiquidityRate,
- vars.nextStableRate,
- vars.nextVariableRate,
- reserveCache.nextLiquidityIndex,
- reserveCache.nextVariableBorrowIndex
- );
-}
-```
-- 12.updated the isolated debt whenever a position collateralized by an isolated asset is repaid or liquidated
-```bash=
-IsolationModeLogic.updateIsolatedDebtIfIsolated(
- reservesData,
- reservesList,
- userConfig,
- reserveCache,
- paybackAmount
-);
-```
-- 13. Determine whether to liquidate with atoken (1. If liquidating with atoken: liquidate the user aToken by transferring them to the liquidator 2. If liquidating without atoken: destroy the collateral aTokens and transfer the underlying standard debt Token to the liquidator)
-```bash=
- if (params.receiveAToken) {
- _liquidateATokens(reservesData, reservesList, usersConfig, collateralReserve, params, vars);
-} else {
- _burnCollateralATokens(collateralReserve, params, vars);
-}
-```
-
-- 14.If it is judged that the amount of the liquidation agreement fee is not equal to 0, then the amount of the liquidation agreement fee will be transferred to the treasury of the collateral token.
-```bash=
-// Transfer fee to treasury if it is non-zero
-if (vars.liquidationProtocolFeeAmount != 0) {
- uint256 liquidityIndex = collateralReserve.getNormalizedIncome();
- uint256 scaledDownLiquidationProtocolFee = vars.liquidationProtocolFeeAmount.rayDiv(
- liquidityIndex
- );
- uint256 scaledDownUserBalance = vars.collateralAToken.scaledBalanceOf(params.user);
- // To avoid trying to send more aTokens than available on balance, due to 1 wei imprecision
- if (scaledDownLiquidationProtocolFee > scaledDownUserBalance) {
- vars.liquidationProtocolFeeAmount = scaledDownUserBalance.rayMul(liquidityIndex);
- }
- vars.collateralAToken.transferOnLiquidation(
- params.user,
- vars.collateralAToken.RESERVE_TREASURY_ADDRESS(),
- vars.liquidationProtocolFeeAmount
- );
-}
-```
-- 15.Transfer debt assets that are being repaid to aToken to maintain liquidity
-```bash=
-IERC20(params.debtAsset).safeTransferFrom(
- msg.sender,
- vars.debtReserveCache.aTokenAddress,
- vars.actualDebtToLiquidate
-);
-
-IAToken(vars.debtReserveCache.aTokenAddress).handleRepayment(
- msg.sender,
- params.user,
- vars.actualDebtToLiquidate
-);
-```
-- 16.Submit liquidation event
-```bash=
-event LiquidationCall(
- address indexed collateralAsset,
- address indexed debtAsset,
- address indexed user,
- uint256 debtToCover,
- uint256 liquidatedCollateralAmount,
- address liquidator,
- bool receiveAToken
-);
-
-emit LiquidationCall(
- params.collateralAsset,
- params.debtAsset,
- params.user,
- vars.actualDebtToLiquidate,
- vars.actualCollateralToLiquidate,
- msg.sender,
- params.receiveAToken
-);
-```
-## Bridge
-> source code: crest/blob/dev/aave-bridge/sources/bridge_logic.move
-
-### MintUnbacked
-- 1.Get resource data and update resource status
-
-```bash=
-function executeMintUnbacked(
- mapping(address => DataTypes.ReserveData) storage reservesData,
- mapping(uint256 => address) storage reservesList,
- DataTypes.UserConfigurationMap storage userConfig,
- address asset,
- uint256 amount,
- address onBehalfOf,
- uint16 referralCode
- ) external {
- DataTypes.ReserveData storage reserve = reservesData[asset];
- DataTypes.ReserveCache memory reserveCache = reserve.cache();
-
- reserve.updateState(reserveCache);
-```
-- 2. validate supply
-```bash=
-
-ValidationLogic.validateSupply(reserveCache, reserve, amount);
-
-function validateSupply(
- DataTypes.ReserveCache memory reserveCache,
- DataTypes.ReserveData storage reserve,
- uint256 amount
-) internal view {
- require(amount != 0, Errors.INVALID_AMOUNT);
-
- (bool isActive, bool isFrozen, , , bool isPaused) = reserveCache
- .reserveConfiguration
- .getFlags();
- require(isActive, Errors.RESERVE_INACTIVE);
- require(!isPaused, Errors.RESERVE_PAUSED);
- require(!isFrozen, Errors.RESERVE_FROZEN);
-
- uint256 supplyCap = reserveCache.reserveConfiguration.getSupplyCap();
- require(
- supplyCap == 0 ||
- ((IAToken(reserveCache.aTokenAddress).scaledTotalSupply() +
- uint256(reserve.accruedToTreasury)).rayMul(reserveCache.nextLiquidityIndex) + amount) <=
- supplyCap * (10 ** reserveCache.reserveConfiguration.getDecimals()),
- Errors.SUPPLY_CAP_EXCEEDED
- );
-}
-```
-- 3. Get unbacked in the resource and determine whether unbacked exceeds the maximum value
-```bash=
-uint256 unbackedMintCap = reserveCache.reserveConfiguration.getUnbackedMintCap();
-uint256 reserveDecimals = reserveCache.reserveConfiguration.getDecimals();
-
-uint256 unbacked = reserve.unbacked += amount.toUint128();
-
-require(
- unbacked <= unbackedMintCap * (10 ** reserveDecimals),
- Errors.UNBACKED_MINT_CAP_EXCEEDED
-);
-```
-
-- 4.Recalculate the interest rate of the debt resource updateInterestRates and update the currentLiquidityRate, currentStableBorrowRate, currentVariableBorrowRate of the resource and submit the event
-```bash=
-reserve.updateInterestRates(reserveCache, asset, 0, 0);
-
-function updateInterestRates(
- DataTypes.ReserveData storage reserve,
- DataTypes.ReserveCache memory reserveCache,
- address reserveAddress,
- uint256 liquidityAdded,
- uint256 liquidityTaken
- ) internal {
- UpdateInterestRatesLocalVars memory vars;
-
- vars.totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(
- reserveCache.nextVariableBorrowIndex
- );
-
- (
- vars.nextLiquidityRate,
- vars.nextStableRate,
- vars.nextVariableRate
- ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
- DataTypes.CalculateInterestRatesParams({
- unbacked: reserve.unbacked,
- liquidityAdded: liquidityAdded,
- liquidityTaken: liquidityTaken,
- totalStableDebt: reserveCache.nextTotalStableDebt,
- totalVariableDebt: vars.totalVariableDebt,
- averageStableBorrowRate: reserveCache.nextAvgStableBorrowRate,
- reserveFactor: reserveCache.reserveFactor,
- reserve: reserveAddress,
- aToken: reserveCache.aTokenAddress
- })
- );
-
- reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();
- reserve.currentStableBorrowRate = vars.nextStableRate.toUint128();
- reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();
-
- emit ReserveDataUpdated(
- reserveAddress,
- vars.nextLiquidityRate,
- vars.nextStableRate,
- vars.nextVariableRate,
- reserveCache.nextLiquidityIndex,
- reserveCache.nextVariableBorrowIndex
- );
-}
-```
-- 5. Mint atoken to on_behalf_of account
-- 6. Determine whether on_behalf_of is the first deposit. If so, verify whether it can be automatically used as collateral.
-```bash=
-bool isFirstSupply = IAToken(reserveCache.aTokenAddress).mint(
- msg.sender,
- onBehalfOf,
- amount,
- reserveCache.nextLiquidityIndex
-);
-
-if (isFirstSupply) {
- if (
- ValidationLogic.validateAutomaticUseAsCollateral(
- reservesData,
- reservesList,
- userConfig,
- reserveCache.reserveConfiguration,
- reserveCache.aTokenAddress
- )
- ) {
- userConfig.setUsingAsCollateral(reserve.id, true);
- emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf);
- }
-}
-```
-- 7. Submit MintUnbacked event
-```bash=
-event MintUnbacked(
- address indexed reserve,
- address user,
- address indexed onBehalfOf,
- uint256 amount,
- uint16 indexed referralCode
-);
-emit MintUnbacked(asset, msg.sender, onBehalfOf, amount, referralCode);
-```
-
-### BackUnbacked
-- 1.Get resource data and update resource status
-```bash=
- function executeBackUnbacked(
- DataTypes.ReserveData storage reserve,
- address asset,
- uint256 amount,
- uint256 fee,
- uint256 protocolFeeBps
- ) external returns (uint256) {
- DataTypes.ReserveCache memory reserveCache = reserve.cache();
-
- reserve.updateState(reserveCache);
-```
-- 2.Update resourcesaccruedToTreasury and unbacked fields
-```bash=
-uint256 backingAmount = (amount < reserve.unbacked) ? amount : reserve.unbacked;
-
-uint256 feeToProtocol = fee.percentMul(protocolFeeBps);
-uint256 feeToLP = fee - feeToProtocol;
-uint256 added = backingAmount + fee;
-
-reserveCache.nextLiquidityIndex = reserve.cumulateToLiquidityIndex(
- IERC20(reserveCache.aTokenAddress).totalSupply() +
- uint256(reserve.accruedToTreasury).rayMul(reserveCache.nextLiquidityIndex),
- feeToLP
-);
-
-reserve.accruedToTreasury += feeToProtocol.rayDiv(reserveCache.nextLiquidityIndex).toUint128();
-
-reserve.unbacked -= backingAmount.toUint128();
-```
-- 3.Recalculate the interest rate of the debt resource updateInterestRates and update the currentLiquidityRate, currentStableBorrowRate, currentVariableBorrowRate of the resource and submit the event
-```bash=
-reserve.updateInterestRates(reserveCache, asset, added, 0);
-
-function updateInterestRates(
- DataTypes.ReserveData storage reserve,
- DataTypes.ReserveCache memory reserveCache,
- address reserveAddress,
- uint256 liquidityAdded,
- uint256 liquidityTaken
- ) internal {
- UpdateInterestRatesLocalVars memory vars;
-
- vars.totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(
- reserveCache.nextVariableBorrowIndex
- );
-
- (
- vars.nextLiquidityRate,
- vars.nextStableRate,
- vars.nextVariableRate
- ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
- DataTypes.CalculateInterestRatesParams({
- unbacked: reserve.unbacked,
- liquidityAdded: liquidityAdded,
- liquidityTaken: liquidityTaken,
- totalStableDebt: reserveCache.nextTotalStableDebt,
- totalVariableDebt: vars.totalVariableDebt,
- averageStableBorrowRate: reserveCache.nextAvgStableBorrowRate,
- reserveFactor: reserveCache.reserveFactor,
- reserve: reserveAddress,
- aToken: reserveCache.aTokenAddress
- })
- );
-
- reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();
- reserve.currentStableBorrowRate = vars.nextStableRate.toUint128();
- reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();
-
- emit ReserveDataUpdated(
- reserveAddress,
- vars.nextLiquidityRate,
- vars.nextStableRate,
- vars.nextVariableRate,
- reserveCache.nextLiquidityIndex,
- reserveCache.nextVariableBorrowIndex
- );
-}
-```
-- 4. Transfer standard assets to the corresponding token address
-```bash=
-IERC20(asset).safeTransferFrom(msg.sender, reserveCache.aTokenAddress, added);
-```
-
-- 5. Submit BackUnbacked event
-```bash=
-emit BackUnbacked(asset, msg.sender, backingAmount, fee);
-```
\ No newline at end of file
diff --git a/Makefile b/Makefile
index 4bb137b..28c04cc 100644
--- a/Makefile
+++ b/Makefile
@@ -3,57 +3,74 @@ ifndef GITHUB_ACTIONS
-include .env
endif
-# default env values
-APTOS_NETWORK ?= local
-ARTIFACTS_LEVEL ?= all
-DEFAULT_FUND_AMOUNT ?= 100000000
-DEFAULT_FUNDER_PRIVATE_KEY ?= 0x0
-PYTH_HERMES_URL ?= https://hermes-beta.pyth.network
-PYTH_CONTRACT_ACCOUNT ?= 0x0
-PYTH_DEPLOYER_ACCOUNT ?= 0x0
-PYTH_WORMHOLE ?= 0x0
+# ===================== PROFILES ===================== #
-# ===================== PRIVATE KEYS ===================== #
+# aave base profiles
+AAVE_BASE_PROFILES_KEY_MAP = aave_acl=$(AAVE_ACL_PRIVATE_KEY) \
+ aave_config=$(AAVE_CONFIG_PRIVATE_KEY) \
+ aave_math=$(AAVE_MATH_PRIVATE_KEY) \
+ aave_rate=$(AAVE_RATE_PRIVATE_KEY) \
+ aave_oracle=$(AAVE_ORACLE_PRIVATE_KEY) \
+ aave_pool=$(AAVE_POOL_PRIVATE_KEY) \
+ a_tokens=$(A_TOKENS_PRIVATE_KEY) \
+ underlying_tokens=$(UNDERLYING_TOKENS_PRIVATE_KEY) \
+ variable_tokens=$(VARIABLE_TOKENS_PRIVATE_KEY) \
+ aave_large_packages=$(AAVE_LARGE_PACKAGES_PRIVATE_KEY) \
+ aave_data=$(AAVE_DATA_PRIVATE_KEY)
+
+ifeq ($(APTOS_NETWORK), local)
+ AAVE_PROFILES_KEY_MAP = $(AAVE_BASE_PROFILES_KEY_MAP) data_feeds=$(AAVE_DATA_FEEDS_PRIVATE_KEY) platform=$(AAVE_PLATFORM_PRIVATE_KEY)
+else
+ AAVE_PROFILES_KEY_MAP = $(AAVE_BASE_PROFILES_KEY_MAP)
+endif
-LARGE_PACKAGES_ACCOUNT_PRIVATE_KEY := 0xc9680e7b29b0a03344fb7e774f9919e5a99b62d25f4c00d91542571dde0e56e6
+AAVE_PROFILES := $(shell echo $(AAVE_PROFILES_KEY_MAP) | tr ' ' '\n' | cut -d '=' -f1)
-# ===================== PROFILES ===================== #
+# test user profiles
+TEST_PROFILES_KEY_MAP = test_account_0=$(TEST_ACCOUNT_0_PRIVATE_KEY) \
+ test_account_1=$(TEST_ACCOUNT_1_PRIVATE_KEY) \
+ test_account_2=$(TEST_ACCOUNT_2_PRIVATE_KEY) \
+ test_account_3=$(TEST_ACCOUNT_3_PRIVATE_KEY) \
+ test_account_4=$(TEST_ACCOUNT_4_PRIVATE_KEY) \
+ test_account_5=$(TEST_ACCOUNT_5_PRIVATE_KEY)
-PROFILES := aave_acl \
- aave_config \
- aave_math \
- aave_oracle \
- aave_mock_oracle \
- aave_pool \
- a_tokens \
- underlying_tokens \
- variable_tokens \
- deployer_pm \
- resource_pm
-
-TEST_PROFILES := test_account_0 \
- test_account_1 \
- test_account_2 \
- test_account_3 \
- test_account_4 \
- test_account_5
-
-ORACLE_PROFILES := pyth=$(PYTH_CONTRACT_ACCOUNT),deployer=$(PYTH_DEPLOYER_ACCOUNT),wormhole=$(PYTH_WORMHOLE)
-
-LARGE_PACKAGES_PROFILE := aave_large_packages=aave_large_packages
+TEST_PROFILES := $(shell echo $(TEST_PROFILES_KEY_MAP) | tr ' ' '\n' | cut -d '=' -f1)
# ===================== NAMED ADDRESSES ===================== #
-define APTOS_NAMED_ADDRESSES
-$(foreach profile,$(PROFILES),$(profile)=$(profile),)$(ORACLE_PROFILES),$(LARGE_PACKAGES_PROFILE)
+# resource named addresses
+AAVE_ORACLE_ADDRESS := $(shell [ -f .aptos/config.yaml ] && yq '.profiles.aave_oracle.account' .aptos/config.yaml || echo "")
+LARGE_PACKAGE_ADDRESS := $(shell [ -f .aptos/config.yaml ] && yq '.profiles.aave_large_packages.account' .aptos/config.yaml || echo "")
+
+RESOURCE_NAMED_ADDRESSES := aave_oracle_racc_address=$(shell \
+ [ -n "$(AAVE_ORACLE_ADDRESS)" ] && \
+ aptos account derive-resource-account-address \
+ --address "$(AAVE_ORACLE_ADDRESS)" \
+ --seed "AAVE_ORACLE" \
+ --seed-encoding "Utf8" | jq -r '.Result' || \
+ echo "")
+
+ORACLE_NAMED_ADDRESSES := $(shell \
+ if [ -n "$(CHAINLINK_DATA_FEEDS)" ] && [ -n "$(CHAINLINK_PLATFORM)" ]; then \
+ echo ", data_feeds=$(CHAINLINK_DATA_FEEDS), platform=$(CHAINLINK_PLATFORM)"; \
+ else \
+ echo ""; \
+ fi)
+
+define AAVE_NAMED_ADDRESSES
+$(foreach profile,$(AAVE_PROFILES),$(profile)=$(profile),) \
+$(RESOURCE_NAMED_ADDRESSES) \
+$(ORACLE_NAMED_ADDRESSES)
endef
# ======================= CLEAN ====================== #
+
clean-package-%:
cd ./aave-core/aave-$* && rm -rf build
-clean-root:
+clean-core:
cd ./aave-core && rm -rf build
+
# ===================== CONFIG ===================== #
set-workspace-config:
@@ -71,54 +88,97 @@ init-workspace-config:
# ===================== TESTING ===================== #
local-testnet:
- aptos node run-local-testnet --with-faucet --force-restart
+ aptos node run-localnet \
+ --assume-yes \
+ --no-txn-stream \
+ --force-restart \
+ --faucet-port 8081 \
+ --performance
+
+local-testnet-docker:
+ aptos node run-localnet \
+ --force-restart \
+ --performance \
+ --with-indexer-api \
+ --indexer-api-port 8090 \
+ --faucet-port 8081 \
+ --use-host-postgres \
+ --host-postgres-host "postgres" \
+ --host-postgres-port 5432 \
+ --host-postgres-password "postgres" \
+ --postgres-user "postgres" \
+ --postgres-database "indexer" \
+ --existing-hasura-url http://hasura:8092
ts-test:
cd test-suites && \
@pnpm i && \
- @pnpm run init-data && \
- @pnpm run core-operations && \
+ @pnpm run deploy:init-data && \
+ @pnpm run deploy:core-operations && \
@pnpm run test
test-all:
make test-acl
make test-config
make test-math
- make test-mock-oracle
+ make test-rate
+ make test-chainlink-platform
+ make test-chainlink-data-feeds
+ make test-oracle
make test-pool
# ===================== PROFILES ===================== #
init-profiles:
- @for profile in $(PROFILES); do \
- echo | aptos init --profile $$profile --network $(APTOS_NETWORK) --assume-yes --skip-faucet; \
- done
- aptos init --profile aave_large_packages --network $(APTOS_NETWORK) --assume-yes --skip-faucet --private-key $(LARGE_PACKAGES_ACCOUNT_PRIVATE_KEY);
+ @if [ "$(UPGRADE_CONTRACTS)" = "true" ]; then \
+ echo "UPGRADE_CONTRACTS is true, using fixed aave profiles"; \
+ for profile in $(shell echo $(AAVE_PROFILES_KEY_MAP) | tr ' ' '\n' | cut -d '=' -f 1); do \
+ PRIVATE_KEY=$$(echo $(AAVE_PROFILES_KEY_MAP) | tr ' ' '\n' | grep "^$$profile=" | cut -d '=' -f2); \
+ echo "Initializing profile: $$profile ..."; \
+ echo | aptos init --profile $$profile --network $(APTOS_NETWORK) --assume-yes --skip-faucet --private-key $$PRIVATE_KEY; \
+ done; \
+ else \
+ echo "UPGRADE_CONTRACTS is false, generating new aave profiles ..."; \
+ for profile in $(AAVE_PROFILES); do \
+ echo "Initializing aave profile: $$profile with random private key"; \
+ echo | aptos init --profile $$profile --network $(APTOS_NETWORK) --assume-yes --skip-faucet; \
+ done; \
+ fi
init-test-profiles:
- @for profile in $(TEST_PROFILES); do \
- echo | aptos init --profile $$profile --network $(APTOS_NETWORK) --assume-yes --skip-faucet; \
- done
+ @if [ "$(UPGRADE_CONTRACTS)" = "true" ]; then \
+ echo "UPGRADE_CONTRACTS is true, using fixed test profiles"; \
+ for profile in $(shell echo $(TEST_PROFILES_KEY_MAP) | tr ' ' '\n' | cut -d '=' -f 1); do \
+ PRIVATE_KEY=$$(echo $(TEST_PROFILES_KEY_MAP) | tr ' ' '\n' | grep "^$$profile=" | cut -d '=' -f2); \
+ echo "Initializing test profile: $$profile ..."; \
+ echo | aptos init --profile $$profile --network $(APTOS_NETWORK) --assume-yes --skip-faucet --private-key $$PRIVATE_KEY; \
+ done; \
+ else \
+ echo "UPGRADE_CONTRACTS is false, generating new test profiles ..."; \
+ for profile in $(TEST_PROFILES); do \
+ echo "Initializing test profile: $$profile with random private key"; \
+ echo | aptos init --profile $$profile --network $(APTOS_NETWORK) --assume-yes --skip-faucet; \
+ done; \
+ fi
fund-profiles:
- @for profile in $(PROFILES); do \
- aptos account fund-with-faucet --account $$profile --amount $(DEFAULT_FUND_AMOUNT) --profile $$profile && sleep 5; \
+ @for profile in $(AAVE_PROFILES); do \
+ aptos account fund-with-faucet --account $$profile --amount $(DEFAULT_FUND_AMOUNT) --profile $$profile; \
done
- aptos account fund-with-faucet --account aave_large_packages --amount $(DEFAULT_FUND_AMOUNT) --profile aave_large_packages;
fund-test-profiles:
@for profile in $(TEST_PROFILES); do \
- aptos account fund-with-faucet --account $$profile --amount $(DEFAULT_FUND_AMOUNT) --profile $$profile && sleep 5; \
+ aptos account fund-with-faucet --account $$profile --amount $(DEFAULT_FUND_AMOUNT) --profile $$profile; \
done
top-up-profiles:
- @for profile in $(PROFILES); do \
- aptos account transfer --account $$profile --amount $(DEFAULT_FUND_AMOUNT) --assume-yes --private-key $(DEFAULT_FUNDER_PRIVATE_KEY) && sleep 5; \
+ @for profile in $(AAVE_PROFILES); do \
+ aptos account transfer --account $$profile --amount $(DEFAULT_FUND_AMOUNT) --assume-yes --private-key $(DEFAULT_FUNDER_PRIVATE_KEY); \
done
top-up-test-profiles:
@for profile in $(TEST_PROFILES); do \
- aptos account transfer --account $$profile --amount $(DEFAULT_FUND_AMOUNT) --assume-yes --private-key $(DEFAULT_FUNDER_PRIVATE_KEY) && sleep 5; \
+ aptos account transfer --account $$profile --amount $(DEFAULT_FUND_AMOUNT) --assume-yes --private-key $(DEFAULT_FUNDER_PRIVATE_KEY); \
done
# ===================== PACKAGE AAVE-ACL ===================== #
@@ -128,7 +188,8 @@ compile-acl:
--included-artifacts $(ARTIFACTS_LEVEL) \
--save-metadata \
--package-dir "aave-acl" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
publish-acl:
cd aave-core && aptos move publish --assume-yes \
@@ -136,21 +197,32 @@ publish-acl:
--included-artifacts $(ARTIFACTS_LEVEL) \
--sender-account aave_acl \
--profile aave_acl \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --gas-unit-price 100 \
+ --max-gas 10000
test-acl:
cd aave-core && aptos move test \
--ignore-compile-warnings \
--skip-attribute-checks \
--package-dir "aave-acl" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
--coverage
doc-acl:
cd aave-core && aptos move document \
--skip-attribute-checks \
--package-dir "aave-acl" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+fmt-acl:
+ aptos move fmt \
+ --package-path "aave-core/aave-acl" \
+ --config-path ./movefmt.toml \
+ --emit-mode "overwrite" \
+ -v
# ===================== PACKAGE AAVE-CONFIG ===================== #
@@ -159,7 +231,8 @@ compile-config:
--included-artifacts $(ARTIFACTS_LEVEL) \
--save-metadata \
--package-dir "aave-config" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
publish-config:
cd aave-core && aptos move publish --assume-yes \
@@ -167,21 +240,32 @@ publish-config:
--included-artifacts $(ARTIFACTS_LEVEL) \
--sender-account aave_config \
--profile aave_config \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --gas-unit-price 100 \
+ --max-gas 50000
test-config:
cd aave-core && aptos move test \
--ignore-compile-warnings \
--skip-attribute-checks \
--package-dir "aave-config" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
--coverage
doc-config:
cd aave-core && aptos move document \
--skip-attribute-checks \
--package-dir "aave-config" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+fmt-config:
+ aptos move fmt \
+ --package-path "aave-core/aave-config" \
+ --config-path ./movefmt.toml \
+ --emit-mode "overwrite" \
+ -v
# ===================== PACKAGE AAVE-LARGE-PACKAGES ===================== #
@@ -190,7 +274,8 @@ compile-large-packages:
--included-artifacts $(ARTIFACTS_LEVEL) \
--save-metadata \
--package-dir "aave-large-packages" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
publish-large-packages:
cd aave-core && aptos move publish --assume-yes \
@@ -198,21 +283,32 @@ publish-large-packages:
--included-artifacts $(ARTIFACTS_LEVEL) \
--sender-account aave_large_packages \
--profile aave_large_packages \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --gas-unit-price 100 \
+ --max-gas 10000
test-large-packages:
cd aave-core && aptos move test \
--ignore-compile-warnings \
--skip-attribute-checks \
--package-dir "aave-large-packages" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
--coverage
doc-large-packages:
cd aave-core && aptos move document \
--skip-attribute-checks \
--package-dir "aave-large-packages" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+fmt-large-packages:
+ aptos move fmt \
+ --package-path "aave-core/aave-large-packages" \
+ --config-path ./movefmt.toml \
+ --emit-mode "overwrite" \
+ -v
# ===================== PACKAGE AAVE-MATH ===================== #
@@ -221,7 +317,8 @@ compile-math:
--included-artifacts $(ARTIFACTS_LEVEL) \
--save-metadata \
--package-dir "aave-math" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
publish-math:
cd aave-core && aptos move publish --assume-yes \
@@ -229,83 +326,207 @@ publish-math:
--included-artifacts $(ARTIFACTS_LEVEL) \
--sender-account aave_math \
--profile aave_math \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --gas-unit-price 100 \
+ --max-gas 10000
test-math:
cd aave-core && aptos move test \
--ignore-compile-warnings \
--skip-attribute-checks \
--package-dir "aave-math" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
--coverage
doc-math:
cd aave-core && aptos move document \
--skip-attribute-checks \
--package-dir "aave-math" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
-# ===================== PACKAGE AAVE-ORACLE ===================== #
+fmt-math:
+ aptos move fmt \
+ --package-path "aave-core/aave-math" \
+ --config-path ./movefmt.toml \
+ --emit-mode "overwrite" \
+ -v
-compile-oracle:
+# ===================== PACKAGE AAVE-RATE ===================== #
+
+compile-rate:
cd aave-core && aptos move compile \
--included-artifacts $(ARTIFACTS_LEVEL) \
- --save-metadata \
- --package-dir "aave-oracle" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --save-metadata \
+ --package-dir "aave-rate" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
-publish-oracle:
+publish-rate:
cd aave-core && aptos move publish --assume-yes \
- --package-dir "aave-oracle" \
+ --package-dir "aave-rate" \
--included-artifacts $(ARTIFACTS_LEVEL) \
- --sender-account aave_oracle \
- --profile aave_oracle \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
-
-test-oracle:
+ --sender-account aave_rate \
+ --profile aave_rate \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --gas-unit-price 100 \
+ --max-gas 20000
+
+test-rate:
cd aave-core && aptos move test \
--ignore-compile-warnings \
--skip-attribute-checks \
- --package-dir "aave-oracle" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}" \
+ --package-dir "aave-rate" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
--coverage
-doc-oracle:
+doc-rate:
cd aave-core && aptos move document \
--skip-attribute-checks \
- --package-dir "aave-oracle" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --package-dir "aave-rate" \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+fmt-rate:
+ aptos move fmt \
+ --package-path "aave-core/aave-rate" \
+ --config-path ./movefmt.toml \
+ --emit-mode "overwrite" \
+ -v
+
+# ===================== PACKAGE AAVE-DATA ===================== #
+
+compile-data:
+ cd aave-core && aptos move compile \
+ --included-artifacts $(ARTIFACTS_LEVEL) \
+ --save-metadata \
+ --package-dir "aave-data" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+publish-data:
+ cd aave-core && aptos move publish --assume-yes \
+ --package-dir "aave-data" \
+ --included-artifacts $(ARTIFACTS_LEVEL) \
+ --sender-account aave_data \
+ --profile aave_data \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+test-data:
+ cd aave-core && aptos move test \
+ --ignore-compile-warnings \
+ --skip-attribute-checks \
+ --package-dir "aave-data" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --coverage
+
+fmt-data:
+ aptos move fmt \
+ --package-path "aave-core/aave-data" \
+ --config-path ./movefmt.toml \
+ --emit-mode "overwrite" \
+ -v
+
+# ===================== PACKAGES CHAINLINK ===================== #
+
+compile-chainlink-platform:
+ cd aave-core && aptos move compile \
+ --included-artifacts $(ARTIFACTS_LEVEL) \
+ --save-metadata \
+ --package-dir "chainlink-platform" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+test-chainlink-platform:
+ cd aave-core && aptos move test \
+ --ignore-compile-warnings \
+ --skip-attribute-checks \
+ --package-dir "chainlink-platform" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --coverage
-# ===================== PACKAGE AAVE-MOCK-ORACLE ===================== #
+publish-chainlink-platform:
+ cd aave-core && aptos move publish --assume-yes \
+ --package-dir "chainlink-platform" \
+ --included-artifacts $(ARTIFACTS_LEVEL) \
+ --sender-account platform \
+ --profile platform \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
-compile-mock-oracle:
+compile-chainlink-data-feeds:
cd aave-core && aptos move compile \
--included-artifacts $(ARTIFACTS_LEVEL) \
--save-metadata \
- --package-dir "aave-mock-oracle" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --package-dir "chainlink-data-feeds" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+test-chainlink-data-feeds:
+ cd aave-core && aptos move test \
+ --ignore-compile-warnings \
+ --skip-attribute-checks \
+ --package-dir "chainlink-data-feeds" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --coverage
-publish-mock-oracle:
+publish-chainlink-data-feeds:
cd aave-core && aptos move publish --assume-yes \
- --package-dir "aave-mock-oracle" \
+ --package-dir "chainlink-data-feeds" \
--included-artifacts $(ARTIFACTS_LEVEL) \
- --sender-account aave_mock_oracle \
- --profile aave_mock_oracle \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --sender-account data_feeds \
+ --profile data_feeds \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+# ===================== PACKAGE AAVE-ORACLE ===================== #
-test-mock-oracle:
+compile-oracle:
+ cd aave-core && aptos move compile \
+ --included-artifacts $(ARTIFACTS_LEVEL) \
+ --save-metadata \
+ --package-dir "aave-oracle" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+publish-oracle:
+ cd aave-core && aptos move publish --assume-yes \
+ --package-dir "aave-oracle" \
+ --included-artifacts $(ARTIFACTS_LEVEL) \
+ --sender-account aave_oracle \
+ --profile aave_oracle \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --gas-unit-price 100 \
+ --max-gas 30000
+
+test-oracle:
cd aave-core && aptos move test \
--ignore-compile-warnings \
--skip-attribute-checks \
- --package-dir "aave-mock-oracle" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}" \
+ --package-dir "aave-oracle" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
--coverage
-doc-mock-oracle:
+doc-oracle:
cd aave-core && aptos move document \
--skip-attribute-checks \
- --package-dir "aave-mock-oracle" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --package-dir "aave-oracle" \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
+
+fmt-oracle:
+ aptos move fmt \
+ --package-path "aave-core/aave-oracle" \
+ --config-path ./movefmt.toml \
+ --emit-mode "overwrite" \
+ -v
# ===================== PACKAGE AAVE-POOL ===================== #
@@ -313,7 +534,8 @@ compile-pool:
cd aave-core && aptos move compile \
--included-artifacts $(ARTIFACTS_LEVEL) \
--save-metadata \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
publish-pool:
cd aave-core && aptos move publish --assume-yes \
@@ -321,7 +543,10 @@ publish-pool:
--chunked-publish \
--sender-account aave_pool \
--profile aave_pool \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --skip-fetch-latest-git-deps \
+ --large-packages-module-address "$(LARGE_PACKAGE_ADDRESS)" \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
+ --chunk-size 45000
publish-pool-local:
cd test-suites && \
@@ -331,82 +556,178 @@ test-pool:
cd aave-core && aptos move test \
--ignore-compile-warnings \
--skip-attribute-checks \
- --named-addresses "${APTOS_NAMED_ADDRESSES}" \
+ --skip-fetch-latest-git-deps \
+ --named-addresses "${AAVE_NAMED_ADDRESSES}" \
--coverage
doc-pool:
cd aave-core && aptos move document \
--skip-attribute-checks \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
+ --named-addresses "${AAVE_NAMED_ADDRESSES}"
-# ===================== PACKAGE AAVE-SCRIPTS ===================== #
+fmt-pool:
+ aptos move fmt \
+ --package-path "aave-core" \
+ --config-path ./movefmt.toml \
+ --emit-mode "overwrite" \
+ -v
-compile-scripts:
- cd aave-core && aptos move compile \
- --included-artifacts $(ARTIFACTS_LEVEL) \
- --save-metadata \
- --package-dir "aave-scripts" \
- --named-addresses "${APTOS_NAMED_ADDRESSES}"
-
-run-script-post-publish:
- cd aave-core && \
- aptos move run-script \
- --assume-yes \
- --compiled-script-path aave-scripts/build/AaveScripts/bytecode_scripts/post_publish.mv \
- --sender-account=aave_acl \
- --profile=aave_acl
+# ===================== AAVE-SCRIPTS ===================== #
-run-script-xxx:
- cd aave-core && \
- aptos move run-script \
- --assume-yes \
- --script-path aave-scripts/sources/post-publish.move \
+configure-acl:
+ aptos move run-script \
+ --assume-yes \
+ --compiled-script-path aave-scripts/build/AaveScripts/bytecode_scripts/configure_acl.mv \
--sender-account=aave_acl \
--profile=aave_acl
+create-reserves:
+ aptos move run-script \
+ --assume-yes \
+ --compiled-script-path aave-scripts/build/AaveScripts/bytecode_scripts/create_reserves.mv \
+ --sender-account=aave_pool \
+ --profile=aave_pool
+
+create-emodes:
+ aptos move run-script \
+ --assume-yes \
+ --compiled-script-path aave-scripts/build/AaveScripts/bytecode_scripts/create_emodes.mv \
+ --sender-account=aave_pool \
+ --profile=aave_pool
+
+configure-reserves:
+ aptos move run-script \
+ --assume-yes \
+ --compiled-script-path aave-scripts/build/AaveScripts/bytecode_scripts/configure_reserves.mv \
+ --sender-account=aave_pool \
+ --profile=aave_pool
+
+configure-interest-rates:
+ aptos move run-script \
+ --assume-yes \
+ --compiled-script-path aave-scripts/build/AaveScripts/bytecode_scripts/configure_interest_rates.mv \
+ --sender-account=aave_pool \
+ --profile=aave_pool
+
+configure-price-feeds:
+ aptos move run-script \
+ --assume-yes \
+ --compiled-script-path aave-scripts/build/AaveScripts/bytecode_scripts/configure_price_feeds.mv \
+ --sender-account=aave_pool \
+ --profile=aave_pool
+
+fmt-scripts:
+ aptos move fmt \
+ --package-path "aave-core/aave-scripts" \
+ --config-path ./movefmt.toml \
+ --emit-mode "overwrite" \
+ -v
+
# ===================== GLOBAL COMMANDS ===================== #
+ifeq ($(APTOS_NETWORK), local)
+COMPILE_CHAINLINK_TARGETS := compile-chainlink-platform compile-chainlink-data-feeds
+PUBLISH_CHAINLINK_TARGETS := publish-chainlink-platform publish-chainlink-data-feeds
+else
+COMPILE_CHAINLINK_TARGETS :=
+PUBLISH_CHAINLINK_TARGETS :=
+endif
+
compile-all:
- make compile-acl
make compile-config
- @if [ "$(APTOS_NETWORK)" = "local" ]; then \
- make compile-large-packages; \
- else \
- echo "Skipping compile-large-packages for APTOS_NETWORK different to local"; \
- fi
+ make compile-acl
+ make compile-large-packages
make compile-math
- make compile-mock-oracle
+ make compile-rate
+ @for target in $(COMPILE_CHAINLINK_TARGETS); do \
+ make $$target; \
+ done
+ make compile-oracle
make compile-pool
+ make compile-data
publish-all:
- make publish-acl
make publish-config
- @if [ "$(APTOS_NETWORK)" = "local" ]; then \
- make publish-large-packages; \
- else \
- echo "Skipping publish-large-packages for APTOS_NETWORK different than local"; \
- fi
+ make publish-acl
+ make publish-large-packages
make publish-math
- make publish-mock-oracle
+ make publish-rate
+ @for target in $(PUBLISH_CHAINLINK_TARGETS); do \
+ make $$target; \
+ done
+ make publish-oracle
make publish-pool
+ make publish-data
doc-all:
- make doc-acl
make doc-config
+ make doc-acl
make doc-large-packages
make doc-math
- make doc-mock-oracle
+ make doc-rate
+ make doc-oracle
make doc-pool
clean-all:
- make clean-package-acl
make clean-package-config
- make clean-large-packages
+ make clean-package-acl
+ make clean-package-large-packages
make clean-package-math
- make clean-package-mock-oracle
+ make clean-package-rate
+ make clean-chainlink-platform
+ make clean-chainlink-data-feeds
make clean-package-oracle
- make clean-root
+ make clean-core
+ make clean-data
+
+# ------------------------------------------------------------
+# Formatting
+# ------------------------------------------------------------
+
+fmt: fmt-move fmt-prettier fmt-markdown
# fmt & lint all directories
-fmt-all:
- movefmt --config-path=./movefmt.toml --emit "overwrite" -v
\ No newline at end of file
+fmt-move:
+ make fmt-acl
+ make fmt-config
+ make fmt-large-packages
+ make fmt-math
+ make fmt-rate
+ make fmt-oracle
+ make fmt-pool
+ make fmt-data
+ make fmt-scripts
+
+fmt-prettier:
+ pnpm prettier:fix
+
+fmt-markdown:
+ pnpm md:fix
+
+# ------------------------------------------------------------
+# Validate code
+# ------------------------------------------------------------
+
+lint-prettier:
+ pnpm prettier:validate
+
+lint-markdown:
+ pnpm md:lint
+
+lint-codespell: ensure-codespell
+ codespell --skip "*.json"
+
+ensure-codespell:
+ @if ! command -v codespell &> /dev/null; then \
+ echo "codespell not found. Please install it by running the command `pip install codespell` or refer to the following link for more information: https://github.com/codespell-project/codespell" \
+ exit 1; \
+ fi
+
+lint:
+ make lint-prettier && \
+ make lint-markdown && \
+ make fmt && \
+ make lint-codespell
+
+fix-lint:
+ make fmt
diff --git a/README.md b/README.md
index 798f036..5a1745a 100644
--- a/README.md
+++ b/README.md
@@ -10,8 +10,7 @@ This is the official Aptos version of the Aave V3 Protocol.
├── aave-config // Configurator Package
├── aave-flash-loan // Flash loan Package
├── aave-math // Math library Package
-├── aave-oracle // Pyth Oracle Package
-├── aave-mock-oracle // Mock Oracle Package
+├── aave-oracle // Chainlink Oracle Package
├── aave-pool // Pool Package
├── aave-supply-borrow // Supply-Borrow Package
├── aave-tokens // Tokens Package
@@ -95,63 +94,53 @@ Dependencies for all packages:
## 1. Clone the code
```bash=
-git clone this-project-code && cd this-project-code
+git clone (aave-aptos-v3)(https://github.com/aave/aptos-v3) && cd into it
```
Make sure you have the following installed and configured:
- Aptos-Cli [see here](https://aptos.dev/tools/aptos-cli/)
+- Yq tool: [see here](https://github.com/mikefarah/yq)
- NodeJS/pnpm/npm/yarn [see here](https://pnpm.io/installation)
+- Codespell [see here](https://pypi.org/project/codespell/)
+- Pre-commit [see here](https://pre-commit.com/#install)
+- Python3 [see here](https://www.python.org/)
-## 2. Local Testnet (recommended for development)
+## 2. Local Testnet using Makefile
Local testnet commands are all bundled inside a `Makefile` at the root.
-There is a `.env.local` template at the root that we recommend renaming to `.env` before executing the remaining steps.
+There is a `.env.template` template at the root that we recommend renaming to `.env` and adjusting the values of before executing the remaining steps.
Prior to all, run:
-```shell
-make set-workspace-config
-```
-
-to set up your aptos profiles configuration to point at the project workspace.
-
-Then, to run a local testnet, execute:
-
```shell
make local-testnet
```
+to start the local testnet without indexer. It usually takes about 10 seconds for the local testnet to be fully operational.
+
Once local testnet is running, in another terminal do:
```shell
make init-profiles && make init-test-profiles && make fund-profiles && make fund-test-profiles
```
-This will create all needed accounts for publishing Aaave V3 and save them under a file under `.aptos/config.yaml` at the workspace root.
-The accounts will be prefunded with APT too. The structure of the file is something like:
-```shell
- profiles:
- profileX:
- private_key: "..."
- public_key: "..."
- account: ...
- rest_url: "https://fullnode.....aptoslabs.com"
- faucet_url: "https://faucet.....aptoslabs.com"
- profileY:
- ...
-```
+This will create all needed accounts for publishing Aave V3 and save them under a file under `.aptos/config.yaml` at the workspace root.
+The accounts will be prefunded with APT too.
+
All aave packages can be now compiled using the command:
```shell
make compile-all
```
+
and subsequently deployed to local testnet via:
```shell
make publish-all
```
+
If needed one could also run all aptos unit tests via:
```shell
@@ -161,53 +150,26 @@ make test-all
To view transactions or query any data deployed on the local testnet you
can use the following url:
-https://explorer.aptoslabs.com/?network=local
-
-
-## 3. Testnet, Devnet
-
-All necessary commands required for mainnet, testnet and devnet are bundled in the `Makefile` at the root.
+
-Before anything, for testnet or devnet, the `.env.testnet` file located at the root of this repo is to be renamed to `.env` and adjusted before compiling
-and publishing depending on what network we want to deploy our packages to. The default configuration is pointing
-at Aptos `testnet`, but one could also easily change the environmental variable `APTOS_NETWORK` to `devnet`.
+## 3. Local Testnet using Apterly
-For testnet and devnet deployment a funded with APT account (5 APT is more than enough) is required so make sure you have one and replace
-its private key in `DEFAULT_FUNDER_PRIVATE_KEY`.
-
-The remaining steps are as similar to the local testnet, but using the `Makefile`.
-
-```shell
-make compile-all
-```
-and subsequently deployed to local testnet via:
-
-```shell
-make publish-all
-```
-If needed one could also run all aptos unit tests via:
-
-```shell
-make test-all
-```
-
-**NOTE**: For mainnet and testnet deployments we would rather create the profiles which the `make init-profiles` command
-does ourselves and fund them through the faucet before deployment.
+Apterly is a tool that mimics some of the functionalities that Tenderly offers. You can read more about it under [Apterly](apterly/README.md). Follow the Readme if you want to deploy the protocol using docker-compose.
## 4. Checking contracts in explorer
+
For each published package, get the transaction id `YOUR_TX_ID` and replace it in the url below to see more data. Also make
sure you are using the correct network in the url - `devnet` or `testnet`.
-> https://explorer.aptoslabs.com/txn/{YOUR_TX_ID}?network=NETWORK_NAME
-
+>
## 5. Running Aptos Unit Tests
-These tests do not require any published data and can thus be executed everytime, prerequisite being we have all named
+These tests do not require any published data and can thus be executed every time, prerequisite being we have all named
addresses set:
```shell
- $ make test-all
+make test-all
```
## 6. Running Typescript Integration/e2e Tests
@@ -215,7 +177,7 @@ addresses set:
These tests are only to be run after having successfully published all packages:
```shell
- $ make ts-test
+make ts-test
```
## 7. Creating Aptos Documentation
@@ -223,10 +185,5 @@ These tests are only to be run after having successfully published all packages:
To create extensive Aptos documentation for all modules usually generated under the `doc` folder of each package, run:
```shell
- $ make doc-all
+make doc-all
```
-
-## 8. Business Logic (WIP)
-
-Please read the following readme which explains the business logic:
-[Business Logic](./BusinessLogic.md)
\ No newline at end of file
diff --git a/aave-core/.gitignore b/aave-core/.gitignore
new file mode 100644
index 0000000..0e5f3e7
--- /dev/null
+++ b/aave-core/.gitignore
@@ -0,0 +1,2 @@
+chainlink-data-feeds/*
+chainlink-platform/*
diff --git a/aave-core/Move.toml b/aave-core/Move.toml
index 1cf873f..8eff480 100644
--- a/aave-core/Move.toml
+++ b/aave-core/Move.toml
@@ -14,6 +14,7 @@ AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir
AaveAcl = { local = "./aave-acl" }
AaveConfig = { local = "./aave-config" }
AaveMath = { local = "./aave-math" }
-AaveMockOracle = { local = "./aave-mock-oracle" }
+AaveOracle = { local = "aave-oracle" }
+AaveRate = { local = "./aave-rate" }
[dev-dependencies]
diff --git a/aave-core/aave-acl/Move.toml b/aave-core/aave-acl/Move.toml
index 2dd588c..68636ab 100644
--- a/aave-core/aave-acl/Move.toml
+++ b/aave-core/aave-acl/Move.toml
@@ -11,5 +11,6 @@ aave_acl = '_'
[dependencies]
AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework/", rev = "mainnet" }
+AaveConfig = { local = "../aave-config" }
-[dev-dependencies]
\ No newline at end of file
+[dev-dependencies]
diff --git a/aave-core/aave-acl/sources/acl_manage.move b/aave-core/aave-acl/sources/acl_manage.move
index fc9f555..355eb7f 100644
--- a/aave-core/aave-acl/sources/acl_manage.move
+++ b/aave-core/aave-acl/sources/acl_manage.move
@@ -34,7 +34,9 @@ module aave_acl::acl_manage {
use aptos_std::smart_table::{Self, SmartTable};
use aptos_framework::event;
- const DEFAULT_ADMIN_ROLE: vector = b"DEFAULT_ADMIN";
+ use aave_config::error_config;
+
+ const DEFAULT_ADMIN_ROLE: vector = b"";
const POOL_ADMIN_ROLE: vector = b"POOL_ADMIN";
const EMERGENCY_ADMIN_ROLE: vector = b"EMERGENCY_ADMIN";
const RISK_ADMIN_ROLE: vector = b"RISK_ADMIN";
@@ -46,17 +48,8 @@ module aave_acl::acl_manage {
const ADMIN_CONTROLLED_ECOSYSTEM_RESERVE_FUNDS_ADMIN_ROLE: vector = b"ADMIN_CONTROLLED_ECOSYSTEM_RESERVE_FUNDS_ADMIN";
const REWARDS_CONTROLLER_ADMIN_ROLE: vector = b"REWARDS_CONTROLLER_ADMIN_ROLE";
- // You are not an administrator and cannot initialize resources.
- const ENOT_MANAGEMENT: u64 = 1;
- // Role does not exist.
- 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`
+ /// @dev Emitted when `new_admin_role` is set as ``role``'s admin role, replacing `previous_admin_role`
///
/// `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
/// {RoleAdminChanged} not being emitted signaling this.
@@ -98,15 +91,20 @@ module aave_acl::acl_manage {
}
#[test_only]
- public fun test_init_module(user: &signer) acquires Roles {
- init_module(user);
- grant_default_admin_role(user);
+ public fun test_init_module(admin: &signer) acquires Roles {
+ init_module(admin);
+ grant_default_admin_role(admin);
}
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(
+ admin,
+ Roles {
+ acl_instance: smart_table::new()
+ }
+ );
}
public entry fun grant_default_admin_role(admin: &signer) acquires Roles {
@@ -116,11 +114,11 @@ module aave_acl::acl_manage {
}
fun check_super_admin(admin: address) {
- assert!(admin == @aave_acl, ENOT_MANAGEMENT);
+ assert!(admin == @aave_acl, error_config::get_enot_acl_owner());
}
fun only_role(role: String, user: address) acquires Roles {
- assert!(has_role(role, user), EROLE_NOT_ADMIN);
+ assert!(has_role(role, user), error_config::get_erole_missmatch());
}
#[view]
@@ -133,25 +131,30 @@ module aave_acl::acl_manage {
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)
+ return string::utf8(b"")
};
smart_table::borrow(&roles.acl_instance, role).admin_role
}
- /// @dev Sets `adminRole` as ``role``'s admin role.
+ /// @dev Sets `admin_role` 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;
+ let previous_admin_role = get_role_admin(role);
+ let roles = borrow_global_mut(@aave_acl);
+
+ if (!smart_table::contains(&mut roles.acl_instance, role)) {
+ let members = smart_table::new();
+ let role_data = RoleData { members, admin_role };
+ smart_table::add(&mut roles.acl_instance, role, role_data);
+ } else {
+ let role_data = smart_table::borrow_mut(&mut roles.acl_instance, role);
+ role_data.admin_role = admin_role;
+ };
event::emit(
RoleAdminChanged { role, previous_admin_role, new_admin_role: admin_role }
@@ -159,7 +162,9 @@ module aave_acl::acl_manage {
}
#[view]
- /// @dev Returns `true` if `account` has been granted `role`.
+ /// @dev Returns `true` if `user` has been granted `role`.
+ /// @param role The role identifier
+ /// @param user The account to check
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)) {
@@ -195,7 +200,7 @@ module aave_acl::acl_manage {
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() };
+ let role_data = RoleData { members, admin_role: string::utf8(b"") };
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);
@@ -222,7 +227,10 @@ module aave_acl::acl_manage {
public entry fun renounce_role(
admin: &signer, role: String, user: address
) acquires Roles {
- assert!(signer::address_of(admin) == user, EROLE_CAN_ONLY_RENOUNCE_SELF);
+ assert!(
+ signer::address_of(admin) == user,
+ error_config::get_erole_can_only_renounce_self()
+ );
revoke_role_internal(admin, role, user);
}
@@ -349,28 +357,28 @@ module aave_acl::acl_manage {
has_role(get_funds_admin_role(), admin)
}
- public entry fun add_emission_admin_role(admin: &signer, user: address) acquires Roles {
+ public entry fun add_emission_admin(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 Roles {
+ public entry fun remove_emission_admin(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 Roles {
+ public fun is_emission_admin(admin: address): bool acquires Roles {
has_role(get_emission_admin_role(), admin)
}
- public entry fun add_admin_controlled_ecosystem_reserve_funds_admin_role(
+ public entry fun add_admin_controlled_ecosystem_reserve_funds_admin(
admin: &signer, user: address
) acquires Roles {
- grant_role(admin, get_admin_controlled_ecosystem_reserve_funds_admin_role(), user);
+ grant_role(
+ admin, get_admin_controlled_ecosystem_reserve_funds_admin_role(), user
+ );
}
- public entry fun remove_admin_controlled_ecosystem_reserve_funds_admin_role(
+ public entry fun remove_admin_controlled_ecosystem_reserve_funds_admin(
admin: &signer, user: address
) acquires Roles {
revoke_role(
@@ -379,26 +387,26 @@ module aave_acl::acl_manage {
}
#[view]
- public fun is_admin_controlled_ecosystem_reserve_funds_admin_role(
+ public fun is_admin_controlled_ecosystem_reserve_funds_admin(
admin: address
): bool acquires Roles {
has_role(get_admin_controlled_ecosystem_reserve_funds_admin_role(), admin)
}
- public entry fun add_rewards_controller_admin_role(
+ public entry fun add_rewards_controller_admin(
admin: &signer, user: address
) acquires Roles {
grant_role(admin, get_rewards_controller_admin_role(), user);
}
- public entry fun remove_rewards_controller_admin_role(
+ public entry fun remove_rewards_controller_admin(
admin: &signer, user: address
) acquires Roles {
revoke_role(admin, get_rewards_controller_admin_role(), user);
}
#[view]
- public fun is_rewards_controller_admin_role(admin: address): bool acquires Roles {
+ public fun is_rewards_controller_admin(admin: address): bool acquires Roles {
has_role(get_rewards_controller_admin_role(), admin)
}
diff --git a/aave-core/aave-acl/tests/acl_manage_tests.move b/aave-core/aave-acl/tests/acl_manage_tests.move
index f0f8f30..983e4aa 100644
--- a/aave-core/aave-acl/tests/acl_manage_tests.move
+++ b/aave-core/aave-acl/tests/acl_manage_tests.move
@@ -4,61 +4,61 @@ module aave_acl::acl_manage_tests {
use std::string::utf8;
use aave_acl::acl_manage::{
- add_admin_controlled_ecosystem_reserve_funds_admin_role,
+ add_admin_controlled_ecosystem_reserve_funds_admin,
add_asset_listing_admin,
add_bridge,
add_emergency_admin,
- add_emission_admin_role,
+ add_emission_admin,
add_flash_borrower,
add_funds_admin,
add_pool_admin,
- add_rewards_controller_admin_role,
+ add_rewards_controller_admin,
add_risk_admin,
+ get_admin_controlled_ecosystem_reserve_funds_admin_role,
+ get_admin_controlled_ecosystem_reserve_funds_admin_role_for_testing,
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_emission_admin_role,
+ get_emissions_admin_role_for_testing,
get_flash_borrower_role,
get_flash_borrower_role_for_testing,
+ get_funds_admin_role,
+ get_funds_admin_role_for_testing,
get_pool_admin_role,
get_pool_admin_role_for_testing,
+ get_rewards_controller_admin_role,
+ get_rewards_controller_admin_role_for_testing,
get_risk_admin_role,
get_risk_admin_role_for_testing,
grant_role,
has_role,
- is_admin_controlled_ecosystem_reserve_funds_admin_role,
+ is_admin_controlled_ecosystem_reserve_funds_admin,
is_asset_listing_admin,
is_bridge,
is_emergency_admin,
- is_emission_admin_role,
+ is_emission_admin,
is_flash_borrower,
is_funds_admin,
is_pool_admin,
- is_rewards_controller_admin_role,
+ is_rewards_controller_admin,
is_risk_admin,
- remove_admin_controlled_ecosystem_reserve_funds_admin_role,
+ remove_admin_controlled_ecosystem_reserve_funds_admin,
remove_asset_listing_admin,
remove_bridge,
remove_emergency_admin,
- remove_emission_admin_role,
+ remove_emission_admin,
remove_flash_borrower,
remove_funds_admin,
remove_pool_admin,
- remove_rewards_controller_admin_role,
+ remove_rewards_controller_admin,
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
+ test_init_module
};
const TEST_SUCCESS: u64 = 1;
@@ -68,8 +68,9 @@ module aave_acl::acl_manage_tests {
#[test]
fun test_asset_listing_admin_role() {
assert!(
- get_asset_listing_admin_role() == get_asset_listing_admin_role_for_testing(),
- TEST_SUCCESS,
+ get_asset_listing_admin_role()
+ == get_asset_listing_admin_role_for_testing(),
+ TEST_SUCCESS
);
}
@@ -82,7 +83,7 @@ module aave_acl::acl_manage_tests {
fun test_get_flash_borrower_role() {
assert!(
get_flash_borrower_role() == get_flash_borrower_role_for_testing(),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -95,7 +96,7 @@ module aave_acl::acl_manage_tests {
fun test_get_emergency_admin_role() {
assert!(
get_emergency_admin_role() == get_emergency_admin_role_for_testing(),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -115,7 +116,7 @@ module aave_acl::acl_manage_tests {
fun test_emission_admin_role() {
assert!(
get_emission_admin_role() == get_emissions_admin_role_for_testing(),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -124,7 +125,7 @@ module aave_acl::acl_manage_tests {
assert!(
get_admin_controlled_ecosystem_reserve_funds_admin_role()
== get_admin_controlled_ecosystem_reserve_funds_admin_role_for_testing(),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -133,7 +134,7 @@ module aave_acl::acl_manage_tests {
assert!(
get_rewards_controller_admin_role()
== get_rewards_controller_admin_role_for_testing(),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -149,7 +150,7 @@ module aave_acl::acl_manage_tests {
grant_role(
super_admin,
get_asset_listing_admin_role_for_testing(),
- signer::address_of(test_addr),
+ signer::address_of(test_addr)
);
// check the address has the role assigned
assert!(is_asset_listing_admin(signer::address_of(test_addr)), TEST_SUCCESS);
@@ -175,7 +176,7 @@ module aave_acl::acl_manage_tests {
grant_role(
super_admin,
get_flash_borrower_role_for_testing(),
- signer::address_of(test_addr),
+ signer::address_of(test_addr)
);
// check the address has the role assigned
assert!(is_flash_borrower(signer::address_of(test_addr)), TEST_SUCCESS);
@@ -187,7 +188,9 @@ module aave_acl::acl_manage_tests {
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)
+ 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);
@@ -201,7 +204,7 @@ module aave_acl::acl_manage_tests {
grant_role(
super_admin,
get_emergency_admin_role_for_testing(),
- signer::address_of(test_addr),
+ signer::address_of(test_addr)
);
// check the address has the role assigned
assert!(is_emergency_admin(signer::address_of(test_addr)), TEST_SUCCESS);
@@ -213,7 +216,9 @@ module aave_acl::acl_manage_tests {
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)
+ 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);
@@ -227,7 +232,7 @@ module aave_acl::acl_manage_tests {
grant_role(
super_admin,
get_funds_admin_role_for_testing(),
- signer::address_of(test_addr),
+ signer::address_of(test_addr)
);
// check the address has the role assigned
assert!(is_funds_admin(signer::address_of(test_addr)), TEST_SUCCESS);
@@ -241,10 +246,10 @@ module aave_acl::acl_manage_tests {
grant_role(
super_admin,
get_emissions_admin_role_for_testing(),
- signer::address_of(test_addr),
+ signer::address_of(test_addr)
);
// check the address has the role assigned
- assert!(is_emission_admin_role(signer::address_of(test_addr)), TEST_SUCCESS);
+ assert!(is_emission_admin(signer::address_of(test_addr)), TEST_SUCCESS);
}
#[test(super_admin = @aave_acl, test_addr = @0x01)]
@@ -257,14 +262,14 @@ module aave_acl::acl_manage_tests {
grant_role(
super_admin,
get_admin_controlled_ecosystem_reserve_funds_admin_role_for_testing(),
- signer::address_of(test_addr),
+ signer::address_of(test_addr)
);
// check the address has the role assigned
assert!(
- is_admin_controlled_ecosystem_reserve_funds_admin_role(
+ is_admin_controlled_ecosystem_reserve_funds_admin(
signer::address_of(test_addr)
),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -278,12 +283,12 @@ module aave_acl::acl_manage_tests {
grant_role(
super_admin,
get_rewards_controller_admin_role_for_testing(),
- signer::address_of(test_addr),
+ 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,
+ is_rewards_controller_admin(signer::address_of(test_addr)),
+ TEST_SUCCESS
);
}
@@ -296,12 +301,16 @@ module aave_acl::acl_manage_tests {
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)
+ 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,
+ !has_role(
+ get_pool_admin_role_for_testing(), signer::address_of(other_addr)
+ ),
+ TEST_SUCCESS
);
}
@@ -312,7 +321,9 @@ module aave_acl::acl_manage_tests {
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)
+ 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);
@@ -325,12 +336,14 @@ module aave_acl::acl_manage_tests {
// now remove the role
revoke_role(
- test_addr, get_pool_admin_role_for_testing(), signer::address_of(test_addr)
+ 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,
+ TEST_SUCCESS
);
}
@@ -454,13 +467,13 @@ module aave_acl::acl_manage_tests {
// init the module
test_init_module(super_admin);
// add the asset listing role to some address
- add_emission_admin_role(super_admin, signer::address_of(test_addr));
+ add_emission_admin(super_admin, signer::address_of(test_addr));
// check the address has the role assigned
- assert!(is_emission_admin_role(signer::address_of(test_addr)), TEST_SUCCESS);
+ assert!(is_emission_admin(signer::address_of(test_addr)), TEST_SUCCESS);
// remove pool admin
- remove_emission_admin_role(super_admin, signer::address_of(test_addr));
+ remove_emission_admin(super_admin, signer::address_of(test_addr));
// check the address has no longer the role assigned
- assert!(!is_emission_admin_role(signer::address_of(test_addr)), TEST_SUCCESS);
+ assert!(!is_emission_admin(signer::address_of(test_addr)), TEST_SUCCESS);
}
#[test(super_admin = @aave_acl, test_addr = @0x01)]
@@ -470,26 +483,26 @@ 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(
+ add_admin_controlled_ecosystem_reserve_funds_admin(
super_admin, signer::address_of(test_addr)
);
// check the address has the role assigned
assert!(
- is_admin_controlled_ecosystem_reserve_funds_admin_role(
+ is_admin_controlled_ecosystem_reserve_funds_admin(
signer::address_of(test_addr)
),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
// remove pool admin
- remove_admin_controlled_ecosystem_reserve_funds_admin_role(
+ remove_admin_controlled_ecosystem_reserve_funds_admin(
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(
+ !is_admin_controlled_ecosystem_reserve_funds_admin(
signer::address_of(test_addr)
),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -500,18 +513,18 @@ module aave_acl::acl_manage_tests {
// init the module
test_init_module(super_admin);
// add the asset listing role to some address
- add_rewards_controller_admin_role(super_admin, signer::address_of(test_addr));
+ add_rewards_controller_admin(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,
+ is_rewards_controller_admin(signer::address_of(test_addr)),
+ TEST_SUCCESS
);
// remove pool admin
- remove_rewards_controller_admin_role(super_admin, signer::address_of(test_addr));
+ remove_rewards_controller_admin(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,
+ !is_rewards_controller_admin(signer::address_of(test_addr)),
+ TEST_SUCCESS
);
}
}
diff --git a/aave-core/aave-config/sources/error_config.move b/aave-core/aave-config/sources/error_config.move
index 33e5bdf..55fca99 100644
--- a/aave-core/aave-config/sources/error_config.move
+++ b/aave-core/aave-config/sources/error_config.move
@@ -1,7 +1,7 @@
/// @title Errors library
/// @author Aave
/// @notice Defines the error messages emitted by the different contracts of the Aave protocol
-module aave_config::error {
+module aave_config::error_config {
/// 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
@@ -164,25 +164,89 @@ module aave_config::error {
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;
+ /// Aptos has introduced a new business logic error code range from 1001 to 2000.
+
+ /// aave_acl module error code range from 1001 to 1100.
+ /// Account is not the acl's owner.
+ const ENOT_ACL_OWNER: u64 = 1001;
+ /// Account is missing role.
+ const EROLE_MISSMATCH: u64 = 1002;
+ /// can only renounce roles for self
+ const EROLE_CAN_ONLY_RENOUNCE_SELF: u64 = 1003;
+
+ /// aave_math module error code range from 1101 to 1200.
+ /// Calculation results in overflow
+ const EOVERFLOW: u64 = 1101;
+ /// Cannot divide by zero
+ const EDIVISION_BY_ZERO: u64 = 1102;
+
+ /// aave_oracle module error code range from 1201 to 1300.
+ /// Account is not the oracle's owner.
+ const ENOT_ORACLE_OWNER: u64 = 1201;
+ const EORACLE_RESOURCE_NOT_FOUND: u64 = 1202;
+
+ /// aave_oracle
+ /// Not an asset listing or a pool admin error
+ const ENOT_ASSET_LISTING_OR_POOL_ADMIN: u64 = 1203;
+ /// base currency not set
+ const EBASE_CURRENCY_NOT_SET: u64 = 1204;
+ /// identical base currency already added
+ const EIDENTICAL_BASE_CURRENCY_ALREADY_ADDED: u64 = 1205;
+ /// missing price feed identifier
+ const EMISSING_PRICE_FEED_IDENTIFIER: u64 = 1206;
+ /// missing price vaa
+ const EMISSING_PRICE_VAA: u64 = 1207;
+ /// not existing price feed identifier
+ const EPRICE_FEED_IDENTIFIER_NOT_EXIST: u64 = 1208;
+
+ /// aave_rate module error code range from 1301 to 1400.
+ /// Account is not the rate's owner.
+ const ENOT_RATE_OWNER: u64 = 1301;
+
+ /// aave_pool module error code range from 1401 to 1500.
+ /// Account is not the pool's owner.
+ const ENOT_POOL_OWNER: u64 = 1401;
+ /// User is not listed
+ const EUSER_NOT_LISTED: u64 = 1402;
/// Mismatch of reserves count in storage
- const ERESERVES_STORAGE_COUNT_MISMATCH: u64 = 93;
+ const ERESERVES_STORAGE_COUNT_MISMATCH: u64 = 1403;
/// 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 = 1404;
/// Account does not exist
- const EACCOUNT_DOES_NOT_EXIST: u64 = 95;
-
+ const EACCOUNT_DOES_NOT_EXIST: u64 = 1405;
/// Flashloan payer is different from the flashloan receiver
- const EFLASHLOAN_PAYER_NOT_RECEIVER: u64 = 95;
+ const EFLASHLOAN_PAYER_NOT_RECEIVER: u64 = 1406;
+ /// Price oracle validation failed
+ const EPRICE_ORACLE_CHECK_FAILED: u64 = 1407;
+ /// reserve list not initialized
+ const ERESERVE_LIST_NOT_INITIALIZED: u64 = 1408;
+
+ /// aave_tokens
+ /// Token already exists
+ const ETOKEN_ALREADY_EXISTS: u64 = 1409;
+ /// Token not exist
+ const ETOKEN_NOT_EXIST: u64 = 1410;
+ /// Resource not exist
+ const ERESOURCE_NOT_EXIST: u64 = 1411;
+ /// Token name already exist
+ const ETOKEN_NAME_ALREADY_EXIST: u64 = 1412;
+ /// Token symbol already exist
+ const ETOKEN_SYMBOL_ALREADY_EXIST: u64 = 1413;
+
+ /// coin migrations
+ /// User has insufficient coins to wrap
+ const EINSUFFICIENT_COINS_TO_WRAP: u64 = 1414;
+ /// User has insufficient fungible assets to unwrap
+ const EINSUFFICIENT_FAS_TO_UNWRAP: u64 = 1415;
+ /// The coin has not been mapped to a fungible asset by Aptos
+ const EUNMAPPED_COIN_TO_FA: u64 = 1416;
public fun get_ecaller_not_pool_admin(): u64 {
ECALLER_NOT_POOL_ADMIN
@@ -400,10 +464,6 @@ module aave_config::error {
EINCONSISTENT_EMODE_CATEGORY
}
- public fun get_eprice_oracle_sentinel_check_failed(): u64 {
- EPRICE_ORACLE_SENTINEL_CHECK_FAILED
- }
-
public fun get_easset_not_borrowable_in_isolation(): u64 {
EASSET_NOT_BORROWABLE_IN_ISOLATION
}
@@ -520,6 +580,62 @@ module aave_config::error {
ERESERVE_DEBT_NOT_ZERO
}
+ public fun get_enot_acl_owner(): u64 {
+ ENOT_ACL_OWNER
+ }
+
+ public fun get_erole_missmatch(): u64 {
+ EROLE_MISSMATCH
+ }
+
+ public fun get_erole_can_only_renounce_self(): u64 {
+ EROLE_CAN_ONLY_RENOUNCE_SELF
+ }
+
+ public fun get_eoverflow(): u64 {
+ EOVERFLOW
+ }
+
+ public fun get_edivision_by_zero(): u64 {
+ EDIVISION_BY_ZERO
+ }
+
+ public fun get_enot_oracle_owner(): u64 {
+ ENOT_ORACLE_OWNER
+ }
+
+ public fun get_eoracle_resource_not_found(): u64 {
+ EORACLE_RESOURCE_NOT_FOUND
+ }
+
+ public fun get_enot_asset_listing_or_pool_admin(): u64 {
+ ENOT_ASSET_LISTING_OR_POOL_ADMIN
+ }
+
+ public fun get_ebase_currency_not_set(): u64 {
+ EBASE_CURRENCY_NOT_SET
+ }
+
+ public fun get_eidentical_base_currency_already_added(): u64 {
+ EIDENTICAL_BASE_CURRENCY_ALREADY_ADDED
+ }
+
+ public fun get_emissing_price_feed_identifier(): u64 {
+ EMISSING_PRICE_FEED_IDENTIFIER
+ }
+
+ public fun get_emissing_price_vaa(): u64 {
+ EMISSING_PRICE_VAA
+ }
+
+ public fun get_eprice_feed_identifier_not_exist(): u64 {
+ EPRICE_FEED_IDENTIFIER_NOT_EXIST
+ }
+
+ public fun get_enot_pool_owner(): u64 {
+ ENOT_POOL_OWNER
+ }
+
public fun get_eflashloan_disabled(): u64 {
EFLASHLOAN_DISABLED
}
@@ -539,4 +655,48 @@ module aave_config::error {
public fun get_flashloan_payer_not_receiver(): u64 {
EFLASHLOAN_PAYER_NOT_RECEIVER
}
+
+ public fun get_eprice_oracle_check_failed(): u64 {
+ EPRICE_ORACLE_CHECK_FAILED
+ }
+
+ public fun get_enot_rate_owner(): u64 {
+ ENOT_RATE_OWNER
+ }
+
+ public fun get_ereserve_list_not_initialized(): u64 {
+ ERESERVE_LIST_NOT_INITIALIZED
+ }
+
+ public fun get_etoken_already_exists(): u64 {
+ ETOKEN_ALREADY_EXISTS
+ }
+
+ public fun get_etoken_not_exist(): u64 {
+ ETOKEN_NOT_EXIST
+ }
+
+ public fun get_eresource_not_exist(): u64 {
+ ERESOURCE_NOT_EXIST
+ }
+
+ public fun get_etoken_name_already_exist(): u64 {
+ ETOKEN_NAME_ALREADY_EXIST
+ }
+
+ public fun get_etoken_symbol_already_exist(): u64 {
+ ETOKEN_SYMBOL_ALREADY_EXIST
+ }
+
+ public fun get_einsufficient_coins_to_wrap(): u64 {
+ EINSUFFICIENT_COINS_TO_WRAP
+ }
+
+ public fun get_einsufficient_fas_to_unwrap(): u64 {
+ EINSUFFICIENT_FAS_TO_UNWRAP
+ }
+
+ public fun get_eunmapped_coin_to_fa(): u64 {
+ EUNMAPPED_COIN_TO_FA
+ }
}
diff --git a/aave-core/aave-config/sources/reserve_config.move b/aave-core/aave-config/sources/reserve_config.move
index 6000061..9de42fa 100644
--- a/aave-core/aave-config/sources/reserve_config.move
+++ b/aave-core/aave-config/sources/reserve_config.move
@@ -1,8 +1,8 @@
/// @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;
+module aave_config::reserve_config {
+ use aave_config::error_config;
use aave_config::helper;
const LTV_MASK: u256 =
@@ -98,7 +98,7 @@ module aave_config::reserve {
/// bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled
/// bit 212-251 debt ceiling for isolation mode with (ReserveConfigurationMap::DEBT_CEILING_DECIMALS) decimals
/// bit 252-255 unused
- data: u256,
+ data: u256
}
/// @notice init the reserve configuration
@@ -129,10 +129,11 @@ module aave_config::reserve {
) {
assert!(
liquidation_threshold <= MAX_VALID_LIQUIDATION_THRESHOLD,
- error_config::get_einvalid_liq_threshold(),
+ error_config::get_einvalid_liq_threshold()
);
self.data = (self.data & LIQUIDATION_THRESHOLD_MASK)
- |(liquidation_threshold << (LIQUIDATION_THRESHOLD_START_BIT_POSITION as u8))
+ | (liquidation_threshold
+ << (LIQUIDATION_THRESHOLD_START_BIT_POSITION as u8))
}
/// @notice Gets the liquidation threshold of the reserve
@@ -151,10 +152,10 @@ module aave_config::reserve {
) {
assert!(
liquidation_bonus <= MAX_VALID_LIQUIDATION_BONUS,
- error_config::get_einvalid_liq_bonus(),
+ error_config::get_einvalid_liq_bonus()
);
self.data = (self.data & LIQUIDATION_BONUS_MASK)
- |(liquidation_bonus << (LIQUIDATION_BONUS_START_BIT_POSITION as u8))
+ | (liquidation_bonus << (LIQUIDATION_BONUS_START_BIT_POSITION as u8))
}
/// @notice Gets the liquidation bonus of the reserve
@@ -173,7 +174,7 @@ module aave_config::reserve {
) {
assert!(decimals <= MAX_VALID_DECIMALS, error_config::get_einvalid_decimals());
self.data = (self.data & DECIMALS_MASK)
- |(decimals << (RESERVE_DECIMALS_START_BIT_POSITION as u8))
+ | (decimals << (RESERVE_DECIMALS_START_BIT_POSITION as u8))
}
/// @notice Gets the decimals of the underlying asset of the reserve
@@ -216,7 +217,7 @@ module aave_config::reserve {
frozen_state = 1;
};
self.data = (self.data & FROZEN_MASK)
- |(frozen_state << (IS_FROZEN_START_BIT_POSITION as u8))
+ | (frozen_state << (IS_FROZEN_START_BIT_POSITION as u8))
}
/// @notice Gets the frozen state of the reserve
@@ -237,7 +238,7 @@ module aave_config::reserve {
paused_state = 1;
};
self.data = (self.data & PAUSED_MASK)
- |(paused_state << (IS_PAUSED_START_BIT_POSITION as u8))
+ | (paused_state << (IS_PAUSED_START_BIT_POSITION as u8))
}
/// @notice Gets the paused state of the reserve
@@ -262,7 +263,7 @@ module aave_config::reserve {
borrowable_state = 1;
};
self.data = (self.data & BORROWABLE_IN_ISOLATION_MASK)
- |(borrowable_state << (BORROWABLE_IN_ISOLATION_START_BIT_POSITION as u8))
+ | (borrowable_state << (BORROWABLE_IN_ISOLATION_START_BIT_POSITION as u8))
}
/// @notice Gets the borrowable in isolation flag for the reserve.
@@ -328,11 +329,11 @@ module aave_config::reserve {
) {
assert!(
reserve_factor <= MAX_VALID_RESERVE_FACTOR,
- error_config::get_einvalid_reserve_factor(),
+ error_config::get_einvalid_reserve_factor()
);
self.data = (self.data & RESERVE_FACTOR_MASK)
- |(reserve_factor << (RESERVE_FACTOR_START_BIT_POSITION as u8))
+ | (reserve_factor << (RESERVE_FACTOR_START_BIT_POSITION as u8))
}
/// @notice Gets the reserve factor of the reserve
@@ -353,7 +354,7 @@ module aave_config::reserve {
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));
+ | (borrow_cap << (BORROW_CAP_START_BIT_POSITION as u8));
}
/// @notice Gets the borrow cap of the reserve
@@ -374,7 +375,7 @@ module aave_config::reserve {
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))
+ | (supply_cap << (SUPPLY_CAP_START_BIT_POSITION as u8))
}
/// @notice Gets the supply cap of the reserve
@@ -393,11 +394,11 @@ module aave_config::reserve {
) {
assert!(
debt_ceiling <= MAX_VALID_DEBT_CEILING,
- error_config::get_einvalid_debt_ceiling(),
+ error_config::get_einvalid_debt_ceiling()
);
self.data = (self.data & DEBT_CEILING_MASK)
- |(debt_ceiling << (DEBT_CEILING_START_BIT_POSITION as u8));
+ | (debt_ceiling << (DEBT_CEILING_START_BIT_POSITION as u8));
}
/// @notice Gets the debt ceiling for the asset if the asset is in isolation mode
@@ -416,10 +417,10 @@ module aave_config::reserve {
) {
assert!(
liquidation_protocol_fee <= MAX_VALID_LIQUIDATION_PROTOCOL_FEE,
- error_config::get_einvalid_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)
)
@@ -443,11 +444,11 @@ module aave_config::reserve {
) {
assert!(
unbacked_mint_cap <= MAX_VALID_UNBACKED_MINT_CAP,
- error_config::get_einvalid_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))
+ | (unbacked_mint_cap << (UNBACKED_MINT_CAP_START_BIT_POSITION as u8))
}
/// @dev Gets the unbacked mint cap of the reserve
@@ -466,10 +467,10 @@ module aave_config::reserve {
) {
assert!(
emode_category <= MAX_VALID_EMODE_CATEGORY,
- error_config::get_einvalid_emode_category(),
+ error_config::get_einvalid_emode_category()
);
self.data = (self.data & EMODE_CATEGORY_MASK)
- |(emode_category << (EMODE_CATEGORY_START_BIT_POSITION as u8))
+ | (emode_category << (EMODE_CATEGORY_START_BIT_POSITION as u8))
}
/// @dev Gets the eMode asset category
@@ -491,7 +492,7 @@ module aave_config::reserve {
flash_loan_enabled_state = 1;
};
self.data = (self.data & FLASHLOAN_ENABLED_MASK)
- |(flash_loan_enabled_state << (FLASHLOAN_ENABLED_START_BIT_POSITION as u8))
+ | (flash_loan_enabled_state << (FLASHLOAN_ENABLED_START_BIT_POSITION as u8))
}
/// @notice Gets the flashloanable flag for the reserve
@@ -509,8 +510,10 @@ module aave_config::reserve {
/// @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)
)
}
@@ -522,14 +525,15 @@ module aave_config::reserve {
/// @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) {
+ public fun get_params(self: &ReserveConfigurationMap):
+ (u256, u256, u256, u256, u256, u256) {
(
get_ltv(self),
get_liquidation_threshold(self),
get_liquidation_bonus(self),
get_decimals(self),
get_reserve_factor(self),
- get_emode_category(self),
+ get_emode_category(self)
)
}
diff --git a/aave-core/aave-config/sources/user_config.move b/aave-core/aave-config/sources/user_config.move
index f7285a2..c28c776 100644
--- a/aave-core/aave-config/sources/user_config.move
+++ b/aave-core/aave-config/sources/user_config.move
@@ -1,10 +1,10 @@
/// @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;
+module aave_config::user_config {
+ use aave_config::error_config;
use aave_config::helper;
- use aave_config::reserve as reserve_config;
+ use aave_config::reserve_config;
const BORROWING_MASK: u256 =
0x5555555555555555555555555555555555555555555555555555555555555555;
@@ -32,7 +32,7 @@ module aave_config::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,
+ data: u256
}
/// @notice Initializes the user configuration map
@@ -83,7 +83,7 @@ module aave_config::user {
) {
assert!(
reserve_index < (reserve_config::get_max_reserves_count() as u256),
- error_config::get_einvalid_reserve_index(),
+ error_config::get_einvalid_reserve_index()
);
let bit = 1 << ((reserve_index << 1) as u8);
if (borrowing) {
@@ -98,11 +98,11 @@ module aave_config::user {
/// @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(
- self: &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(),
+ error_config::get_einvalid_reserve_index()
);
let bit: u256 = 1 << (((reserve_index << 1) + 1) as u8);
if (using_as_collateral) {
@@ -121,7 +121,7 @@ module aave_config::user {
): bool {
assert!(
reserve_index < (reserve_config::get_max_reserves_count() as u256),
- error_config::get_einvalid_reserve_index(),
+ error_config::get_einvalid_reserve_index()
);
(self.data >> ((reserve_index << 1) as u8))
& 3 != 0
@@ -136,7 +136,7 @@ module aave_config::user {
): bool {
assert!(
reserve_index < (reserve_config::get_max_reserves_count() as u256),
- error_config::get_einvalid_reserve_index(),
+ error_config::get_einvalid_reserve_index()
);
(self.data >> ((reserve_index << 1) as u8))
& 1 != 0
@@ -151,7 +151,7 @@ module aave_config::user {
): bool {
assert!(
reserve_index < (reserve_config::get_max_reserves_count() as u256),
- error_config::get_einvalid_reserve_index(),
+ error_config::get_einvalid_reserve_index()
);
(self.data >> ((reserve_index << 1) as u8) + 1)
& 1 != 0
diff --git a/aave-core/aave-config/tests/error_tests.move b/aave-core/aave-config/tests/error_tests.move
index 121d89c..0a9cb8b 100644
--- a/aave-core/aave-config/tests/error_tests.move
+++ b/aave-core/aave-config/tests/error_tests.move
@@ -1,95 +1,95 @@
#[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,
+ use aave_config::error_config::{
+ get_eaccount_does_not_exist,
+ get_eacl_admin_cannot_be_zero,
+ get_eaddresses_provider_already_added,
+ get_eaddresses_provider_not_registered,
+ get_easset_not_borrowable_in_isolation,
+ get_easset_not_listed,
+ get_eborrow_cap_exceeded,
+ get_eborrowing_not_enabled,
+ get_ebridge_protocol_fee_invalid,
+ get_ecaller_must_be_pool,
get_ecaller_not_asset_listing_or_pool_admin,
+ get_ecaller_not_atoken,
get_ecaller_not_bridge,
- get_eaddresses_provider_not_registered,
- get_einvalid_addresses_provider_id,
- get_enot_contract,
+ get_ecaller_not_emergency_admin,
+ get_ecaller_not_pool_admin,
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_ecaller_not_pool_or_emergency_admin,
+ get_ecaller_not_risk_or_pool_admin,
+ get_ecollateral_balance_is_zero,
+ get_ecollateral_cannot_be_liquidated,
+ get_ecollateral_cannot_cover_new_borrow,
+ get_ecollateral_same_as_borrowing_currency,
+ get_edebt_ceiling_exceeded,
+ get_edebt_ceiling_not_zero,
get_eemode_category_reserved,
- get_einvalid_emode_category_assignment,
- get_ereserve_liquidity_not_zero,
+ get_eflashloan_disabled,
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_einconsistent_flashloan_params,
+ get_einconsistent_params_length,
+ get_einterest_rate_rebalance_conditions_not_met,
+ get_einvalid_addresses_provider,
+ get_einvalid_addresses_provider_id,
+ get_einvalid_amount,
get_einvalid_borrow_cap,
- get_einvalid_supply_cap,
+ get_einvalid_burn_amount,
+ get_einvalid_debt_ceiling,
+ get_einvalid_decimals,
+ get_einvalid_emode_category,
+ get_einvalid_emode_category_assignment,
+ get_einvalid_emode_category_params,
+ get_einvalid_expiration,
+ get_einvalid_flashloan_executor_return,
+ get_einvalid_interest_rate_mode_selected,
+ get_einvalid_liq_bonus,
+ get_einvalid_liq_threshold,
get_einvalid_liquidation_protocol_fee,
+ get_einvalid_ltv,
+ get_einvalid_mint_amount,
+ get_einvalid_optimal_usage_ratio,
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_reserve_params,
get_einvalid_signature,
+ get_einvalid_supply_cap,
+ get_einvalid_unbacked_mint_cap,
+ get_eltv_validation_failed,
+ get_eno_debt_of_selected_type,
+ get_eno_explicit_amount_to_repay_on_behalf,
+ get_eno_more_reserves_allowed,
+ get_eno_outstanding_variable_debt,
+ get_enot_contract,
+ get_enot_enough_available_user_balance,
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_eprice_oracle_check_failed,
+ get_ereserve_already_added,
+ get_ereserve_already_initialized,
get_ereserve_debt_not_zero,
- get_eflashloan_disabled,
- get_euser_not_listed,
+ get_ereserve_frozen,
+ get_ereserve_inactive,
+ get_ereserve_liquidity_not_zero,
+ get_ereserve_paused,
+ get_ereserves_storage_count_mismatch,
get_esigner_and_on_behalf_of_no_same,
- get_eaccount_does_not_exist,
- get_flashloan_payer_not_receiver,
+ get_esiloed_borrowing_violation,
+ get_especified_currency_not_borrowed_by_user,
+ get_esupply_cap_exceeded,
+ get_eunbacked_mint_cap_exceeded,
+ get_eunderlying_balance_zero,
+ get_eunderlying_cannot_be_rescued,
+ get_eunderlying_claimable_rights_not_zero,
+ get_euser_in_isolation_mode_or_ltv_zero,
+ get_euser_not_listed,
+ get_evariable_debt_supply_not_zero,
+ get_ezero_address_not_valid,
+ get_flashloan_payer_not_receiver
};
const TEST_SUCCESS: u64 = 1;
@@ -201,8 +201,6 @@ module aave_config::error_tests {
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
@@ -264,18 +262,75 @@ module aave_config::error_tests {
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;
+ /// Aptos has introduced a new business logic error code range from 1001 to 2000.
+
+ /// aave_acl module error code range from 1001 to 1100.
+ /// Account is not the acl's owner.
+ const ENOT_ACL_OWNER: u64 = 1001;
+ /// Account is missing role.
+ const EROLE_MISSMATCH: u64 = 1002;
+ /// can only renounce roles for self
+ const EROLE_CAN_ONLY_RENOUNCE_SELF: u64 = 1003;
+
+ /// aave_math module error code range from 1101 to 1200.
+ /// Calculation results in overflow
+ const EOVERFLOW: u64 = 1101;
+ /// Cannot divide by zero
+ const EDIVISION_BY_ZERO: u64 = 1102;
+
+ /// aave_oracle module error code range from 1201 to 1300.
+ /// Account is not the oracle's owner.
+ const ENOT_ORACLE_OWNER: u64 = 1201;
+ const ERESOURCE_NOT_FOUND: u64 = 1202;
+
+ /// aave_oracle
+ /// Not an asset listing or a pool admin error
+ const ENOT_ASSET_LISTING_OR_POOL_ADMIN: u64 = 1203;
+ /// base currency not set
+ const EBASE_CURRENCY_NOT_SET: u64 = 1204;
+ /// identical base currency already added
+ const EIDENTICAL_BASE_CURRENCY_ALREADY_ADDED: u64 = 1205;
+ /// missing price feed identifier
+ const EMISSING_PRICE_FEED_IDENTIFIER: u64 = 1206;
+ /// missing price vaa
+ const EMISSING_PRICE_VAA: u64 = 1207;
+ /// not existing price feed identifier
+ const EPRICE_FEED_IDENTIFIER_NOT_EXIST: u64 = 1208;
+
+ /// aave_rate module error code range from 1301 to 1400.
+ /// Account is not the rate's owner.
+ const ENOT_RATE_OWNER: u64 = 1301;
+
+ /// aave_pool module error code range from 1401 to 1500.
+ /// Account is not the pool's owner.
+ const ENOT_POOL_OWNER: u64 = 1401;
+ /// User is not listed
+ const EUSER_NOT_LISTED: u64 = 1402;
/// Mismatch of reserves count in storage
- const ERESERVES_STORAGE_COUNT_MISMATCH: u64 = 93;
+ const ERESERVES_STORAGE_COUNT_MISMATCH: u64 = 1403;
/// 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 = 1404;
/// Account does not exist
- const EACCOUNT_DOES_NOT_EXIST: u64 = 95;
-
+ const EACCOUNT_DOES_NOT_EXIST: u64 = 1405;
/// Flashloan payer is different from the flashloan receiver
- const EFLASHLOAN_PAYER_NOT_RECEIVER: u64 = 95;
+ const EFLASHLOAN_PAYER_NOT_RECEIVER: u64 = 1406;
+ /// Price oracle validation failed
+ const EPRICE_ORACLE_CHECK_FAILED: u64 = 1407;
+ /// reserve list not initialized
+ const ERESERVE_LIST_NOT_INITIALIZED: u64 = 1408;
+
+ /// aave_tokens
+ /// Token already exists
+ const ETOKEN_ALREADY_EXISTS: u64 = 1409;
+ /// Token not exist
+ const ETOKEN_NOT_EXIST: u64 = 1410;
+ /// Resource not exist
+ const ERESOURCE_NOT_EXIST: u64 = 1411;
+ /// Token name already exist
+ const ETOKEN_NAME_ALREADY_EXIST: u64 = 1412;
+ /// Token symbol already exist
+ const ETOKEN_SYMBOL_ALREADY_EXIST: u64 = 1413;
#[test]
fun test_get_ecaller_not_pool_admin() {
@@ -285,15 +340,17 @@ module aave_config::error_tests {
#[test]
fun test_get_ecaller_not_emergency_admin() {
assert!(
- get_ecaller_not_emergency_admin() == ECALLER_NOT_EMERGENCY_ADMIN, TEST_SUCCESS
+ 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,
+ get_ecaller_not_pool_or_emergency_admin()
+ == ECALLER_NOT_POOL_OR_EMERGENCY_ADMIN,
+ TEST_SUCCESS
);
}
@@ -301,7 +358,7 @@ module aave_config::error_tests {
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_SUCCESS
);
}
@@ -310,7 +367,7 @@ module aave_config::error_tests {
assert!(
get_ecaller_not_asset_listing_or_pool_admin()
== ECALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -322,8 +379,9 @@ module aave_config::error_tests {
#[test]
fun test_get_eaddresses_provider_not_registered() {
assert!(
- get_eaddresses_provider_not_registered() == EADDRESSES_PROVIDER_NOT_REGISTERED,
- TEST_SUCCESS,
+ get_eaddresses_provider_not_registered()
+ == EADDRESSES_PROVIDER_NOT_REGISTERED,
+ TEST_SUCCESS
);
}
@@ -331,7 +389,7 @@ module aave_config::error_tests {
fun test_get_einvalid_addresses_provider_id() {
assert!(
get_einvalid_addresses_provider_id() == EINVALID_ADDRESSES_PROVIDER_ID,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -344,7 +402,7 @@ module aave_config::error_tests {
fun test_get_ecaller_not_pool_configurator() {
assert!(
get_ecaller_not_pool_configurator() == ECALLER_NOT_POOL_CONFIGURATOR,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -356,15 +414,17 @@ module aave_config::error_tests {
#[test]
fun test_get_einvalid_addresses_provider() {
assert!(
- get_einvalid_addresses_provider() == EINVALID_ADDRESSES_PROVIDER, TEST_SUCCESS
+ 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,
+ get_einvalid_flashloan_executor_return()
+ == EINVALID_FLASHLOAN_EXECUTOR_RETURN,
+ TEST_SUCCESS
);
}
@@ -377,7 +437,7 @@ module aave_config::error_tests {
fun test_get_ereserves_storage_count_mismatch() {
assert!(
get_ereserves_storage_count_mismatch() == ERESERVES_STORAGE_COUNT_MISMATCH,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -396,22 +456,25 @@ module aave_config::error_tests {
#[test]
fun test_get_einvalid_emode_category_assignment() {
assert!(
- get_einvalid_emode_category_assignment() == EINVALID_EMODE_CATEGORY_ASSIGNMENT,
- TEST_SUCCESS,
+ 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
+ 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
+ get_eflashloan_premium_invalid() == EFLASHLOAN_PREMIUM_INVALID,
+ TEST_SUCCESS
);
}
@@ -424,7 +487,7 @@ module aave_config::error_tests {
fun test_get_einvalid_emode_category_params() {
assert!(
get_einvalid_emode_category_params() == EINVALID_EMODE_CATEGORY_PARAMS,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -432,7 +495,7 @@ module aave_config::error_tests {
fun test_get_ebridge_protocol_fee_invalid() {
assert!(
get_ebridge_protocol_fee_invalid() == EBRIDGE_PROTOCOL_FEE_INVALID,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -479,8 +542,9 @@ module aave_config::error_tests {
#[test]
fun test_get_enot_enough_available_user_balance() {
assert!(
- get_enot_enough_available_user_balance() == ENOT_ENOUGH_AVAILABLE_USER_BALANCE,
- TEST_SUCCESS,
+ get_enot_enough_available_user_balance()
+ == ENOT_ENOUGH_AVAILABLE_USER_BALANCE,
+ TEST_SUCCESS
);
}
@@ -489,14 +553,15 @@ module aave_config::error_tests {
assert!(
get_einvalid_interest_rate_mode_selected()
== EINVALID_INTEREST_RATE_MODE_SELECTED,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
#[test]
fun test_get_ecollateral_balance_is_zero() {
assert!(
- get_ecollateral_balance_is_zero() == ECOLLATERAL_BALANCE_IS_ZERO, TEST_SUCCESS
+ get_ecollateral_balance_is_zero() == ECOLLATERAL_BALANCE_IS_ZERO,
+ TEST_SUCCESS
);
}
@@ -505,15 +570,16 @@ module aave_config::error_tests {
assert!(
get_ehealth_factor_lower_than_liquidation_threshold()
== EHEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD,
- TEST_SUCCESS,
+ 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,
+ get_ecollateral_cannot_cover_new_borrow()
+ == ECOLLATERAL_CANNOT_COVER_NEW_BORROW,
+ TEST_SUCCESS
);
}
@@ -522,7 +588,7 @@ module aave_config::error_tests {
assert!(
get_ecollateral_same_as_borrowing_currency()
== ECOLLATERAL_SAME_AS_BORROWING_CURRENCY,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -538,7 +604,7 @@ module aave_config::error_tests {
assert!(
get_eno_explicit_amount_to_repay_on_behalf()
== ENO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -546,7 +612,7 @@ module aave_config::error_tests {
fun test_get_eno_outstanding_variable_debt() {
assert!(
get_eno_outstanding_variable_debt() == ENO_OUTSTANDING_VARIABLE_DEBT,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -560,15 +626,16 @@ module aave_config::error_tests {
assert!(
get_einterest_rate_rebalance_conditions_not_met()
== EINTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET,
- TEST_SUCCESS,
+ 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,
+ get_ehealth_factor_not_below_threshold()
+ == EHEALTH_FACTOR_NOT_BELOW_THRESHOLD,
+ TEST_SUCCESS
);
}
@@ -576,7 +643,7 @@ module aave_config::error_tests {
fun test_get_ecollateral_cannot_be_liquidated() {
assert!(
get_ecollateral_cannot_be_liquidated() == ECOLLATERAL_CANNOT_BE_LIQUIDATED,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -585,7 +652,7 @@ module aave_config::error_tests {
assert!(
get_especified_currency_not_borrowed_by_user()
== ESPECIFIED_CURRENCY_NOT_BORROWED_BY_USER,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -593,7 +660,7 @@ module aave_config::error_tests {
fun test_get_einconsistent_flashloan_params() {
assert!(
get_einconsistent_flashloan_params() == EINCONSISTENT_FLASHLOAN_PARAMS,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -610,7 +677,8 @@ module aave_config::error_tests {
#[test]
fun test_get_eunbacked_mint_cap_exceededd() {
assert!(
- get_eunbacked_mint_cap_exceeded() == EUNBACKED_MINT_CAP_EXCEEDED, TEST_SUCCESS
+ get_eunbacked_mint_cap_exceeded() == EUNBACKED_MINT_CAP_EXCEEDED,
+ TEST_SUCCESS
);
}
@@ -624,7 +692,7 @@ module aave_config::error_tests {
assert!(
get_eunderlying_claimable_rights_not_zero()
== EUNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -632,7 +700,7 @@ module aave_config::error_tests {
fun test_get_evariable_debt_supply_not_zero() {
assert!(
get_evariable_debt_supply_not_zero() == EVARIABLE_DEBT_SUPPLY_NOT_ZERO,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -645,23 +713,16 @@ module aave_config::error_tests {
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_SUCCESS
);
}
#[test]
fun test_get_easset_not_borrowable_in_isolation() {
assert!(
- get_easset_not_borrowable_in_isolation() == EASSET_NOT_BORROWABLE_IN_ISOLATION,
- TEST_SUCCESS,
+ get_easset_not_borrowable_in_isolation()
+ == EASSET_NOT_BORROWABLE_IN_ISOLATION,
+ TEST_SUCCESS
);
}
@@ -669,15 +730,16 @@ module aave_config::error_tests {
fun test_get_ereserve_already_initialized() {
assert!(
get_ereserve_already_initialized() == ERESERVE_ALREADY_INITIALIZED,
- TEST_SUCCESS,
+ 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,
+ get_euser_in_isolation_mode_or_ltv_zero()
+ == EUSER_IN_ISOLATION_MODE_OR_LTV_ZERO,
+ TEST_SUCCESS
);
}
@@ -714,8 +776,9 @@ module aave_config::error_tests {
#[test]
fun test_get_einvalid_liquidation_protocol_fee() {
assert!(
- get_einvalid_liquidation_protocol_fee() == EINVALID_LIQUIDATION_PROTOCOL_FEE,
- TEST_SUCCESS,
+ get_einvalid_liquidation_protocol_fee()
+ == EINVALID_LIQUIDATION_PROTOCOL_FEE,
+ TEST_SUCCESS
);
}
@@ -727,7 +790,8 @@ module aave_config::error_tests {
#[test]
fun test_get_einvalid_unbacked_mint_cap() {
assert!(
- get_einvalid_unbacked_mint_cap() == EINVALID_UNBACKED_MINT_CAP, TEST_SUCCESS
+ get_einvalid_unbacked_mint_cap() == EINVALID_UNBACKED_MINT_CAP,
+ TEST_SUCCESS
);
}
@@ -751,7 +815,8 @@ module aave_config::error_tests {
#[test]
fun test_get_einconsistent_params_length() {
assert!(
- get_einconsistent_params_length() == EINCONSISTENT_PARAMS_LENGTH, TEST_SUCCESS
+ get_einconsistent_params_length() == EINCONSISTENT_PARAMS_LENGTH,
+ TEST_SUCCESS
);
}
@@ -789,7 +854,7 @@ module aave_config::error_tests {
fun test_get_einvalid_optimal_usage_ratio() {
assert!(
get_einvalid_optimal_usage_ratio() == EINVALID_OPTIMAL_USAGE_RATIO,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -797,15 +862,16 @@ module aave_config::error_tests {
fun test_get_eunderlying_cannot_be_rescued() {
assert!(
get_eunderlying_cannot_be_rescued() == EUNDERLYING_CANNOT_BE_RESCUED,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
#[test]
fun test_get_eaddresses_provider_already_added() {
assert!(
- get_eaddresses_provider_already_added() == EADDRESSES_PROVIDER_ALREADY_ADDED,
- TEST_SUCCESS,
+ get_eaddresses_provider_already_added()
+ == EADDRESSES_PROVIDER_ALREADY_ADDED,
+ TEST_SUCCESS
);
}
@@ -813,14 +879,15 @@ module aave_config::error_tests {
fun test_get_epool_addresses_do_not_match() {
assert!(
get_epool_addresses_do_not_match() == EPOOL_ADDRESSES_DO_NOT_MATCH,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
#[test]
fun test_get_esiloed_borrowing_violation() {
assert!(
- get_esiloed_borrowing_violation() == ESILOED_BORROWING_VIOLATION, TEST_SUCCESS
+ get_esiloed_borrowing_violation() == ESILOED_BORROWING_VIOLATION,
+ TEST_SUCCESS
);
}
@@ -843,7 +910,7 @@ module aave_config::error_tests {
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_SUCCESS
);
}
@@ -856,7 +923,7 @@ module aave_config::error_tests {
fun test_get_flashloan_payer_not_receiver() {
assert!(
get_flashloan_payer_not_receiver() == EFLASHLOAN_PAYER_NOT_RECEIVER,
- TEST_SUCCESS,
+ TEST_SUCCESS
);
}
@@ -864,4 +931,12 @@ module aave_config::error_tests {
fun test_get_einvalid_liq_bonus() {
assert!(get_einvalid_liq_bonus() == EINVALID_LIQ_BONUS, TEST_SUCCESS);
}
+
+ #[test]
+ fun test_get_price_oracle_check_failed() {
+ assert!(
+ get_eprice_oracle_check_failed() == EPRICE_ORACLE_CHECK_FAILED,
+ 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 49cc112..aedaa75 100644
--- a/aave-core/aave-config/tests/reserve_config_tests.move
+++ b/aave-core/aave-config/tests/reserve_config_tests.move
@@ -1,44 +1,45 @@
#[test_only]
module aave_config::reserve_tests {
- use aave_config::reserve::{
- init,
- ReserveConfigurationMap,
+ use aave_config::reserve_config::{
get_borrow_cap,
- get_ltv,
- get_liquidation_threshold,
- get_liquidation_bonus,
+ get_borrowing_enabled,
+ get_caps,
get_decimals,
+ get_emode_category,
+ get_flags,
+ get_flash_loan_enabled,
get_frozen,
- get_borrowing_enabled,
+ get_liquidation_bonus,
+ get_liquidation_protocol_fee,
+ get_liquidation_threshold,
+ get_ltv,
+ get_max_valid_decimals,
+ get_max_valid_emode_category,
+ get_max_valid_liquidation_protocol_fee,
+ get_max_valid_liquidation_threshold,
+ get_max_valid_ltv,
+ get_max_valid_reserve_factor,
+ get_params,
get_reserve_factor,
get_supply_cap,
- get_liquidation_protocol_fee,
get_unbacked_mint_cap,
- get_emode_category,
- get_flash_loan_enabled,
- get_flags,
- get_params,
- get_caps,
- set_ltv,
- set_liquidation_threshold,
- set_liquidation_bonus,
+ init,
+ ReserveConfigurationMap,
+ set_borrow_cap,
+ set_borrowing_enabled,
set_decimals,
+ set_emode_category,
+ set_flash_loan_enabled,
set_frozen,
- set_borrowing_enabled,
+ set_liquidation_bonus,
+ set_liquidation_protocol_fee,
+ set_liquidation_threshold,
+ set_ltv,
set_reserve_factor,
- set_borrow_cap,
set_supply_cap,
- set_liquidation_protocol_fee,
- set_unbacked_mint_cap,
- set_emode_category,
- set_flash_loan_enabled,
- get_max_valid_reserve_factor,
- get_max_valid_liquidation_threshold,
- get_max_valid_decimals,
- get_max_valid_emode_category,
- get_max_valid_liquidation_protocol_fee,
- get_max_valid_ltv
+ set_unbacked_mint_cap
};
+
//
// Test example reference link: https://github.com/aave/aave-v3-core/blob/master/test-suites/reserve-configuration.spec.ts
// test functions
@@ -251,12 +252,14 @@ module aave_config::reserve_tests {
check_params(&reserve_config, ZERO, ZERO);
set_reserve_factor(&mut reserve_config, get_max_valid_reserve_factor());
- check_params(&reserve_config, ENUM_RESERVE_FACTOR, get_max_valid_reserve_factor());
+ check_params(
+ &reserve_config, ENUM_RESERVE_FACTOR, get_max_valid_reserve_factor()
+ );
}
#[test]
// set_reserve_factor() with reserve_factor > MAX_VALID_RESERVE_FACTOR
- #[expected_failure(abort_code = 67, location = aave_config::reserve)]
+ #[expected_failure(abort_code = 67, location = aave_config::reserve_config)]
fun test_set_reserve_factor_expected_failure() {
let reserve_config = init();
check_params(&reserve_config, ZERO, ZERO);
@@ -351,7 +354,7 @@ module aave_config::reserve_tests {
#[test]
// set_ltv() with ltv > MAX_VALID_LTV (revert expected)
- #[expected_failure(abort_code = 63, location = aave_config::reserve)]
+ #[expected_failure(abort_code = 63, location = aave_config::reserve_config)]
fun test_set_ltv_expected_failure() {
let reserve_config = init();
assert!(get_ltv(&reserve_config) == ZERO, SUCCESS);
@@ -373,12 +376,12 @@ module aave_config::reserve_tests {
check_params(
&reserve_config,
ENUM_LIQUIDATION_THRESHOLD,
- get_max_valid_liquidation_threshold(),
+ get_max_valid_liquidation_threshold()
);
assert!(
get_liquidation_threshold(&reserve_config)
== get_max_valid_liquidation_threshold(),
- SUCCESS,
+ SUCCESS
);
set_liquidation_threshold(&mut reserve_config, ZERO);
@@ -388,7 +391,7 @@ module aave_config::reserve_tests {
#[test]
// set_liquidation_threshold() with threshold > MAX_VALID_LIQUIDATION_THRESHOLD (revert expected)
- #[expected_failure(abort_code = 64, location = aave_config::reserve)]
+ #[expected_failure(abort_code = 64, location = aave_config::reserve_config)]
fun test_set_liquidation_threshold_expected_failure() {
let reserve_config = init();
assert!(get_liquidation_threshold(&reserve_config) == ZERO, SUCCESS);
@@ -417,7 +420,7 @@ module aave_config::reserve_tests {
#[test]
// set_decimals() with decimals > MAX_VALID_DECIMALS (revert expected)
- #[expected_failure(abort_code = 66, location = aave_config::reserve)]
+ #[expected_failure(abort_code = 66, location = aave_config::reserve_config)]
fun test_set_decimals_expected_failure() {
let reserve_config = init();
assert!(get_decimals(&reserve_config) == ZERO, SUCCESS);
@@ -434,7 +437,8 @@ module aave_config::reserve_tests {
set_emode_category(&mut reserve_config, get_max_valid_emode_category());
assert!(
- get_emode_category(&reserve_config) == get_max_valid_emode_category(), SUCCESS
+ get_emode_category(&reserve_config) == get_max_valid_emode_category(),
+ SUCCESS
);
set_emode_category(&mut reserve_config, ZERO);
@@ -443,7 +447,7 @@ module aave_config::reserve_tests {
#[test]
// set_emode_category() with category_id > MAX_VALID_EMODE_CATEGORY (revert expected)
- #[expected_failure(abort_code = 71, location = aave_config::reserve)]
+ #[expected_failure(abort_code = 71, location = aave_config::reserve_config)]
fun test_set_emode_category_expected_failure() {
let reserve_config = init();
assert!(get_emode_category(&reserve_config) == ZERO, SUCCESS);
@@ -464,13 +468,13 @@ module aave_config::reserve_tests {
assert!(
get_liquidation_protocol_fee(&reserve_config)
== get_max_valid_liquidation_protocol_fee(),
- SUCCESS,
+ SUCCESS
);
}
#[test]
// setLiquidationProtocolFee() with liquidationProtocolFee > MAX_VALID_LIQUIDATION_PROTOCOL_FEE (revert expected)
- #[expected_failure(abort_code = 70, location = aave_config::reserve)]
+ #[expected_failure(abort_code = 70, location = aave_config::reserve_config)]
fun test_set_liquidation_protocol_fee_expected_failure() {
let reserve_config = init();
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 c44ee68..ef43585 100644
--- a/aave-core/aave-config/tests/user_config_tests.move
+++ b/aave-core/aave-config/tests/user_config_tests.move
@@ -1,7 +1,8 @@
#[test_only]
module aave_config::user_tests {
use aave_config::helper::Self;
- use aave_config::user::{
+ use aave_config::user_config::{
+ get_first_asset_id_by_mask,
get_health_factor_liquidation_threshold,
get_health_factor_liquidation_threshold_for_testing,
get_isolated_collateral_supplier_role,
@@ -19,8 +20,7 @@ module aave_config::user_tests {
is_using_as_collateral_or_borrowing,
set_borrowing,
set_using_as_collateral,
- test_init_module,
- get_first_asset_id_by_mask,
+ test_init_module
};
const TEST_SUCCESS: u64 = 1;
@@ -32,17 +32,17 @@ module aave_config::user_tests {
assert!(
get_minimum_health_factor_liquidation_threshold()
== get_minimum_health_factor_liquidation_threshold_for_testing(),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
assert!(
get_health_factor_liquidation_threshold()
== get_health_factor_liquidation_threshold_for_testing(),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
assert!(
get_isolated_collateral_supplier_role()
== get_isolated_collateral_supplier_role_for_testing(),
- TEST_SUCCESS,
+ TEST_SUCCESS
);
// test default values
let user_config_map = get_user_config_map();
@@ -58,7 +58,7 @@ module aave_config::user_tests {
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,
+ TEST_SUCCESS
);
// test collateral
set_using_as_collateral(&mut user_config_map, reserve_index, true);
@@ -67,7 +67,7 @@ module aave_config::user_tests {
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,
+ TEST_SUCCESS
);
}
diff --git a/aave-core/aave-mock-oracle/Move.toml b/aave-core/aave-data/Move.toml
similarity index 74%
rename from aave-core/aave-mock-oracle/Move.toml
rename to aave-core/aave-data/Move.toml
index 09a69db..871d7e1 100644
--- a/aave-core/aave-mock-oracle/Move.toml
+++ b/aave-core/aave-data/Move.toml
@@ -1,14 +1,17 @@
[package]
-name = "AaveMockOracle"
+name = "AaveData"
version = "1.0.0"
upgrade_policy = "compatible"
authors = []
[addresses]
-aave_mock_oracle = "_"
+aave_data = "_"
+
+[dev-addresses]
[dependencies]
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" }
+AavePool = { local = "../" }
+[dev-dependencies]
diff --git a/aave-core/aave-data/sources/v1.move b/aave-core/aave-data/sources/v1.move
new file mode 100644
index 0000000..2f93952
--- /dev/null
+++ b/aave-core/aave-data/sources/v1.move
@@ -0,0 +1,125 @@
+module aave_data::v1 {
+ // std
+ use std::signer;
+ use std::string;
+ use std::string::String;
+ use aptos_std::string_utils;
+ use aptos_std::smart_table;
+ // locals
+ use aave_config::error_config;
+
+ // prefixes
+ const ATOKEN_NAME_PREFIX: vector = b"AAVE_A";
+ const ATOKEN_SYMBOL_PREFIX: vector = b"aaveA";
+ const VARTOKEN_NAME_PREFIX: vector = b"AAVE_VAR";
+ const VARTOKEN_SYMBOL_PREFIX: vector = b"aaveVar";
+
+ struct Data has key {
+ price_feeds_testnet: smart_table::SmartTable>,
+ price_feeds_mainnet: smart_table::SmartTable>,
+ underlying_assets_testnet: smart_table::SmartTable,
+ underlying_assets_mainnet: smart_table::SmartTable,
+ reserves_config_testnet: smart_table::SmartTable,
+ reserves_config_mainnet: smart_table::SmartTable,
+ interest_rate_strategy_testnet: smart_table::SmartTable,
+ interest_rate_strategy_mainnet: smart_table::SmartTable,
+ emodes_testnet: smart_table::SmartTable,
+ emodes_mainnet: smart_table::SmartTable
+ }
+
+ fun init_module(account: &signer) {
+ assert!(
+ signer::address_of(account) == @aave_data,
+ error_config::get_enot_pool_owner()
+ );
+ move_to(
+ account,
+ Data {
+ price_feeds_testnet: aave_data::v1_values::build_price_feeds_testnet(),
+ price_feeds_mainnet: aave_data::v1_values::build_price_feeds_mainnet(),
+ underlying_assets_testnet: aave_data::v1_values::build_underlying_assets_testnet(),
+ underlying_assets_mainnet: aave_data::v1_values::build_underlying_assets_mainnet(),
+ reserves_config_testnet: aave_data::v1_values::build_reserve_config_testnet(),
+ reserves_config_mainnet: aave_data::v1_values::build_reserve_config_mainnet(),
+ interest_rate_strategy_testnet: aave_data::v1_values::build_interest_rate_strategy_testnet(),
+ interest_rate_strategy_mainnet: aave_data::v1_values::build_interest_rate_strategy_mainnet(),
+ emodes_testnet: aave_data::v1_values::build_emodes_testnet(),
+ emodes_mainnet: aave_data::v1_values::build_emodes_mainnet()
+ }
+ );
+ }
+
+ public inline fun get_atoken_name(underlying_asset_symbol: String): String {
+ string_utils::format2(&b"{}_{}", ATOKEN_NAME_PREFIX, underlying_asset_symbol)
+ }
+
+ public inline fun get_atoken_symbol(underlying_asset_symbol: String): String {
+ string_utils::format2(&b"{}{}", ATOKEN_SYMBOL_PREFIX, underlying_asset_symbol)
+ }
+
+ public inline fun get_vartoken_name(underlying_asset_symbol: String): String {
+ string_utils::format2(&b"{}_{}", VARTOKEN_NAME_PREFIX, underlying_asset_symbol)
+ }
+
+ public inline fun get_vartoken_symbol(underlying_asset_symbol: String): String {
+ string_utils::format2(&b"{}{}", VARTOKEN_SYMBOL_PREFIX, underlying_asset_symbol)
+ }
+
+ public inline fun get_asset_symbols_testnet(): &vector acquires Data {
+ &smart_table::keys(&borrow_global(@aave_pool).price_feeds_testnet)
+ }
+
+ public inline fun get_asset_symbols_mainnet(): &vector acquires Data {
+ &smart_table::keys(&borrow_global(@aave_pool).price_feeds_mainnet)
+ }
+
+ public inline fun get_price_feeds_tesnet():
+ &smart_table::SmartTable> acquires Data {
+ &borrow_global(@aave_pool).price_feeds_testnet
+ }
+
+ public inline fun get_price_feeds_mainnet():
+ &smart_table::SmartTable> acquires Data {
+ &borrow_global(@aave_pool).price_feeds_mainnet
+ }
+
+ public inline fun get_underlying_assets_testnet():
+ &smart_table::SmartTable acquires Data {
+ &borrow_global(@aave_pool).underlying_assets_testnet
+ }
+
+ public inline fun get_underlying_assets_mainnet():
+ &smart_table::SmartTable acquires Data {
+ &borrow_global(@aave_pool).underlying_assets_mainnet
+ }
+
+ public inline fun get_reserves_config_testnet():
+ &smart_table::SmartTable acquires Data {
+ &borrow_global(@aave_pool).reserves_config_testnet
+ }
+
+ public inline fun get_reserves_config_mainnet():
+ &smart_table::SmartTable acquires Data {
+ &borrow_global(@aave_pool).reserves_config_mainnet
+ }
+
+ public inline fun get_interest_rate_strategy_testnet():
+ &smart_table::SmartTable acquires Data {
+ &borrow_global(@aave_pool).interest_rate_strategy_testnet
+ }
+
+ public inline fun get_interest_rate_strategy_mainnet():
+ &smart_table::SmartTable acquires Data {
+ &borrow_global(@aave_pool).interest_rate_strategy_mainnet
+ }
+
+ public inline fun get_emodes_mainnet():
+ &smart_table::SmartTable acquires Data {
+ &borrow_global(@aave_pool).emodes_mainnet
+ }
+
+ public inline fun get_emodes_testnet():
+ &smart_table::SmartTable acquires Data {
+ &borrow_global(@aave_pool).emodes_testnet
+ }
+}
diff --git a/aave-core/aave-data/sources/v1_values.move b/aave-core/aave-data/sources/v1_values.move
new file mode 100644
index 0000000..6984081
--- /dev/null
+++ b/aave-core/aave-data/sources/v1_values.move
@@ -0,0 +1,608 @@
+module aave_data::v1_values {
+ // std
+ use std::option;
+ use std::option::Option;
+ use std::string;
+ use std::string::{String, utf8};
+ use aptos_std::smart_table;
+ use aptos_std::smart_table::SmartTable;
+ use aptos_framework::aptos_coin;
+ // locals
+ use aave_pool::coin_migrator;
+
+ // assets
+ const USDT_ASSET: vector = b"USDT";
+ const USDC_ASSET: vector = b"USDC";
+ const AMAPT_ASSET: vector = b"amAPT";
+ const THAPT_ASSET: vector = b"thAPT";
+ const APT_ASSET: vector = b"APT";
+
+ struct ReserveConfig has store, copy, drop {
+ base_ltv_as_collateral: u256,
+ liquidation_threshold: u256,
+ liquidation_bonus: u256,
+ liquidation_protocol_fee: u256,
+ borrowing_enabled: bool,
+ flashLoan_enabled: bool,
+ reserve_factor: u256,
+ supply_cap: u256,
+ borrow_cap: u256,
+ debt_ceiling: u256,
+ borrowable_isolation: bool,
+ siloed_borrowing: bool,
+ emode_category: Option
+ }
+
+ struct InterestRateStrategy has store, copy, drop {
+ optimal_usage_ratio: u256,
+ base_variable_borrow_rate: u256,
+ variable_rate_slope1: u256,
+ variable_rate_slope2: u256
+ }
+
+ struct EmodeConfig has store, copy, drop {
+ category_id: u256,
+ ltv: u256,
+ liquidation_threshold: u256,
+ liquidation_bonus: u256,
+ label: String
+ }
+
+ public fun get_emode_category_id(emode_config: &EmodeConfig): u256 {
+ emode_config.category_id
+ }
+
+ public fun get_emode_ltv(emode_config: &EmodeConfig): u256 {
+ emode_config.ltv
+ }
+
+ public fun get_emode_liquidation_threshold(emode_config: &EmodeConfig): u256 {
+ emode_config.liquidation_threshold
+ }
+
+ public fun get_emode_liquidation_bonus(emode_config: &EmodeConfig): u256 {
+ emode_config.liquidation_bonus
+ }
+
+ public fun get_emode_liquidation_label(emode_config: &EmodeConfig): String {
+ emode_config.label
+ }
+
+ public fun get_optimal_usage_ratio(ir_strategy: &InterestRateStrategy): u256 {
+ ir_strategy.optimal_usage_ratio
+ }
+
+ public fun get_base_variable_borrow_rate(
+ ir_strategy: &InterestRateStrategy
+ ): u256 {
+ ir_strategy.base_variable_borrow_rate
+ }
+
+ public fun get_variable_rate_slope1(
+ ir_strategy: &InterestRateStrategy
+ ): u256 {
+ ir_strategy.variable_rate_slope1
+ }
+
+ public fun get_variable_rate_slope2(
+ ir_strategy: &InterestRateStrategy
+ ): u256 {
+ ir_strategy.variable_rate_slope2
+ }
+
+ public fun get_base_ltv_as_collateral(reserve_config: &ReserveConfig): u256 {
+ reserve_config.base_ltv_as_collateral
+ }
+
+ public fun get_liquidation_threshold(reserve_config: &ReserveConfig): u256 {
+ reserve_config.liquidation_threshold
+ }
+
+ public fun get_liquidation_bonus(reserve_config: &ReserveConfig): u256 {
+ reserve_config.liquidation_bonus
+ }
+
+ public fun get_liquidation_protocol_fee(
+ reserve_config: &ReserveConfig
+ ): u256 {
+ reserve_config.liquidation_protocol_fee
+ }
+
+ public fun get_borrowing_enabled(reserve_config: &ReserveConfig): bool {
+ reserve_config.borrowing_enabled
+ }
+
+ public fun get_flashLoan_enabled(reserve_config: &ReserveConfig): bool {
+ reserve_config.flashLoan_enabled
+ }
+
+ public fun get_reserve_factor(reserve_config: &ReserveConfig): u256 {
+ reserve_config.reserve_factor
+ }
+
+ public fun get_supply_cap(reserve_config: &ReserveConfig): u256 {
+ reserve_config.supply_cap
+ }
+
+ public fun get_borrow_cap(reserve_config: &ReserveConfig): u256 {
+ reserve_config.borrow_cap
+ }
+
+ public fun get_debt_ceiling(reserve_config: &ReserveConfig): u256 {
+ reserve_config.debt_ceiling
+ }
+
+ public fun get_borrowable_isolation(reserve_config: &ReserveConfig): bool {
+ reserve_config.borrowable_isolation
+ }
+
+ public fun get_siloed_borrowing(reserve_config: &ReserveConfig): bool {
+ reserve_config.siloed_borrowing
+ }
+
+ public fun get_emode_category(reserve_config: &ReserveConfig): Option {
+ reserve_config.emode_category
+ }
+
+ // TODO: add settings here per network
+ public fun build_emodes_testnet(): SmartTable {
+ let emodes = smart_table::new();
+ smart_table::add(
+ &mut emodes,
+ 1,
+ EmodeConfig {
+ category_id: 1,
+ ltv: 9000,
+ liquidation_threshold: 9300,
+ liquidation_bonus: 10200,
+ label: string::utf8(b"ETH Correlated")
+ }
+ );
+ smart_table::add(
+ &mut emodes,
+ 2,
+ EmodeConfig {
+ category_id: 2,
+ ltv: 9500,
+ liquidation_threshold: 9700,
+ liquidation_bonus: 10100,
+ label: string::utf8(b"Stablecoins")
+ }
+ );
+ emodes
+ }
+
+ // TODO: add settings here per network
+ public fun build_emodes_mainnet(): SmartTable {
+ let emodes = smart_table::new();
+ smart_table::add(
+ &mut emodes,
+ 1,
+ EmodeConfig {
+ category_id: 1,
+ ltv: 9000,
+ liquidation_threshold: 9300,
+ liquidation_bonus: 10200,
+ label: string::utf8(b"ETH Correlated")
+ }
+ );
+ smart_table::add(
+ &mut emodes,
+ 2,
+ EmodeConfig {
+ category_id: 2,
+ ltv: 9500,
+ liquidation_threshold: 9700,
+ liquidation_bonus: 10100,
+ label: string::utf8(b"Stablecoins")
+ }
+ );
+ emodes
+ }
+
+ // TODO: add feed id here per network
+ public fun build_price_feeds_testnet(): SmartTable> {
+ let price_feeds_testnet = smart_table::new>();
+ smart_table::add(
+ &mut price_feeds_testnet,
+ string::utf8(APT_ASSET),
+ x"011e22d6bf000332000000000000000000000000000000000000000000000000"
+ );
+ smart_table::add(
+ &mut price_feeds_testnet,
+ string::utf8(USDC_ASSET),
+ x"01a80ff216000332000000000000000000000000000000000000000000000000"
+ );
+ smart_table::add(
+ &mut price_feeds_testnet,
+ string::utf8(USDT_ASSET),
+ x"016d06ebb6000332000000000000000000000000000000000000000000000000"
+ );
+ smart_table::add(
+ &mut price_feeds_testnet,
+ string::utf8(AMAPT_ASSET),
+ x"01a0b4d920000332000000000000000000000000000000000000000000000000"
+ );
+ smart_table::add(
+ &mut price_feeds_testnet,
+ string::utf8(THAPT_ASSET),
+ x"01d585327c000332000000000000000000000000000000000000000000000000"
+ );
+ price_feeds_testnet
+ }
+
+ // TODO: add feed id here per network
+ public fun build_price_feeds_mainnet(): SmartTable> {
+ let price_feeds_mainnet = smart_table::new>();
+ smart_table::add(
+ &mut price_feeds_mainnet,
+ string::utf8(APT_ASSET),
+ x"011e22d6bf000332000000000000000000000000000000000000000000000000"
+ );
+ smart_table::add(
+ &mut price_feeds_mainnet,
+ string::utf8(USDC_ASSET),
+ x"01a80ff216000332000000000000000000000000000000000000000000000000"
+ );
+ smart_table::add(
+ &mut price_feeds_mainnet,
+ string::utf8(USDT_ASSET),
+ x"016d06ebb6000332000000000000000000000000000000000000000000000000"
+ );
+ smart_table::add(
+ &mut price_feeds_mainnet,
+ string::utf8(AMAPT_ASSET),
+ x"01a0b4d920000332000000000000000000000000000000000000000000000000"
+ );
+ smart_table::add(
+ &mut price_feeds_mainnet,
+ string::utf8(THAPT_ASSET),
+ x"01d585327c000332000000000000000000000000000000000000000000000000"
+ );
+ price_feeds_mainnet
+ }
+
+ // TODO: add address here per network
+ public fun build_underlying_assets_testnet(): SmartTable {
+ let apt_mapped_fa_asset = coin_migrator::get_fa_address();
+ let underlying_assets_testnet = smart_table::new();
+ smart_table::upsert(&mut underlying_assets_testnet, utf8(USDT_ASSET), @0x0);
+ smart_table::upsert(&mut underlying_assets_testnet, utf8(USDC_ASSET), @0x0);
+ smart_table::upsert(&mut underlying_assets_testnet, utf8(AMAPT_ASSET), @0x0);
+ smart_table::upsert(&mut underlying_assets_testnet, utf8(THAPT_ASSET), @0x0);
+ smart_table::upsert(
+ &mut underlying_assets_testnet, utf8(APT_ASSET), apt_mapped_fa_asset
+ );
+ underlying_assets_testnet
+ }
+
+ // TODO: add address here per network
+ public fun build_underlying_assets_mainnet(): SmartTable {
+ let apt_mapped_fa_asset = coin_migrator::get_fa_address();
+ let underlying_assets_mainnet = smart_table::new();
+ smart_table::upsert(&mut underlying_assets_mainnet, utf8(USDT_ASSET), @0x0);
+ smart_table::upsert(&mut underlying_assets_mainnet, utf8(USDC_ASSET), @0x0);
+ smart_table::upsert(&mut underlying_assets_mainnet, utf8(AMAPT_ASSET), @0x0);
+ smart_table::upsert(&mut underlying_assets_mainnet, utf8(THAPT_ASSET), @0x0);
+ smart_table::upsert(
+ &mut underlying_assets_mainnet, utf8(APT_ASSET), apt_mapped_fa_asset
+ );
+ underlying_assets_mainnet
+ }
+
+ // TODO: add data for each value
+ public fun build_reserve_config_testnet(): SmartTable {
+ let reserve_config = smart_table::new();
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(USDT_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(USDC_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(AMAPT_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(THAPT_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(APT_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ reserve_config
+ }
+
+ // TODO: add data for each value
+ public fun build_reserve_config_mainnet(): SmartTable {
+ let reserve_config = smart_table::new();
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(USDT_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(USDC_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(AMAPT_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(THAPT_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ smart_table::upsert(
+ &mut reserve_config,
+ utf8(APT_ASSET),
+ ReserveConfig {
+ base_ltv_as_collateral: 8000,
+ liquidation_threshold: 8500,
+ liquidation_bonus: 10500,
+ liquidation_protocol_fee: 1000,
+ borrowing_enabled: true,
+ flashLoan_enabled: true,
+ reserve_factor: 1000,
+ supply_cap: 0,
+ borrow_cap: 0,
+ debt_ceiling: 0,
+ borrowable_isolation: true,
+ siloed_borrowing: true,
+ emode_category: option::none()
+ }
+ );
+ reserve_config
+ }
+
+ // TODO: add data for each value
+ public fun build_interest_rate_strategy_mainnet():
+ SmartTable {
+ let interest_rate_config = smart_table::new();
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(USDT_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(USDC_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(AMAPT_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(THAPT_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(APT_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ interest_rate_config
+ }
+
+ // TODO: add data for each value
+ public fun build_interest_rate_strategy_testnet():
+ SmartTable {
+ let interest_rate_config = smart_table::new();
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(USDT_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(USDC_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(AMAPT_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(THAPT_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ smart_table::upsert(
+ &mut interest_rate_config,
+ utf8(APT_ASSET),
+ InterestRateStrategy {
+ optimal_usage_ratio: 800000000000000000000000000,
+ base_variable_borrow_rate: 0,
+ variable_rate_slope1: 40000000000000000000000000,
+ variable_rate_slope2: 750000000000000000000000000
+ }
+ );
+ interest_rate_config
+ }
+}
diff --git a/aave-core/aave-large-packages/Move.toml b/aave-core/aave-large-packages/Move.toml
index f7449a7..3eb7198 100644
--- a/aave-core/aave-large-packages/Move.toml
+++ b/aave-core/aave-large-packages/Move.toml
@@ -12,4 +12,4 @@ aave_large_packages = "_"
[dependencies]
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
+[dev-dependencies]
diff --git a/aave-core/aave-large-packages/sources/large_packages.move b/aave-core/aave-large-packages/sources/large_packages.move
index 611ca16..ca33abc 100644
--- a/aave-core/aave-large-packages/sources/large_packages.move
+++ b/aave-core/aave-large-packages/sources/large_packages.move
@@ -10,7 +10,6 @@
/// Any missing index in this range will cause the function to fail.
module aave_large_packages::large_packages {
use std::error;
- use std::option::{Self, Option};
use std::signer;
use std::vector;
use aptos_std::smart_table::{Self, SmartTable};
@@ -27,26 +26,36 @@ module aave_large_packages::large_packages {
struct StagingArea has key {
metadata_serialized: vector,
code: SmartTable>,
- last_module_idx: u64,
+ last_module_idx: u64
}
public entry fun stage_code_chunk(
owner: &signer,
metadata_chunk: vector,
code_indices: vector,
- code_chunks: vector>,
+ code_chunks: vector>
) acquires StagingArea {
- stage_code_chunk_internal(owner, metadata_chunk, code_indices, code_chunks);
+ stage_code_chunk_internal(
+ owner,
+ metadata_chunk,
+ code_indices,
+ code_chunks
+ );
}
public entry fun stage_code_chunk_and_publish_to_account(
owner: &signer,
metadata_chunk: vector,
code_indices: vector,
- code_chunks: vector>,
+ code_chunks: vector>
) acquires StagingArea {
let staging_area =
- stage_code_chunk_internal(owner, metadata_chunk, code_indices, code_chunks);
+ stage_code_chunk_internal(
+ owner,
+ metadata_chunk,
+ code_indices,
+ code_chunks
+ );
publish_to_account(owner, staging_area);
cleanup_staging_area(owner);
}
@@ -55,10 +64,15 @@ module aave_large_packages::large_packages {
owner: &signer,
metadata_chunk: vector,
code_indices: vector,
- code_chunks: vector>,
+ code_chunks: vector>
) acquires StagingArea {
let staging_area =
- stage_code_chunk_internal(owner, metadata_chunk, code_indices, code_chunks);
+ stage_code_chunk_internal(
+ owner,
+ metadata_chunk,
+ code_indices,
+ code_chunks
+ );
publish_to_object(owner, staging_area);
cleanup_staging_area(owner);
}
@@ -68,11 +82,16 @@ module aave_large_packages::large_packages {
metadata_chunk: vector,
code_indices: vector,
code_chunks: vector>,
- code_object: Option